コード例 #1
0
LTBOOL SURFACE::Init(CButeMgr & buteMgr, char* aTagName)
{
    if (!aTagName) return LTFALSE;

	eType					= (SurfaceType) buteMgr.GetInt(aTagName, SRFMGR_SURFACE_ID);
    bShowsMark              = (LTBOOL) buteMgr.GetInt(aTagName, SRFMGR_SURFACE_SHOWSMARK);
    bCanSeeThrough          = (LTBOOL) buteMgr.GetInt(aTagName, SRFMGR_SURFACE_CANSEETHROUGH);
    bCanShootThrough        = (LTBOOL) buteMgr.GetInt(aTagName, SRFMGR_SURFACE_CANSHOOTTHROUGH);
    bShowBreath             = (LTBOOL) buteMgr.GetInt(aTagName, SRFMGR_SURFACE_SHOWBREATH);
	nMaxShootThroughPerturb	= buteMgr.GetInt(aTagName, SRFMGR_SURFACE_MAXSHOOTTHROUGHPERTURB);
	nMaxShootThroughThickness= buteMgr.GetInt(aTagName, SRFMGR_SURFACE_MAXSHOOTTHROUGHTHICKNESS);
    fDeathNoiseModifier     = (LTFLOAT) buteMgr.GetDouble(aTagName, SRFMGR_SURFACE_DEATHNOISEMOD);
    fMovementNoiseModifier  = (LTFLOAT) buteMgr.GetDouble(aTagName, SRFMGR_SURFACE_MOVENOISEMOD);
    fImpactNoiseModifier    = (LTFLOAT) buteMgr.GetDouble(aTagName, SRFMGR_SURFACE_IMPACTNOISEMOD);
    fBodyFallSndRadius      = (LTFLOAT) buteMgr.GetDouble(aTagName, SRFMGR_SURFACE_BODYFALLSNDRADIUS);
    fBodyLedgeFallSndRadius = (LTFLOAT) buteMgr.GetDouble(aTagName, SRFMGR_SURFACE_BODYLEDGEFALLSNDRADIUS);
    fBulletHoleMinScale     = (LTFLOAT) buteMgr.GetDouble(aTagName, SRFMGR_SURFACE_BULLETHOLEMINSCALE);
    fBulletHoleMaxScale     = (LTFLOAT) buteMgr.GetDouble(aTagName, SRFMGR_SURFACE_BULLETHOLEMAXSCALE);
    fBulletRangeDampen      = (LTFLOAT) buteMgr.GetDouble(aTagName, SRFMGR_SURFACE_BULLETRANGEDAMPEN);
    fBulletDamageDampen     = (LTFLOAT) buteMgr.GetDouble(aTagName, SRFMGR_SURFACE_BULLETDAMAGEDAMPEN);
    fActivationSndRadius    = (LTFLOAT) buteMgr.GetDouble(aTagName, SRFMGR_SURFACE_ACTIVATIONSNDRADIUS);
    fShellSndRadius         = (LTFLOAT) buteMgr.GetDouble(aTagName, SRFMGR_SURFACE_SHELLSNDRADIUS);
    fGrenadeSndRadius       = (LTFLOAT) buteMgr.GetDouble(aTagName, SRFMGR_SURFACE_GRENADESNDRADIUS);
    fHardness               = (LTFLOAT) buteMgr.GetDouble(aTagName, SRFMGR_SURFACE_HARDNESS);
    fFootPrintLifetime      = (LTFLOAT) buteMgr.GetDouble(aTagName, SRFMGR_SURFACE_FOOTPRINTLIFETIME);
    fMotoVelMult			= (LTFLOAT) buteMgr.GetDouble(aTagName, SRFMGR_SURFACE_MOTOVELMULTIPLIER);
    fSnowVelMult			= (LTFLOAT) buteMgr.GetDouble(aTagName, SRFMGR_SURFACE_SNOWVELMULTIPLIER);
    bMagnetic               = (LTBOOL) buteMgr.GetInt(aTagName, SRFMGR_SURFACE_MAGNETIC);

	vFootPrintScale			= buteMgr.GetVector(aTagName, SRFMGR_SURFACE_FOOTPRINTSCALE);

	CString str = buteMgr.GetString(aTagName, SRFMGR_SURFACE_NAME);
	if (!str.IsEmpty())
	{
		strncpy(szName, (char*)(LPCSTR)str, ARRAY_LEN(szName));
	}

	str = buteMgr.GetString(aTagName, SRFMGR_SURFACE_BULLETHOLESPR);
	if (!str.IsEmpty())
	{
		strncpy(szBulletHoleSpr, (char*)(LPCSTR)str, ARRAY_LEN(szBulletHoleSpr));
	}

	str = buteMgr.GetString(aTagName, SRFMGR_SURFACE_RTFOOTPRINTSPR);
	if (!str.IsEmpty())
	{
		strncpy(szRtFootPrintSpr, (char*)(LPCSTR)str, ARRAY_LEN(szRtFootPrintSpr));
	}

	str = buteMgr.GetString(aTagName, SRFMGR_SURFACE_LTFOOTPRINTSPR);
	if (!str.IsEmpty())
	{
		strncpy(szLtFootPrintSpr, (char*)(LPCSTR)str, ARRAY_LEN(szLtFootPrintSpr));
	}

    int i;
    for (i=1; i <= SRF_MAX_FOOTSTEP_SNDS; i++)
	{
		sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_RTFOOTSND, i);
		str = buteMgr.GetString(aTagName, s_aAttName);

		if (!str.IsEmpty())
		{
			strncpy(szRtFootStepSnds[i-1], (char*)(LPCSTR)str, ARRAY_LEN(szRtFootStepSnds[i-1]));
		}
	}

	for (i=1; i <= SRF_MAX_FOOTSTEP_SNDS; i++)
	{
		sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_LTFOOTSND, i);
		str = buteMgr.GetString(aTagName, s_aAttName);

		if (!str.IsEmpty())
		{
			strncpy(szLtFootStepSnds[i-1], (char*)(LPCSTR)str, ARRAY_LEN(szLtFootStepSnds[i-1]));
		}
	}

	for (i=1; i <= SRF_MAX_MOTORCYCLE_SNDS; i++)
	{
		sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_MOTORCYCLESND, i);
		str = buteMgr.GetString(aTagName, s_aAttName);

		if (!str.IsEmpty())
		{
			strncpy(szMotorcycleSnds[i-1], (char*)(LPCSTR)str, ARRAY_LEN(szMotorcycleSnds[i-1]));
		}
	}

	for (i=1; i <= SRF_MAX_SNOWMOBILE_SNDS; i++)
	{
		sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_SNOWMOBILESND, i);
		str = buteMgr.GetString(aTagName, s_aAttName);

		if (!str.IsEmpty())
		{
			strncpy(szSnowmobileSnds[i-1], (char*)(LPCSTR)str, ARRAY_LEN(szSnowmobileSnds[i-1]));
		}
	}

	str = buteMgr.GetString(aTagName, SRFMGR_SURFACE_BODYFALLSND);
	if (!str.IsEmpty())
	{
		strncpy(szBodyFallSnd, (char*)(LPCSTR)str, ARRAY_LEN(szBodyFallSnd));
	}

	str = buteMgr.GetString(aTagName, SRFMGR_SURFACE_BODYLEDGEFALLSND);
	if (!str.IsEmpty())
	{
		strncpy(szBodyLedgeFallSnd, (char*)(LPCSTR)str, ARRAY_LEN(szBodyLedgeFallSnd));
	}

	str = buteMgr.GetString(aTagName, SRFMGR_SURFACE_ACTIVATIONSND);
	if (!str.IsEmpty())
	{
		strncpy(szActivationSnd, (char*)(LPCSTR)str, ARRAY_LEN(szActivationSnd));
	}

	str = buteMgr.GetString(aTagName, SRFMGR_SURFACE_GRENADEIMPACTSND);
	if (!str.IsEmpty())
	{
		strncpy(szGrenadeImpactSnd, (char*)(LPCSTR)str, ARRAY_LEN(szGrenadeImpactSnd));
	}

	for (i=1; i <= SRF_MAX_IMPACT_SNDS; i++)
	{
		sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_BULLETIMPACTSND, i);
		str = buteMgr.GetString(aTagName, s_aAttName);

		if (!str.IsEmpty())
		{
			strncpy(szBulletImpactSnds[i-1], (char*)(LPCSTR)str, ARRAY_LEN(szBulletImpactSnds[i-1]));
		}
	}

	for (i=1; i <= SRF_MAX_IMPACT_SNDS; i++)
	{
		sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_PROJIMPACTSND, i);
		str = buteMgr.GetString(aTagName, s_aAttName);

		if (!str.IsEmpty())
		{
			strncpy(szProjectileImpactSnds[i-1], (char*)(LPCSTR)str, ARRAY_LEN(szProjectileImpactSnds[i-1]));
		}
	}

	for (i=1; i <= SRF_MAX_IMPACT_SNDS; i++)
	{
		sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_MELEEIMPACTSND, i);
		str = buteMgr.GetString(aTagName, s_aAttName);

		if (!str.IsEmpty())
		{
			strncpy(szMeleeImpactSnds[i-1], (char*)(LPCSTR)str, ARRAY_LEN(szMeleeImpactSnds[i-1]));
		}
	}

	for (i=1; i <= SRF_MAX_SHELL_SNDS; i++)
	{
		sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_SHELLIMPACTSND, i);
		str = buteMgr.GetString(aTagName, s_aAttName);

		if (!str.IsEmpty())
		{
			strncpy(szShellImpactSnds[i-1], (char*)(LPCSTR)str, ARRAY_LEN(szShellImpactSnds[i-1]));
		}
	}

	// Impact specific scale fx...

	// Build our impact scale fx id list...

	nNumImpactScaleFX = 0;
	sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_IMPACTSCALENAME, nNumImpactScaleFX);

	while (buteMgr.Exist(aTagName, s_aAttName) && nNumImpactScaleFX < SRF_MAX_IMPACT_SCALEFX)
	{
		str = buteMgr.GetString(aTagName, s_aAttName);
		if (!str.IsEmpty())
		{
			CScaleFX* pScaleFX = g_pFXButeMgr->GetScaleFX((char*)(LPCSTR)str);
			if (pScaleFX)
			{
				aImpactScaleFXIds[nNumImpactScaleFX] = pScaleFX->nId;
			}
		}

		nNumImpactScaleFX++;
		sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_IMPACTSCALENAME, nNumImpactScaleFX);
	}

	// Build our impact particle shower fx id list...

	nNumImpactPShowerFX = 0;
	sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_IMPACTPSHOWERNAME, nNumImpactPShowerFX);

	while (buteMgr.Exist(aTagName, s_aAttName) && nNumImpactPShowerFX < SRF_MAX_IMPACT_PSHOWERFX)
	{
		str = buteMgr.GetString(aTagName, s_aAttName);
		if (!str.IsEmpty())
		{
			CPShowerFX* pPShowerFX = g_pFXButeMgr->GetPShowerFX((char*)(LPCSTR)str);
			if (pPShowerFX)
			{
				aImpactPShowerFXIds[nNumImpactPShowerFX] = pPShowerFX->nId;
			}
		}

		nNumImpactPShowerFX++;
		sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_IMPACTPSHOWERNAME, nNumImpactPShowerFX);
	}

	// Build our impact poly debris fx id list...

	nNumImpactPolyDebrisFX = 0;
	sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_IMPACTPOLYDEBRISNAME, nNumImpactPolyDebrisFX);

	while (buteMgr.Exist(aTagName, s_aAttName) && nNumImpactPolyDebrisFX < SRF_MAX_IMPACT_PSHOWERFX)
	{
		str = buteMgr.GetString(aTagName, s_aAttName);
		if (!str.IsEmpty())
		{
			CPolyDebrisFX* pPolyDebrisFX = g_pFXButeMgr->GetPolyDebrisFX((char*)(LPCSTR)str);
			if (pPolyDebrisFX)
			{
				aImpactPolyDebrisFXIds[nNumImpactPolyDebrisFX] = pPolyDebrisFX->nId;
			}
		}

		nNumImpactPolyDebrisFX++;
		sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_IMPACTPOLYDEBRISNAME, nNumImpactPolyDebrisFX);
	}

	// Build our under water impact particle shower fx id list...


	nNumUWImpactPShowerFX = 0;
	sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_UWIMPACTPSHOWERNAME, nNumUWImpactPShowerFX);

	while (buteMgr.Exist(aTagName, s_aAttName) && nNumUWImpactPShowerFX < SRF_MAX_IMPACT_PSHOWERFX)
	{
		str = buteMgr.GetString(aTagName, s_aAttName);
		if (!str.IsEmpty())
		{
			CPShowerFX* pPShowerFX = g_pFXButeMgr->GetPShowerFX((char*)(LPCSTR)str);
			if (pPShowerFX)
			{
				aUWImpactPShowerFXIds[nNumUWImpactPShowerFX] = pPShowerFX->nId;
			}
		}

		nNumUWImpactPShowerFX++;
		sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_UWIMPACTPSHOWERNAME, nNumUWImpactPShowerFX);
	}



	// Exit specific scale fx...

	// Build our exit scale fx id list...

	nNumExitScaleFX = 0;
	sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_EXITSCALENAME, nNumExitScaleFX);

	while (buteMgr.Exist(aTagName, s_aAttName) && nNumExitScaleFX < SRF_MAX_IMPACT_SCALEFX)
	{
		str = buteMgr.GetString(aTagName, s_aAttName);
		if (!str.IsEmpty())
		{
			CScaleFX* pScaleFX = g_pFXButeMgr->GetScaleFX((char*)(LPCSTR)str);
			if (pScaleFX)
			{
				aExitScaleFXIds[nNumExitScaleFX]  = pScaleFX->nId;
			}
		}

		nNumExitScaleFX++;
		sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_EXITSCALENAME, nNumExitScaleFX);
	}

	// Build our exit particle shower fx id list...

	nNumExitPShowerFX = 0;
	sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_EXITPSHOWERNAME, nNumExitPShowerFX);

	while (buteMgr.Exist(aTagName, s_aAttName) && nNumExitPShowerFX < SRF_MAX_IMPACT_PSHOWERFX)
	{
		str = buteMgr.GetString(aTagName, s_aAttName);
		if (!str.IsEmpty())
		{
			CPShowerFX* pPShowerFX = g_pFXButeMgr->GetPShowerFX((char*)(LPCSTR)str);
			if (pPShowerFX)
			{
				aExitPShowerFXIds[nNumExitPShowerFX] = pPShowerFX->nId;
			}
		}

		nNumExitPShowerFX++;
		sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_EXITPSHOWERNAME, nNumExitPShowerFX);
	}

	// Build our exit poly debris fx id list...

	nNumExitPolyDebrisFX = 0;
	sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_EXITPOLYDEBRISNAME, nNumExitPolyDebrisFX);

	while (buteMgr.Exist(aTagName, s_aAttName) && nNumExitPolyDebrisFX < SRF_MAX_IMPACT_PSHOWERFX)
	{
		str = buteMgr.GetString(aTagName, s_aAttName);
		if (!str.IsEmpty())
		{
			CPolyDebrisFX* pPolyDebrisFX = g_pFXButeMgr->GetPolyDebrisFX((char*)(LPCSTR)str);
			if (pPolyDebrisFX)
			{
				aExitPolyDebrisFXIds[nNumExitPolyDebrisFX] = pPolyDebrisFX->nId;
			}
		}

		nNumExitPolyDebrisFX++;
		sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_EXITPOLYDEBRISNAME, nNumExitPolyDebrisFX);
	}

	// Build our under water exit particle shower fx id list...

	nNumUWExitPShowerFX = 0;
	sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_UWIMPACTPSHOWERNAME, nNumUWExitPShowerFX);

	while (buteMgr.Exist(aTagName, s_aAttName) && nNumUWExitPShowerFX < SRF_MAX_IMPACT_PSHOWERFX)
	{
		str = buteMgr.GetString(aTagName, s_aAttName);
		if (!str.IsEmpty())
		{
			CPShowerFX* pPShowerFX = g_pFXButeMgr->GetPShowerFX((char*)(LPCSTR)str);
			if (pPShowerFX)
			{
				aUWExitPShowerFXIds[nNumUWExitPShowerFX] = pPShowerFX->nId;
			}
		}

		nNumUWExitPShowerFX++;
		sprintf(s_aAttName, "%s%d", SRFMGR_SURFACE_UWIMPACTPSHOWERNAME, nNumUWExitPShowerFX);
	}

    return LTTRUE;
}
コード例 #2
0
ファイル: res_ari_asterisk.c プロジェクト: lyx2014/Asterisk
/*!
 * \brief Parameter parsing callback for /asterisk/info.
 * \param get_params GET parameters in the HTTP request.
 * \param path_vars Path variables extracted from the request.
 * \param headers HTTP headers.
 * \param[out] response Response to the HTTP request.
 */
static void ast_ari_asterisk_get_info_cb(
	struct ast_tcptls_session_instance *ser,
	struct ast_variable *get_params, struct ast_variable *path_vars,
	struct ast_variable *headers, struct ast_ari_response *response)
{
	struct ast_ari_asterisk_get_info_args args = {};
	struct ast_variable *i;
	RAII_VAR(struct ast_json *, body, NULL, ast_json_unref);
#if defined(AST_DEVMODE)
	int is_valid;
	int code;
#endif /* AST_DEVMODE */

	for (i = get_params; i; i = i->next) {
		if (strcmp(i->name, "only") == 0) {
			/* Parse comma separated list */
			char *vals[MAX_VALS];
			size_t j;

			args.only_parse = ast_strdup(i->value);
			if (!args.only_parse) {
				ast_ari_response_alloc_failed(response);
				goto fin;
			}

			if (strlen(args.only_parse) == 0) {
				/* ast_app_separate_args can't handle "" */
				args.only_count = 1;
				vals[0] = args.only_parse;
			} else {
				args.only_count = ast_app_separate_args(
					args.only_parse, ',', vals,
					ARRAY_LEN(vals));
			}

			if (args.only_count == 0) {
				ast_ari_response_alloc_failed(response);
				goto fin;
			}

			if (args.only_count >= MAX_VALS) {
				ast_ari_response_error(response, 400,
					"Bad Request",
					"Too many values for only");
				goto fin;
			}

			args.only = ast_malloc(sizeof(*args.only) * args.only_count);
			if (!args.only) {
				ast_ari_response_alloc_failed(response);
				goto fin;
			}

			for (j = 0; j < args.only_count; ++j) {
				args.only[j] = (vals[j]);
			}
		} else
		{}
	}
	/* Look for a JSON request entity */
	body = ast_http_get_json(ser, headers);
	if (!body) {
		switch (errno) {
		case EFBIG:
			ast_ari_response_error(response, 413, "Request Entity Too Large", "Request body too large");
			goto fin;
		case ENOMEM:
			ast_ari_response_error(response, 500, "Internal Server Error", "Error processing request");
			goto fin;
		case EIO:
			ast_ari_response_error(response, 400, "Bad Request", "Error parsing request body");
			goto fin;
		}
	}
	if (ast_ari_asterisk_get_info_parse_body(body, &args)) {
		ast_ari_response_alloc_failed(response);
		goto fin;
	}
	ast_ari_asterisk_get_info(headers, &args, response);
#if defined(AST_DEVMODE)
	code = response->response_code;

	switch (code) {
	case 0: /* Implementation is still a stub, or the code wasn't set */
		is_valid = response->message == NULL;
		break;
	case 500: /* Internal Server Error */
	case 501: /* Not Implemented */
		is_valid = 1;
		break;
	default:
		if (200 <= code && code <= 299) {
			is_valid = ast_ari_validate_asterisk_info(
				response->message);
		} else {
			ast_log(LOG_ERROR, "Invalid error response %d for /asterisk/info\n", code);
			is_valid = 0;
		}
	}

	if (!is_valid) {
		ast_log(LOG_ERROR, "Response validation failed for /asterisk/info\n");
		ast_ari_response_error(response, 500,
			"Internal Server Error", "Response validation failed");
	}
#endif /* AST_DEVMODE */

fin: __attribute__((unused))
	ast_free(args.only_parse);
	ast_free(args.only);
	return;
}
コード例 #3
0
/*! \brief Parse DNS NAPTR record used in ENUM ---*/
static int parse_naptr(unsigned char *dst, int dstsize, char *tech, int techsize, unsigned char *answer, int len, unsigned char *naptrinput)
{
	char tech_return[80];
	char *oanswer = (char *)answer;
	char flags[512] = "";
	char services[512] = "";
	char *p;
	char regexp[512] = "";
	char repl[512] = "";
	char tempdst[512] = "";
	char errbuff[512] = "";
	char delim;
	char *delim2;
	char *pattern, *subst, *d;
	int res;
	int regexp_len, rc;
	static const int max_bt = 10; /* max num of regexp backreference allowed, must remain 10 to guarantee a valid backreference index */
	int size, matchindex; /* size is the size of the backreference sub. */
	size_t d_len = sizeof(tempdst) - 1;
	regex_t preg;
	regmatch_t pmatch[max_bt];

	tech_return[0] = '\0';
	dst[0] = '\0';

	if (len < sizeof(struct naptr)) {
		ast_log(LOG_WARNING, "NAPTR record length too short\n");
		return -1;
	}
	answer += sizeof(struct naptr);
	len -= sizeof(struct naptr);
	if ((res = parse_ie(flags, sizeof(flags) - 1, answer, len)) < 0) {
		ast_log(LOG_WARNING, "Failed to get flags from NAPTR record\n");
		return -1;
	} else {
		answer += res;
		len -= res;
	}

	if ((res = parse_ie(services, sizeof(services) - 1, answer, len)) < 0) {
		ast_log(LOG_WARNING, "Failed to get services from NAPTR record\n");
		return -1;
	} else {
		answer += res;
		len -= res;
	}
	if ((res = parse_ie(regexp, sizeof(regexp) - 1, answer, len)) < 0) {
		ast_log(LOG_WARNING, "Failed to get regexp from NAPTR record\n");
		return -1;
	} else {
		answer += res;
		len -= res;
	}

	if ((res = dn_expand((unsigned char *)oanswer, (unsigned char *)answer + len, (unsigned char *)answer, repl, sizeof(repl) - 1)) < 0) {
		ast_log(LOG_WARNING, "Failed to expand hostname\n");
		return -1;
	}

	ast_debug(3, "NAPTR input='%s', flags='%s', services='%s', regexp='%s', repl='%s'\n",
		naptrinput, flags, services, regexp, repl);


	if (tolower(flags[0]) != 'u') {
		ast_log(LOG_WARNING, "NAPTR Flag must be 'U' or 'u'.\n");
		return -1;
	}

	p = strstr(services, "e2u+");
	if (p == NULL)
		p = strstr(services, "E2U+");
	if (p){
		p = p + 4;
		if (strchr(p, ':')){
			p = strchr(p, ':') + 1;
		}
		ast_copy_string(tech_return, p, sizeof(tech_return));
	} else {

		p = strstr(services, "+e2u");
		if (p == NULL)
			p = strstr(services, "+E2U");
		if (p) {
			*p = 0;
			p = strchr(services, ':');
			if (p)
				*p = 0;
			ast_copy_string(tech_return, services, sizeof(tech_return));
		}
	}

	regexp_len = strlen(regexp);
	if (regexp_len < 7) {
		ast_log(LOG_WARNING, "Regex too short to be meaningful.\n");
		return -1;
	}

	/* this takes the first character of the regexp (which is a delimiter)
	 * and uses that character to find the index of the second delimiter */
	delim = regexp[0];
	delim2 = strchr(regexp + 1, delim);
	if ((delim2 == NULL) || (regexp[regexp_len - 1] != delim)) {  /* is the second delimiter found, and is the end of the regexp a delimiter */
		ast_log(LOG_WARNING, "Regex delimiter error (on \"%s\").\n", regexp);
		return -1;
	} else if (strchr((delim2 + 1), delim) == NULL) { /* if the second delimiter is found, make sure there is a third instance.  this could be the end one instead of the middle */
		ast_log(LOG_WARNING, "Regex delimiter error (on \"%s\").\n", regexp);
		return -1;
	}
	pattern = regexp + 1;   /* pattern is the regex without the begining and ending delimiter */
	*delim2 = 0;    /* zero out the middle delimiter */
	subst   = delim2 + 1; /* dst substring is everything after the second delimiter. */
	regexp[regexp_len - 1] = 0; /* zero out the last delimiter */

/*
 * now do the regex wizardry.
 */

	if (regcomp(&preg, pattern, REG_EXTENDED | REG_NEWLINE)) {
		ast_log(LOG_WARNING, "NAPTR Regex compilation error (regex = \"%s\").\n", regexp);
		return -1;
	}

	if (preg.re_nsub > ARRAY_LEN(pmatch)) {
		ast_log(LOG_WARNING, "NAPTR Regex compilation error: too many subs.\n");
		regfree(&preg);
		return -1;
	}
	/* pmatch is an array containing the substring indexes for the regex backreference sub.
	 * max_bt is the maximum number of backreferences allowed to be stored in pmatch */
	if ((rc = regexec(&preg, (char *) naptrinput, max_bt, pmatch, 0))) {
		regerror(rc, &preg, errbuff, sizeof(errbuff));
		ast_log(LOG_WARNING, "NAPTR Regex match failed. Reason: %s\n", errbuff);
		regfree(&preg);
		return -1;
	}
	regfree(&preg);

	d = tempdst;
	d_len--;

	/* perform the backreference sub. Search the subst for backreferences,
	 * when a backreference is found, retrieve the backreferences number.
	 * use the backreference number as an index for pmatch to retrieve the
	 * beginning and ending indexes of the substring to insert as the backreference.
	 * if no backreference is found, continue copying the subst into tempdst */
	while (*subst && (d_len > 0)) {
		if ((subst[0] == '\\') && isdigit(subst[1])) { /* is this character the beginning of a backreference */
			matchindex = (int) (subst[1] - '0');
			if (matchindex >= ARRAY_LEN(pmatch)) {
				ast_log(LOG_WARNING, "Error during regex substitution. Invalid pmatch index.\n");
				return -1;
			}
			/* pmatch len is 10. we are garanteed a single char 0-9 is a valid index */
			size = pmatch[matchindex].rm_eo - pmatch[matchindex].rm_so;
			if (size > d_len) {
				ast_log(LOG_WARNING, "Not enough space during NAPTR regex substitution.\n");
				return -1;
			}
			/* are the pmatch indexes valid for the input length */
			if ((strlen((char *) naptrinput) >= pmatch[matchindex].rm_eo) && (pmatch[matchindex].rm_so <= pmatch[matchindex].rm_eo)) {
				memcpy(d, (naptrinput + (int) pmatch[matchindex].rm_so), size);  /* copy input substring into backreference marker */
				d_len -= size;
				subst += 2;  /* skip over backreference characters to next valid character */
				d += size;
			} else {
				ast_log(LOG_WARNING, "Error during regex substitution. Invalid backreference index.\n");
				return -1;
			}
		} else if (isprint(*subst)) {
			*d++ = *subst++;
			d_len--;
		} else {
			ast_log(LOG_WARNING, "Error during regex substitution.\n");
			return -1;
		}
	}
	*d = 0;
	ast_copy_string((char *) dst, tempdst, dstsize);
	dst[dstsize - 1] = '\0';

	if (*tech != '\0'){ /* check if it is requested NAPTR */
		if (!strncasecmp(tech, "ALL", techsize)){
			return 0; /* return or count any RR */
		}
		if (!strncasecmp(tech_return, tech, sizeof(tech_return) < techsize ? sizeof(tech_return): techsize)){
			ast_copy_string(tech, tech_return, techsize);
			return 0; /* we got our RR */
		} else { /* go to the next RR in the DNS answer */
			return 1;
		}
	}

	/* tech was not specified, return first parsed RR */
	ast_copy_string(tech, tech_return, techsize);

	return 0;
}
コード例 #4
0
ファイル: callback_test.c プロジェクト: hownam/fennec
static void
callback_test (int converter, double src_ratio)
{	static TEST_CB_DATA test_callback_data ;
	static float output [BUFFER_LEN] ;

	SRC_STATE	*src_state ;

	long	read_count, read_total ;
	int 	input_len, output_len, error ;

	printf ("\tcallback_test    (SRC ratio = %6.4f) ........... ", src_ratio) ;
	fflush (stdout) ;

	/* Calculate maximun input and output lengths. */
	if (src_ratio >= 1.0)
	{	output_len = BUFFER_LEN ;
		input_len = (int) floor (BUFFER_LEN / src_ratio) ;
		}
	else
	{	input_len = BUFFER_LEN ;
		output_len = (int) floor (BUFFER_LEN * src_ratio) ;
		} ;

	/* Reduce input_len by 10 so output is longer than necessary. */
	input_len -= 10 ;

	if (output_len > BUFFER_LEN)
	{	printf ("\n\nLine %d : output_len > BUFFER_LEN\n\n", __LINE__) ;
		exit (1) ;
		} ;

	test_callback_data.channels = 1 ;
	test_callback_data.count = 0 ;
	test_callback_data.total = input_len ;

	if ((src_state = src_callback_new (test_callback_func, converter, 1, &error, &test_callback_data)) == NULL)
	{	printf ("\n\nLine %d : %s\n\n", __LINE__, src_strerror (error)) ;
		exit (1) ;
		} ;

	read_total = 0 ;
	do
	{	read_count = (ARRAY_LEN (output) - read_total > CB_READ_LEN) ? CB_READ_LEN : ARRAY_LEN (output) - read_total ;
		read_count = src_callback_read (src_state, src_ratio, read_count, output + read_total) ;
		read_total += read_count ;
		}
	while (read_count > 0) ;

	if ((error = src_error (src_state)) != 0)
	{	printf ("\n\nLine %d : %s\n\n", __LINE__, src_strerror (error)) ;
		exit (1) ;
		} ;

	src_state = src_delete (src_state) ;

	if (fabs (read_total - src_ratio * input_len) > 2)
	{	printf ("\n\nLine %d : input / output length mismatch.\n\n", __LINE__) ;
		printf ("    input len  : %d\n", input_len) ;
		printf ("    output len : %ld (should be %g +/- 2)\n\n", read_total, floor (0.5 + src_ratio * input_len)) ;
		exit (1) ;
		} ;

	puts ("ok") ;

	return ;
} /* callback_test */
コード例 #5
0
ファイル: cg_servercmds.c プロジェクト: Wookiee-/jaPRO
static void CG_ConfigStringModified( void ) {
	const char	*str;
	int		num;

	num = atoi( CG_Argv( 1 ) );

	// get the gamestate from the client system, which will have the
	// new configstring already integrated
	trap->GetGameState( &cgs.gameState );

	// look up the individual string that was modified
	str = CG_ConfigString( num );

	// do something with it if necessary
	if ( num == CS_MUSIC ) {
		CG_StartMusic( qtrue );
	} else if ( num == CS_SERVERINFO ) {
		CG_ParseServerinfo();
	} else if ( num == CS_WARMUP ) {
		CG_ParseWarmup();
	} else if ( num == CS_SCORES1 ) {
		cgs.scores1 = atoi( str );
	} else if ( num == CS_SCORES2 ) {
		cgs.scores2 = atoi( str );
	} else if ( num == CS_CLIENT_JEDIMASTER ) {
		cgs.jediMaster = atoi ( str );
	}
	else if ( num == CS_CLIENT_DUELWINNER )
	{
		cgs.duelWinner = atoi ( str );
	}
	else if ( num == CS_CLIENT_DUELISTS )
	{
		char buf[64];
		int c = 0;
		int i = 0;

		while (str[i] && str[i] != '|')
		{
			buf[c] = str[i];
			c++;
			i++;
		}
		buf[c] = 0;

		cgs.duelist1 = atoi ( buf );
		c = 0;

		i++;
		while (str[i] && str[i] != '|')
		{
			buf[c] = str[i];
			c++;
			i++;
		}
		buf[c] = 0;

		cgs.duelist2 = atoi ( buf );

		if (str[i])
		{
			c = 0;
			i++;

			while (str[i])
			{
				buf[c] = str[i];
				c++;
				i++;
			}
			buf[c] = 0;

			cgs.duelist3 = atoi(buf);
		}
	}
	else if ( num == CS_CLIENT_DUELHEALTHS ) {	// nmckenzie: DUEL_HEALTH
		SetDuelistHealthsFromConfigString(str);
	}
	else if ( num == CS_LEVEL_START_TIME ) {
		cgs.levelStartTime = atoi( str );
	} else if ( num == CS_VOTE_TIME ) {
		cgs.voteTime = atoi( str );
		cgs.voteModified = qtrue;
	} else if ( num == CS_VOTE_YES ) {
		cgs.voteYes = atoi( str );
		cgs.voteModified = qtrue;
	} else if ( num == CS_VOTE_NO ) {
		cgs.voteNo = atoi( str );
		cgs.voteModified = qtrue;
	} else if ( num == CS_VOTE_STRING ) {
		Q_strncpyz( cgs.voteString, str, sizeof( cgs.voteString ) );
	} else if ( num >= CS_TEAMVOTE_TIME && num <= CS_TEAMVOTE_TIME + 1) {
		cgs.teamVoteTime[num-CS_TEAMVOTE_TIME] = atoi( str );
		cgs.teamVoteModified[num-CS_TEAMVOTE_TIME] = qtrue;
	} else if ( num >= CS_TEAMVOTE_YES && num <= CS_TEAMVOTE_YES + 1) {
		cgs.teamVoteYes[num-CS_TEAMVOTE_YES] = atoi( str );
		cgs.teamVoteModified[num-CS_TEAMVOTE_YES] = qtrue;
	} else if ( num >= CS_TEAMVOTE_NO && num <= CS_TEAMVOTE_NO + 1) {
		cgs.teamVoteNo[num-CS_TEAMVOTE_NO] = atoi( str );
		cgs.teamVoteModified[num-CS_TEAMVOTE_NO] = qtrue;
	} else if ( num >= CS_TEAMVOTE_STRING && num <= CS_TEAMVOTE_STRING + 1) {
		Q_strncpyz( cgs.teamVoteString[num-CS_TEAMVOTE_STRING], str, sizeof( cgs.teamVoteString ) );
	} else if ( num == CS_INTERMISSION ) {
		cg.intermissionStarted = atoi( str );
	} else if ( num >= CS_MODELS && num < CS_MODELS+MAX_MODELS ) {
		char modelName[MAX_QPATH];
		strcpy(modelName, str);
		if (strstr(modelName, ".glm") || modelName[0] == '$')
		{ //Check to see if it has a custom skin attached.
			CG_HandleAppendedSkin(modelName);
			CG_CacheG2AnimInfo(modelName);
		}

		if (modelName[0] != '$' && modelName[0] != '@')
		{ //don't register vehicle names and saber names as models.
			cgs.gameModels[ num-CS_MODELS ] = trap->R_RegisterModel( modelName );
		}
		else
		{
            cgs.gameModels[ num-CS_MODELS ] = 0;
		}
// GHOUL2 Insert start
		/*
	} else if ( num >= CS_CHARSKINS && num < CS_CHARSKINS+MAX_CHARSKINS ) {
		cgs.skins[ num-CS_CHARSKINS ] = trap->R_RegisterSkin( str );
		*/
		//rww - removed and replaced with CS_G2BONES
// Ghoul2 Insert end
	} else if ( num >= CS_SOUNDS && num < CS_SOUNDS+MAX_SOUNDS ) {
		if ( str[0] != '*' ) {	// player specific sounds don't register here
			cgs.gameSounds[ num-CS_SOUNDS] = trap->S_RegisterSound( str );
		}
		else if (str[1] == '$')
		{ //an NPC soundset
			CG_PrecacheNPCSounds(str);
		}
	} else if ( num >= CS_EFFECTS && num < CS_EFFECTS+MAX_FX ) {
		if (str[0] == '*')
		{ //it's a special global weather effect
			CG_ParseWeatherEffect(str);
			cgs.gameEffects[ num-CS_EFFECTS] = 0;
		}
		else
		{
			cgs.gameEffects[ num-CS_EFFECTS] = trap->FX_RegisterEffect( str );
		}
	}
	else if ( num >= CS_SIEGE_STATE && num < CS_SIEGE_STATE+1 )
	{
		if (str[0])
		{
			CG_ParseSiegeState(str);
		}
	}
	else if ( num >= CS_SIEGE_WINTEAM && num < CS_SIEGE_WINTEAM+1 )
	{
		if (str[0])
		{
			cg_siegeWinTeam = atoi(str);
		}
	}
	else if ( num >= CS_SIEGE_OBJECTIVES && num < CS_SIEGE_OBJECTIVES+1 )
	{
		CG_ParseSiegeObjectiveStatus(str);
	}
	else if (num >= CS_SIEGE_TIMEOVERRIDE && num < CS_SIEGE_TIMEOVERRIDE+1)
	{
		cg_beatingSiegeTime = atoi(str);
		CG_SetSiegeTimerCvar ( cg_beatingSiegeTime );
	}
	else if ( num >= CS_PLAYERS && num < CS_PLAYERS+MAX_CLIENTS )
	{
		CG_NewClientInfo( num - CS_PLAYERS, qtrue);
		CG_BuildSpectatorString();
	} else if ( num == CS_FLAGSTATUS ) {
		if( cgs.gametype == GT_CTF || cgs.gametype == GT_CTY ) {
			// format is rb where its red/blue, 0 is at base, 1 is taken, 2 is dropped
			int redflagId = str[0] - '0', blueflagId = str[1] - '0';

			if ( redflagId >= 0 && redflagId < ARRAY_LEN( ctfFlagStatusRemap ) ) 
				cgs.redflag = ctfFlagStatusRemap[redflagId];

			if ( blueflagId >= 0 && blueflagId < ARRAY_LEN( ctfFlagStatusRemap ) )  
				cgs.blueflag = ctfFlagStatusRemap[blueflagId];
		}
	}
	else if ( num == CS_SHADERSTATE ) {
		CG_ShaderStateChanged();
	}
	else if ( num >= CS_LIGHT_STYLES && num < CS_LIGHT_STYLES + (MAX_LIGHT_STYLES * 3))
	{
		CG_SetLightstyle(num - CS_LIGHT_STYLES);
	}
		
}
コード例 #6
0
ファイル: tr_init.c プロジェクト: Pan7/ioq3df
vidmode_t r_vidModes[] =
{
	{ "Mode  0: 320x240",		320,	240,	1 },
	{ "Mode  1: 400x300",		400,	300,	1 },
	{ "Mode  2: 512x384",		512,	384,	1 },
	{ "Mode  3: 640x480",		640,	480,	1 },
	{ "Mode  4: 800x600",		800,	600,	1 },
	{ "Mode  5: 960x720",		960,	720,	1 },
	{ "Mode  6: 1024x768",		1024,	768,	1 },
	{ "Mode  7: 1152x864",		1152,	864,	1 },
	{ "Mode  8: 1280x1024",		1280,	1024,	1 },
	{ "Mode  9: 1600x1200",		1600,	1200,	1 },
	{ "Mode 10: 2048x1536",		2048,	1536,	1 },
	{ "Mode 11: 856x480 (wide)",856,	480,	1 }
};
static int	s_numVidModes = ARRAY_LEN( r_vidModes );

qboolean R_GetModeInfo( int *width, int *height, float *windowAspect, int mode ) {
	vidmode_t	*vm;
	float			pixelAspect;

	if ( mode < -1 ) {
		return qfalse;
	}
	if ( mode >= s_numVidModes ) {
		return qfalse;
	}

	if ( mode == -1 ) {
		*width = r_customwidth->integer;
		*height = r_customheight->integer;
コード例 #7
0
ファイル: spectrogram.c プロジェクト: erikd/sndfile-tools
static void
get_colour_map_value (float value, double spec_floor_db, unsigned char colour [3], bool gray_scale)
{	static unsigned char map [][3] =
	{	/* These values were originally calculated for a dynamic range of 180dB. */
		{	255,	255,	255	},	/* -0dB */
		{	240,	254,	216	},	/* -10dB */
		{	242,	251,	185	},	/* -20dB */
		{	253,	245,	143	},	/* -30dB */
		{	253,	200,	102	},	/* -40dB */
		{	252,	144,	66	},	/* -50dB */
		{	252,	75,		32	},	/* -60dB */
		{	237,	28,		41	},	/* -70dB */
		{	214,	3,		64	},	/* -80dB */
		{	183,	3,		101	},	/* -90dB */
		{	157,	3,		122	},	/* -100dB */
		{	122,	3,		126	},	/* -110dB */
		{	80,		2,		110	},	/* -120dB */
		{	45,		2,		89	},	/* -130dB */
		{	19,		2,		70	},	/* -140dB */
		{	1,		3,		53	},	/* -150dB */
		{	1,		3,		37	},	/* -160dB */
		{	1,		2,		19	},	/* -170dB */
		{	0,		0,		0	},	/* -180dB */
	} ;

	float rem ;
	int indx ;

	if (gray_scale)
	{	/* "value" is a negative value in decibels.
		 * black (0,0,0) is for <= -180.0, and the other 255 values
		 * should cover the range from -180 to 0 evenly.
		 * (value/spec_floor_db) is >=0.0  and <1.0
		 * because both value and spec_floor_db are negative.
		 * (v/s) * 255.0 goes from 0.0 to 254.9999999 and
		 * floor((v/s) * 255) gives us 0 to 254
		 * converted to 255 to 1 by subtracting it from 255. */
		int gray ; /* The pixel value */

		if (value <= spec_floor_db)
			gray = 0 ;
		else
		{	gray = 255 - lrint (floor ((value / spec_floor_db) * 255.0)) ;
			assert (gray >= 1 && gray <= 255) ;
			} ;
		colour [0] = colour [1] = colour [2] = gray ;
		return ;
		} ;

	if (value >= 0.0)
	{	colour [0] = colour [1] = colour [2] = 255 ;
		return ;
		} ;

	value = fabs (value * (-180.0 / spec_floor_db) * 0.1) ;

	indx = lrintf (floor (value)) ;

	if (indx < 0)
	{	printf ("\nError : colour map array index is %d\n\n", indx) ;
		exit (1) ;
		} ;

	if (indx >= ARRAY_LEN (map) - 1)
	{	colour [0] = colour [1] = colour [2] = 0 ;
		return ;
		} ;

	rem = fmod (value, 1.0) ;

	colour [0] = lrintf ((1.0 - rem) * map [indx][0] + rem * map [indx + 1][0]) ;
	colour [1] = lrintf ((1.0 - rem) * map [indx][1] + rem * map [indx + 1][1]) ;
	colour [2] = lrintf ((1.0 - rem) * map [indx][2] + rem * map [indx + 1][2]) ;

	return ;
} /* get_colour_map_value */
コード例 #8
0
ファイル: event_loop.c プロジェクト: vifm/vifm
void
event_loop(const int *quit)
{
	/* TODO: refactor this function event_loop(). */

	LOG_FUNC_ENTER;

	const wchar_t *const prev_input_buf = curr_input_buf;
	const size_t *const prev_input_buf_pos = curr_input_buf_pos;

	wchar_t input_buf[128];
	size_t input_buf_pos;

	int last_result = 0;
	int wait_for_enter = 0;
	int wait_for_suggestion = 0;
	int timeout = cfg.timeout_len;

	input_buf[0] = L'\0';
	input_buf_pos = 0;
	curr_input_buf = &input_buf[0];
	curr_input_buf_pos = &input_buf_pos;

	/* Make sure to set the working directory once in order to have the
	 * desired state even before any events are processed. */
	(void)vifm_chdir(flist_get_dir(curr_view));

	while(!*quit)
	{
		wint_t c;
		size_t counter;
		int got_input;

		lwin.user_selection = 1;
		rwin.user_selection = 1;

		modes_pre();

		/* Waits for timeout then skips if no key press.  Short-circuit if we're not
		 * waiting for the next key after timeout. */
		do
		{
			const int actual_timeout = wait_for_suggestion
			                         ? MIN(timeout, cfg.sug.delay)
			                         : timeout;

			if(!ensure_term_is_ready())
			{
				wait_for_enter = 0;
				continue;
			}

			modes_periodic();

			bg_check();

			got_input = (get_char_async_loop(status_bar, &c, actual_timeout) != ERR);

			/* If suggestion delay timed out, reset it and wait the rest of the
			 * timeout. */
			if(!got_input && wait_for_suggestion)
			{
				wait_for_suggestion = 0;
				timeout -= actual_timeout;
				display_suggestion_box(input_buf);
				continue;
			}
			wait_for_suggestion = 0;

			if(!got_input && (input_buf_pos == 0 || last_result == KEYS_WAIT))
			{
				timeout = cfg.timeout_len;
				continue;
			}

			if(got_input && c == K(KEY_RESIZE))
			{
				modes_redraw();
				continue;
			}

			break;
		}
		while(1);

		suggestions_are_visible = 0;

		/* Ensure that current working directory is set correctly (some pieces of
		 * code rely on this, e.g. %c macro in current directory). */
		(void)vifm_chdir(flist_get_dir(curr_view));

		if(got_input)
		{
			if(wait_for_enter)
			{
				wait_for_enter = 0;
				curr_stats.save_msg = 0;
				ui_sb_clear();
				if(c == WC_CR)
				{
					continue;
				}
			}

			if(c == WC_C_z)
			{
				ui_shutdown();
				stop_process();
				continue;
			}

			if(input_buf_pos < ARRAY_LEN(input_buf) - 2)
			{
				input_buf[input_buf_pos++] = c;
				input_buf[input_buf_pos] = L'\0';
			}
			else
			{
				/* Recover from input buffer overflow by resetting its contents. */
				reset_input_buf(input_buf, &input_buf_pos);
				clear_input_bar();
				continue;
			}
		}

		counter = vle_keys_counter();
		if(!got_input && last_result == KEYS_WAIT_SHORT)
		{
			hide_suggestion_box();

			last_result = vle_keys_exec_timed_out(input_buf);
			counter = vle_keys_counter() - counter;
			assert(counter <= input_buf_pos);
			if(counter > 0)
			{
				memmove(input_buf, input_buf + counter,
						(wcslen(input_buf) - counter + 1)*sizeof(wchar_t));
			}
		}
		else
		{
			if(got_input)
			{
				curr_stats.save_msg = 0;
			}

			if(last_result == KEYS_WAIT || last_result == KEYS_WAIT_SHORT)
			{
				hide_suggestion_box();
			}

			last_result = vle_keys_exec(input_buf);

			counter = vle_keys_counter() - counter;
			assert(counter <= input_buf_pos);
			if(counter > 0)
			{
				input_buf_pos -= counter;
				memmove(input_buf, input_buf + counter,
						(wcslen(input_buf) - counter + 1)*sizeof(wchar_t));
			}

			if(last_result == KEYS_WAIT || last_result == KEYS_WAIT_SHORT)
			{
				if(should_display_suggestion_box())
				{
					wait_for_suggestion = 1;
				}

				if(got_input)
				{
					modupd_input_bar(input_buf);
				}

				if(last_result == KEYS_WAIT_SHORT && wcscmp(input_buf, L"\033") == 0)
				{
					timeout = 1;
				}

				if(counter > 0)
				{
					clear_input_bar();
				}

				if(!curr_stats.save_msg && curr_view->selected_files &&
						!vle_mode_is(CMDLINE_MODE))
				{
					print_selected_msg();
				}
				continue;
			}
		}

		timeout = cfg.timeout_len;

		process_scheduled_updates();

		reset_input_buf(input_buf, &input_buf_pos);
		clear_input_bar();

		if(ui_sb_multiline())
		{
			wait_for_enter = 1;
			update_all_windows();
			continue;
		}

		/* Ensure that current working directory is set correctly (some pieces of
		 * code rely on this).  PWD could be changed during command execution, but
		 * it should be correct for modes_post() in case of preview modes. */
		(void)vifm_chdir(flist_get_dir(curr_view));
		modes_post();
	}

	curr_input_buf = prev_input_buf;
	curr_input_buf_pos = prev_input_buf_pos;
}
コード例 #9
0
int
sinc_set_converter (SRC_PRIVATE *psrc, int src_enum)
{	SINC_FILTER *filter, temp_filter ;
	increment_t count ;
	int bits ;

	/* Quick sanity check. */
	if (SHIFT_BITS >= sizeof (increment_t) * 8 - 1)
		return SRC_ERR_SHIFT_BITS ;

	if (psrc->private_data != NULL)
	{	free (psrc->private_data) ;
		psrc->private_data = NULL ;
		} ;

	memset (&temp_filter, 0, sizeof (temp_filter)) ;

	temp_filter.sinc_magic_marker = SINC_MAGIC_MARKER ;
	temp_filter.channels = psrc->channels ;

	if (psrc->channels > ARRAY_LEN (temp_filter.left_calc))
		return SRC_ERR_BAD_CHANNEL_COUNT ;
	else if (psrc->channels == 1)
	{	psrc->const_process = sinc_mono_vari_process ;
		psrc->vari_process = sinc_mono_vari_process ;
		}
	else
	if (psrc->channels == 2)
	{	psrc->const_process = sinc_stereo_vari_process ;
		psrc->vari_process = sinc_stereo_vari_process ;
		}
	else
	if (psrc->channels == 4)
	{	psrc->const_process = sinc_quad_vari_process ;
		psrc->vari_process = sinc_quad_vari_process ;
		}
	else
	if (psrc->channels == 6)
	{	psrc->const_process = sinc_hex_vari_process ;
		psrc->vari_process = sinc_hex_vari_process ;
		}
	else
	{	psrc->const_process = sinc_multichan_vari_process ;
		psrc->vari_process = sinc_multichan_vari_process ;
		} ;
	psrc->reset = sinc_reset ;

	switch (src_enum)
	{	case SRC_SINC_FASTEST :
				temp_filter.coeffs = fastest_coeffs.coeffs ;
				temp_filter.coeff_half_len = ARRAY_LEN (fastest_coeffs.coeffs) - 1 ;
				temp_filter.index_inc = fastest_coeffs.increment ;
				break ;

		case SRC_SINC_MEDIUM_QUALITY :
				temp_filter.coeffs = slow_mid_qual_coeffs.coeffs ;
				temp_filter.coeff_half_len = ARRAY_LEN (slow_mid_qual_coeffs.coeffs) - 1 ;
				temp_filter.index_inc = slow_mid_qual_coeffs.increment ;
				break ;

		case SRC_SINC_BEST_QUALITY :
				temp_filter.coeffs = slow_high_qual_coeffs.coeffs ;
				temp_filter.coeff_half_len = ARRAY_LEN (slow_high_qual_coeffs.coeffs) - 1 ;
				temp_filter.index_inc = slow_high_qual_coeffs.increment ;
				break ;

		default :
				return SRC_ERR_BAD_CONVERTER ;
		} ;

	/*
	** FIXME : This needs to be looked at more closely to see if there is
	** a better way. Need to look at prepare_data () at the same time.
	*/

	temp_filter.b_len = lrint (2.5 * temp_filter.coeff_half_len / (temp_filter.index_inc * 1.0) * SRC_MAX_RATIO) ;
	temp_filter.b_len = MAX (temp_filter.b_len, 4096) ;
	temp_filter.b_len *= temp_filter.channels ;

	if ((filter = calloc (1, sizeof (SINC_FILTER) + sizeof (filter->buffer [0]) * (temp_filter.b_len + temp_filter.channels))) == NULL)
		return SRC_ERR_MALLOC_FAILED ;

	*filter = temp_filter ;
	memset (&temp_filter, 0xEE, sizeof (temp_filter)) ;

	psrc->private_data = filter ;

	sinc_reset (psrc) ;

	count = filter->coeff_half_len ;
	for (bits = 0 ; (MAKE_INCREMENT_T (1) << bits) < count ; bits++)
		count |= (MAKE_INCREMENT_T (1) << bits) ;

	if (bits + SHIFT_BITS - 1 >= (int) (sizeof (increment_t) * 8))
		return SRC_ERR_FILTER_LEN ;

	return SRC_ERR_NO_ERROR ;
} /* sinc_set_converter */
コード例 #10
0
ファイル: ui_atoms.c プロジェクト: SilverlineDev/mint-arena
}

consoleCommand_t	ui_commands[] = {
	//{ "levelselect", UI_SPLevelMenu_f, 0 },
	{ "postgame", UI_CalcPostGameStats, CMD_INGAME },
	{ "ui_cache", UI_Cache_f, 0 },
	//{ "ui_cinematics", UI_CinematicsMenu_f, 0 },
	//{ "ui_teamOrders", UI_TeamOrdersMenu_f, CMD_INGAME },
	//{ "iamacheater", UI_SPUnlock_f, 0 },
	//{ "iamamonkey", UI_SPUnlockMedals_f, 0 },
	{ "ui_test", UI_Test_f, CMD_INGAME },
	{ "ui_report", UI_Report, 0 },
	{ "ui_load", UI_Load_f, 0 }
};

int ui_numCommands = ARRAY_LEN( ui_commands );

/*
=================
UI_ConsoleCommand

update frame time, commands are executed by CG_ConsoleCommand
=================
*/
void UI_ConsoleCommand( int realTime ) {
	uiInfo.uiDC.frameTime = realTime - uiInfo.uiDC.realTime;
	uiInfo.uiDC.realTime = realTime;
}

qboolean UI_CursorInRect (int x, int y, int width, int height)
{
コード例 #11
0
	G_Voice( ent, NULL, SAY_ALL, VOICECHAT_TAUNT, qfalse );
}
#endif


static char	*gc_orders[] = {
	"hold your position",
	"hold this position",
	"come here",
	"cover me",
	"guard location",
	"search and destroy",
	"report"
};

static const int numgc_orders = ARRAY_LEN( gc_orders );

void Cmd_GameCommand_f( gentity_t *ent ) {
	int                     targetNum;
	gentity_t       *target;
	int		order;
	char            arg[MAX_TOKEN_CHARS];

	if ( trap_Argc() != 3 ) {
		trap_SendServerCommand( ent-g_entities, va( "print \"Usage: gc <player id> <order 0-%d>\n\"", numgc_orders - 1 ) );
		return;
	}

	trap_Argv( 2, arg, sizeof( arg ) );
	order = atoi( arg );
コード例 #12
0
ファイル: main.c プロジェクト: tzuryby/pimd
int main(int argc, char *argv[])
{	
    int dummy, dummysigalrm, foreground = 0;
    struct timeval tv, difftime, curtime, lasttime, *timeout;
    fd_set rfds, readers;
    int nfds, n, i, secs, ch;
    struct sigaction sa;
    time_t boottime;
    struct option long_options[] = {
	{"config", 1, 0, 'c'},
	{"debug", 2, 0, 'd'},
	{"foreground", 0, 0, 'f'},
	{"disable-vifs", 0, 0, 'N'},
	{"help", 0, 0, 'h'},
	{"version", 0, 0, 'v'},
	{"quit-daemon", 0, 0, 'q'},
	{"reload-config", 0, 0, 'l'},
	{"show-routes", 0, 0, 'r'},
	/* {"show-cache", 0, 0, 'i'}, */
	/* {"show-debug", 0, 0, 'p'}, */
	{0, 0, 0, 0}
    };
    
    snprintf(versionstring, sizeof (versionstring), "pimd version %s", todaysversion);

    while ((ch = getopt_long (argc, argv, "c:d::fhlNP::vqr", long_options, NULL)) != EOF) {
	switch (ch) {
	    case 'c':
		configfilename = optarg;
		break;

	    case 'd':
		if (!optarg) {
		    debug = DEBUG_DEFAULT;
		} else {
		    char *p,*q;
		    size_t i, len;
		    struct debugname *d;

		    debug = 0;
		    p = optarg; q = NULL;
		    while (p) {
			q = strchr(p, ',');
			if (q)
			    *q++ = '\0';
			len = strlen(p);
			for (i = 0, d = debugnames; i < ARRAY_LEN(debugnames); i++, d++)
			    if (len >= d->nchars && strncmp(d->name, p, len) == 0)
				break;

			if (i == ARRAY_LEN(debugnames))
			    return usage();

			debug |= d->level;
			p = q;
		    }
		}
		break;

	    case 'f':
		foreground = 1;
		break;

	    case 'h':
		return usage();

	    case 'l':
		killshow(SIGHUP, NULL);
		return 0;

	    case 'N':
		disable_all_by_default = 1;
		break;

	    case 'P':
#ifdef SNMP
		if (!optarg)
		    dest_port = DEFAULT_PORT;
		else {
		    dest_port = strtonum(optarg, 1, 65535, &errstr);
		    if (errstr) {
			warnx("destination port %s", errstr);
			dest_port = DEFAULT_PORT;
		    }
		}
#else
		warnx("SNMP support missing, please feel free to submit a patch.");
#endif
		break;

	    case 'v':
		printf("%s\n", versionstring);
		return 0;

	    case 'q':
		killshow(SIGTERM, NULL);
		return 0;

	    case 'r':
		killshow(SIGUSR1, _PATH_PIMD_DUMP);
		return 0;
#if 0 /* XXX: TODO */
	    case 'i':
		killshow(SIGUSR2, _PATH_PIMD_CACHE);
		return 0;

	    case 'p':
		killshow(SIGQUIT, NULL);
		return 0;
#endif
	    default:
		return usage();
	}
    }

    argc -= optind;
    argv += optind;

    if (argc > 0) {
	return usage();
    }

    if (geteuid() != 0) {
	fprintf(stderr, "%s: must be root\n", __progname);
	exit(1);
    }
    setlinebuf(stderr);

    if (debug != 0) {
	struct debugname *d;
	char c;
	int tmpd = debug;

	fprintf(stderr, "debug level 0x%lx ", debug);
	c = '(';
	for (d = debugnames; d < debugnames + ARRAY_LEN(debugnames); d++) {
	    if ((tmpd & d->level) == d->level) {
		tmpd &= ~d->level;
		fprintf(stderr, "%c%s", c, d->name);
		c = ',';
	    }
	}
	fprintf(stderr, ")\n");
    }
    
    /*
     * Create directory for runtime files
     */
    mkdir(_PATH_PIMD_RUNDIR, 0755);

    /*
     * Setup logging
     */
#ifdef LOG_DAEMON
    (void)openlog("pimd", LOG_PID, LOG_DAEMON);
    (void)setlogmask(LOG_UPTO(LOG_NOTICE));
#else
    (void)openlog("pimd", LOG_PID);
#endif /* LOG_DAEMON */

    logit(LOG_DEBUG, 0, "%s starting", versionstring);

    do_randomize();
    time(&boottime);
    
    /* Start up the log rate-limiter */
    resetlogging(NULL);

    callout_init();
    init_igmp();
    init_pim();
#ifdef HAVE_ROUTING_SOCKETS
    init_routesock();
#endif /* HAVE_ROUTING_SOCKETS */
    init_pim_mrt();
    init_timers();
    
    /* TODO: check the kernel DVMRP/MROUTED/PIM support version */
    
#ifdef SNMP
    if (i = snmp_init())
	return i;
#endif /* SNMP */
    init_vifs();
    init_rp_and_bsr();   /* Must be after init_vifs() */
    
#ifdef RSRR
    rsrr_init();
#endif /* RSRR */
    
    sa.sa_handler = handler;
    sa.sa_flags = 0;	/* Interrupt system calls */
    sigemptyset(&sa.sa_mask);
    sigaction(SIGALRM, &sa, NULL);
    sigaction(SIGHUP, &sa, NULL);
    sigaction(SIGTERM, &sa, NULL);
    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGUSR1, &sa, NULL);
    sigaction(SIGUSR2, &sa, NULL);
    
    FD_ZERO(&readers);
    FD_SET(igmp_socket, &readers);
    nfds = igmp_socket + 1;
    for (i = 0; i < nhandlers; i++) {
	FD_SET(ihandlers[i].fd, &readers);
	if (ihandlers[i].fd >= nfds)
	    nfds = ihandlers[i].fd + 1;
    }
    
    IF_DEBUG(DEBUG_IF)
	dump_vifs(stderr);
    IF_DEBUG(DEBUG_PIM_MRT)
	dump_pim_mrt(stderr);
    
    /* schedule first timer interrupt */
    timer_setTimer(TIMER_INTERVAL, timer, NULL);
    
    if (!debug && !foreground) {
	/* Detach from the terminal */
	haveterminal = 0;
	if (fork())
	    exit(0);
	(void)close(0);
	(void)close(1);
	(void)close(2);
	(void)open("/", 0);
	(void)dup2(0, 1);
	(void)dup2(0, 2);
#ifdef SYSV
	(void)setpgrp();
#else 
#ifdef TIOCNOTTY
	n = open("/dev/tty", 2);
	if (n >= 0) {
	    (void)ioctl(n, TIOCNOTTY, (char *)0);
	    (void)close(n);
	}
#else
	if (setsid() < 0)
	    perror("setsid");
#endif /* TIOCNOTTY */
#endif /* SYSV */
    } /* End of child process code */
    
    if (pidfile(NULL)) {
	warn("Cannot create pidfile");
    }

    /*
     * Main receive loop.
     */
    dummy = 0;
    dummysigalrm = SIGALRM;
    difftime.tv_usec = 0;
    gettimeofday(&curtime, NULL);
    lasttime = curtime;
    while (1) {
	memcpy(&rfds, &readers, sizeof(rfds));
	secs = timer_nextTimer();
	if (secs == -1)
	    timeout = NULL;
	else {
	    timeout = &tv;
	    timeout->tv_sec = secs;
	   timeout->tv_usec = 0;
        }

        if (boottime) {
           time_t n;

           time(&n);
           if (n > boottime + 15) {
              struct rp_hold *rph = g_rp_hold;

              while(rph) {
                 add_rp_grp_entry(&cand_rp_list, &grp_mask_list,
                                  rph->address, 1, (u_int16)0xffffff, rph->group, rph->mask,
                                  curr_bsr_hash_mask, curr_bsr_fragment_tag);
                 rph = rph->next;
              }
              boottime = 0;
           }
        }
	
	if (sighandled) {
	    if (sighandled & GOT_SIGINT) {
		sighandled &= ~GOT_SIGINT;
		break;
	    }
	    if (sighandled & GOT_SIGHUP) {
		sighandled &= ~GOT_SIGHUP;
		restart(SIGHUP);
		
		/* reconstruct readers and nfds */
		FD_ZERO(&readers);
		FD_SET(igmp_socket, &readers);
		nfds = igmp_socket + 1;
		for (i = 0; i < nhandlers; i++) {
		    FD_SET(ihandlers[i].fd, &readers);
		    if (ihandlers[i].fd >= nfds)
			nfds = ihandlers[i].fd + 1;
		}
		memcpy(&rfds, &readers, sizeof(rfds));
	    }
	    if (sighandled & GOT_SIGUSR1) {
		sighandled &= ~GOT_SIGUSR1;
		fdump(SIGUSR1);
	    }
	    if (sighandled & GOT_SIGUSR2) {
		sighandled &= ~GOT_SIGUSR2;
		cdump(SIGUSR2);
	    }
	    if (sighandled & GOT_SIGALRM) {
		sighandled &= ~GOT_SIGALRM;
		timer(&dummysigalrm);
	    }
	}
	if ((n = select(nfds, &rfds, NULL, NULL, timeout)) < 0) {
	    if (errno != EINTR) /* SIGALRM is expected */
		logit(LOG_WARNING, errno, "select failed");
	    continue;
	}
	if (n > 0) {
	    /* TODO: shall check first igmp_socket for better performance? */
	    for (i = 0; i < nhandlers; i++) {
		if (FD_ISSET(ihandlers[i].fd, &rfds)) {
		    (*ihandlers[i].func)(ihandlers[i].fd, &rfds);
		}
	    }
	}
    
	/*
	 * Handle timeout queue.
	 *
	 * If select + packet processing took more than 1 second,
	 * or if there is a timeout pending, age the timeout queue.
	 *
	 * If not, collect usec in difftime to make sure that the
	 * time doesn't drift too badly.
	 *
	 * If the timeout handlers took more than 1 second,
	 * age the timeout queue again.  XXX This introduces the
	 * potential for infinite loops!
	 */
	do {
	    /*
	     * If the select timed out, then there's no other
	     * activity to account for and we don't need to
	     * call gettimeofday.
	     */
	    if (n == 0) {
		curtime.tv_sec = lasttime.tv_sec + secs;
		curtime.tv_usec = lasttime.tv_usec;
		n = -1;	/* don't do this next time through the loop */
	    } else
		gettimeofday(&curtime, NULL);
	    difftime.tv_sec = curtime.tv_sec - lasttime.tv_sec;
	    difftime.tv_usec += curtime.tv_usec - lasttime.tv_usec;
	    while (difftime.tv_usec >= 1000000) {
		difftime.tv_sec++;
		difftime.tv_usec -= 1000000;
	    }
	    if (difftime.tv_usec < 0) {
		difftime.tv_sec--;
		difftime.tv_usec += 1000000;
	    }
	    lasttime = curtime;
	    if (secs == 0 || difftime.tv_sec > 0)
		age_callout_queue(difftime.tv_sec);
	    secs = -1;
	} while (difftime.tv_sec > 0);
    } /* Main loop */

    logit(LOG_NOTICE, 0, "%s exiting", versionstring);
    cleanup();
    exit(0);
}
コード例 #13
0
ファイル: cg_consolecmds.c プロジェクト: Joanxt/OpenJK
	{ "scoresDown", CG_scrollScoresDown_f },
	{ "scoresUp", CG_scrollScoresUp_f },
	{ "startOrbit", CG_StartOrbit_f },
	//{ "camera", CG_Camera_f },
	{ "loaddeferred", CG_LoadDeferredPlayers },
	{ "invnext", CG_NextInventory_f },
	{ "invprev", CG_PrevInventory_f },
	{ "forcenext", CG_NextForcePower_f },
	{ "forceprev", CG_PrevForcePower_f },
	{ "briefing", CG_SiegeBriefing_f },
	{ "siegeCvarUpdate", CG_SiegeCvarUpdate_f },
	{ "siegeCompleteCvarUpdate", CG_SiegeCompleteCvarUpdate_f },
	{ "clientlist", CG_ClientList_f },
};

static size_t numCommands = ARRAY_LEN( commands );

/*
=================
CG_ConsoleCommand

The string has been tokenized and can be retrieved with
Cmd_Argc() / Cmd_Argv()
=================
*/
qboolean CG_ConsoleCommand( void ) {
	const char	*cmd;
	int		i;

	cmd = CG_Argv(0);
コード例 #14
0
ファイル: command_name.c プロジェクト: phantasea/vifm
SETUP()
{
	vle_cmds_add(commands, ARRAY_LEN(commands));
}
コード例 #15
0
ファイル: wordbreak.c プロジェクト: AlexShiLucky/luapower-all
/**
 * Sets the word breaking information for a generic input string.
 *
 * @param[in]  s			input string
 * @param[in]  len			length of the input
 * @param[in]  lang			language of the input
 * @param[out] brks			pointer to the output breaking data, containing
 *							#WORDBREAK_BREAK, #WORDBREAK_NOBREAK, or
 *							#WORDBREAK_INSIDEACHAR
 * @param[in] get_next_char	function to get the next UTF-32 character
 */
static void set_wordbreaks(
		const void *s,
		size_t len,
		const char *lang,
		char *brks,
		get_next_char_t get_next_char)
{
	enum WordBreakClass wbcLast = WBP_Undefined;
	/* wbcSeqStart is the class that started the current sequence.
	 * WBP_Undefined is a special case that means "sot".
	 * This value is the class that is at the start of the current rule
	 * matching sequence. For example, in case of Numeric+MidNum+Numeric
	 * it'll be Numeric all the way.
	 */
	enum WordBreakClass wbcSeqStart = WBP_Undefined;
	utf32_t ch;
	size_t posNext = 0;
	size_t posCur = 0;
	size_t posLast = 0;

	/* TODO: Language-specific specialization. */
	(void) lang;

	/* Init brks. */
	memset(brks, WORDBREAK_BREAK, len);

	ch = get_next_char(s, len, &posNext);

	while (ch != EOS)
	{
		enum WordBreakClass wbcCur;
		wbcCur = get_char_wb_class(ch, wb_prop_default,
								   ARRAY_LEN(wb_prop_default));

		switch (wbcCur)
		{
	    case WBP_CR:
			/* WB3b */
			set_brks_to(s, brks, posLast, posCur, len,
						WORDBREAK_BREAK, get_next_char);
			wbcSeqStart = wbcCur;
			posLast = posCur;
			break;

	    case WBP_LF:
			if (wbcSeqStart == WBP_CR) /* WB3 */
			{
				set_brks_to(s, brks, posLast, posCur, len,
							WORDBREAK_NOBREAK, get_next_char);
				wbcSeqStart = wbcCur;
				posLast = posCur;
				break;
			}
			/* Fall off */

	    case WBP_Newline:
			/* WB3a,3b */
			set_brks_to(s, brks, posLast, posCur, len,
						WORDBREAK_BREAK, get_next_char);
			wbcSeqStart = wbcCur;
			posLast = posCur;
			break;

	    case WBP_Extend:
	    case WBP_Format:
			/* WB4 - If not the first char/after a newline (WB3a,3b), skip
			 * this class, set it to be the same as the prev, and mark
			 * brks not to break before them. */
			if ((wbcSeqStart == WBP_Undefined) || IS_WB3ab(wbcSeqStart))
			{
				set_brks_to(s, brks, posLast, posCur, len,
							WORDBREAK_BREAK, get_next_char);
				wbcSeqStart = wbcCur;
			}
			else
			{
				/* It's surely not the first */
				brks[posCur - 1] = WORDBREAK_NOBREAK;
				/* "inherit" the previous class. */
				wbcCur = wbcLast;
			}
			break;

	    case WBP_Katakana:
			if ((wbcSeqStart == WBP_Katakana) || /* WB13 */
					(wbcSeqStart == WBP_ExtendNumLet)) /* WB13b */
			{
				set_brks_to(s, brks, posLast, posCur, len,
							WORDBREAK_NOBREAK, get_next_char);
			}
			/* No rule found, reset */
			else
			{
				set_brks_to(s, brks, posLast, posCur, len,
							WORDBREAK_BREAK, get_next_char);
			}
			wbcSeqStart = wbcCur;
			posLast = posCur;
			break;

	    case WBP_ALetter:
			if ((wbcSeqStart == WBP_ALetter) || /* WB5,6,7 */
					(wbcLast == WBP_Numeric) || /* WB10 */
					(wbcSeqStart == WBP_ExtendNumLet)) /* WB13b */
			{
				set_brks_to(s, brks, posLast, posCur, len,
							WORDBREAK_NOBREAK, get_next_char);
			}
			/* No rule found, reset */
			else
			{
				set_brks_to(s, brks, posLast, posCur, len,
							WORDBREAK_BREAK, get_next_char);
			}
			wbcSeqStart = wbcCur;
			posLast = posCur;
			break;

	    case WBP_MidNumLet:
			if ((wbcLast == WBP_ALetter) || /* WB6,7 */
					(wbcLast == WBP_Numeric)) /* WB11,12 */
			{
				/* Go on */
			}
			else
			{
				set_brks_to(s, brks, posLast, posCur, len,
							WORDBREAK_BREAK, get_next_char);
				wbcSeqStart = wbcCur;
				posLast = posCur;
			}
			break;

	    case WBP_MidLetter:
			if (wbcLast == WBP_ALetter) /* WB6,7 */
			{
				/* Go on */
			}
			else
			{
				set_brks_to(s, brks, posLast, posCur, len,
							WORDBREAK_BREAK, get_next_char);
				wbcSeqStart = wbcCur;
				posLast = posCur;
			}
			break;

	    case WBP_MidNum:
			if (wbcLast == WBP_Numeric) /* WB11,12 */
			{
				/* Go on */
			}
			else
			{
				set_brks_to(s, brks, posLast, posCur, len,
							WORDBREAK_BREAK, get_next_char);
				wbcSeqStart = wbcCur;
				posLast = posCur;
			}
			break;

	    case WBP_Numeric:
			if ((wbcSeqStart == WBP_Numeric) || /* WB8,11,12 */
					(wbcLast == WBP_ALetter) || /* WB9 */
					(wbcSeqStart == WBP_ExtendNumLet)) /* WB13b */
			{
				set_brks_to(s, brks, posLast, posCur, len,
							WORDBREAK_NOBREAK, get_next_char);
			}
			/* No rule found, reset */
			else
			{
				set_brks_to(s, brks, posLast, posCur, len,
							WORDBREAK_BREAK, get_next_char);
			}
			wbcSeqStart = wbcCur;
			posLast = posCur;
			break;

	    case WBP_ExtendNumLet:
			/* WB13a,13b */
			if ((wbcSeqStart == wbcLast) &&
				((wbcLast == WBP_ALetter) ||
				 (wbcLast == WBP_Numeric) ||
				 (wbcLast == WBP_Katakana) ||
				 (wbcLast == WBP_ExtendNumLet)))
			{
				set_brks_to(s, brks, posLast, posCur, len,
							WORDBREAK_NOBREAK, get_next_char);
			}
			/* No rule found, reset */
			else
			{
				set_brks_to(s, brks, posLast, posCur, len,
							WORDBREAK_BREAK, get_next_char);
			}
			wbcSeqStart = wbcCur;
			posLast = posCur;
			break;

		 case WBP_Any:
			/* Allow breaks and reset */
			set_brks_to(s, brks, posLast, posCur, len,
						WORDBREAK_BREAK, get_next_char);
			wbcSeqStart = wbcCur;
			posLast = posCur;
			break;

	    default:
			/* Error, should never get here! */
			assert(0);
			break;
		}

		wbcLast = wbcCur;
		posCur = posNext;
		ch = get_next_char(s, len, &posNext);
    }

	/* WB2 */
	set_brks_to(s, brks, posLast, posNext, len,
				WORDBREAK_BREAK, get_next_char);
}
コード例 #16
0
ファイル: timing.c プロジェクト: aderbas/asterisk
static char *timing_test(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	struct ast_timer *timer;
	int count = 0;
	struct timeval start, end;
	unsigned int test_rate = 50;

	switch (cmd) {
	case CLI_INIT:
		e->command = "timing test";
		e->usage = "Usage: timing test <rate>\n"
		           "   Test a timer with a specified rate, 50/sec by default.\n"
		           "";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	if (a->argc != 2 && a->argc != 3) {
		return CLI_SHOWUSAGE;
	}

	if (a->argc == 3) {
		unsigned int rate;
		if (sscanf(a->argv[2], "%30u", &rate) == 1) {
			test_rate = rate;
		} else {
			ast_cli(a->fd, "Invalid rate '%s', using default of %u\n", a->argv[2], test_rate);
		}
	}

	ast_cli(a->fd, "Attempting to test a timer with %u ticks per second.\n", test_rate);

	if (!(timer = ast_timer_open())) {
		ast_cli(a->fd, "Failed to open timing fd\n");
		return CLI_FAILURE;
	}

	ast_cli(a->fd, "Using the '%s' timing module for this test.\n", timer->holder->iface->name);

	start = ast_tvnow();

	ast_timer_set_rate(timer, test_rate);

	while (ast_tvdiff_ms((end = ast_tvnow()), start) < 1000) {
		int res;
		struct pollfd pfd = {
			.fd = ast_timer_fd(timer),
			.events = POLLIN | POLLPRI,
		};

		res = ast_poll(&pfd, 1, 100);

		if (res == 1) {
			count++;
			if (ast_timer_ack(timer, 1) < 0) {
				ast_cli(a->fd, "Timer failed to acknowledge.\n");
				ast_timer_close(timer);
				return CLI_FAILURE;
			}
		} else if (!res) {
			ast_cli(a->fd, "poll() timed out!  This is bad.\n");
		} else if (errno != EAGAIN && errno != EINTR) {
			ast_cli(a->fd, "poll() returned error: %s\n", strerror(errno));
		}
	}

	ast_timer_close(timer);
	timer = NULL;

	ast_cli(a->fd, "It has been %" PRIi64 " milliseconds, and we got %d timer ticks\n",
		ast_tvdiff_ms(end, start), count);

	return CLI_SUCCESS;
}

static struct ast_cli_entry cli_timing[] = {
	AST_CLI_DEFINE(timing_test, "Run a timing test"),
};

static void timing_shutdown(void)
{
	ast_cli_unregister_multiple(cli_timing, ARRAY_LEN(cli_timing));

	ast_heap_destroy(timing_interfaces);
	timing_interfaces = NULL;
}
コード例 #17
0
ファイル: cg_event.cpp プロジェクト: JacksonTech/Unvanquished
static void CG_Obituary( entityState_t *ent )
{
	int          mod;
	int          target, attacker, assistant;
	int          attackerClass = -1;
	const char   *message;
	const char   *messageAssisted = nullptr;
	const char   *messageSuicide = nullptr;
	const char   *targetInfo;
	const char   *attackerInfo;
	const char   *assistantInfo;
	char         targetName[ MAX_NAME_LENGTH ];
	char         attackerName[ MAX_NAME_LENGTH ];
	char         assistantName[ MAX_NAME_LENGTH ];
	gender_t     gender;
	clientInfo_t *ci;
	team_t       attackerTeam, assistantTeam = TEAM_NONE;

	target = ent->otherEntityNum;
	attacker = ent->otherEntityNum2;
	assistant = ent->otherEntityNum3;
	assistantTeam = (team_t) ( ent->generic1 & 0xFF ); // ugly hack allowing for future expansion(!)
	mod = ent->eventParm;

	if ( target < 0 || target >= MAX_CLIENTS )
	{
		CG_Error( "CG_Obituary: target out of range" );
	}

	ci = &cgs.clientinfo[ target ];
	gender = ci->gender;

	if ( attacker < 0 || attacker >= MAX_CLIENTS )
	{
		attacker = ENTITYNUM_WORLD;
		attackerInfo = nullptr;
		attackerTeam = TEAM_NONE;
		strcpy( attackerName, "noname" );
	}
	else
	{
		attackerInfo = CG_ConfigString( CS_PLAYERS + attacker );
		attackerTeam = cgs.clientinfo[ attacker ].team;
		Q_strncpyz( attackerName, Info_ValueForKey( attackerInfo, "n" ), sizeof( attackerName ) );

		// check for kill messages about the current clientNum
		if ( target == cg.snap->ps.clientNum )
		{
			Q_strncpyz( cg.killerName, attackerName, sizeof( cg.killerName ) );
		}
	}

	if ( assistant < 0 || assistant >= MAX_CLIENTS )
	{
		assistantInfo = nullptr;
	}
	else
	{
		assistantInfo = CG_ConfigString( CS_PLAYERS + assistant );
	}

	if ( assistantTeam < TEAM_NONE || assistantTeam >= NUM_TEAMS )
	{
		assistantTeam = TEAM_NONE;
	}

	if ( !assistantInfo )
	{
		strcpy( assistantName, "noname" );
	}
	else
	{
		Q_strncpyz( assistantName, Info_ValueForKey( assistantInfo, "n" ), sizeof( assistantName ) );
	}

	targetInfo = CG_ConfigString( CS_PLAYERS + target );

	if ( !targetInfo )
	{
		return;
	}

	Q_strncpyz( targetName, Info_ValueForKey( targetInfo, "n" ), sizeof( targetName ) );

	// check for single client messages

	if ( cg_emoticonsInMessages.integer )
	{
		if ( mod < MOD_UNKNOWN || mod >= ARRAY_LEN( meansOfDeath ) )
		{
			mod = MOD_UNKNOWN;
		}

		if ( meansOfDeath[ mod ].team )
		{
			attackerTeam = meansOfDeath[ mod ].team;
		}

		// if the long form is needed, show it; but we need a kill icon for this kill type
		if ( *meansOfDeath[ mod ].icon == '>' )
		{
				goto is_long_kill_message;
		}

		// if there's text for the kill type, print a kill message
		if ( *meansOfDeath[ mod ].icon )
		{
			if ( meansOfDeath[ mod ].envKill )
			{
				if ( meansOfDeath[ mod ].showAssist && assistantInfo )
				{
					CG_Printf( "%s (+ %s%s^7) %s %s%s\n", teamTag[ attackerTeam ], teamTag[ assistantTeam ], assistantName, meansOfDeath[ mod ].icon, teamTag[ ci->team ], targetName );
				}
				else
				{
					CG_Printf( "%s %s %s%s\n", teamTag[ attackerTeam ], meansOfDeath[ mod ].icon, teamTag[ ci->team ], targetName );
				}
			}
			else if ( attacker == target )
			{
				CG_Printf( "%s %s%s\n", meansOfDeath[ mod ].icon, teamTag[ ci->team ], targetName );
			}
			else
			{
				if ( meansOfDeath[ mod ].showAssist && assistantInfo )
				{
					CG_Printf( "%s%s^7 (+ %s%s^7) %s %s%s\n", teamTag[ attackerTeam ], attackerName, teamTag[ assistantTeam ], assistantName, meansOfDeath[ mod ].icon, teamTag[ ci->team ], targetName );
				}
				else
				{
					CG_Printf( "%s%s^7 %s %s%s\n", teamTag[ attackerTeam ], attackerName, meansOfDeath[ mod ].icon, teamTag[ ci->team ], targetName );
				}

				// nice big message for teamkills
				if ( attackerTeam == ci->team && attacker == cg.clientNum )
				{
					CG_CenterPrint( va( _("You killed ^1TEAMMATE^7 %s"), targetName ),
							SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH );
				}
			}
		}
	}
	else // Long form
	{
		is_long_kill_message: // <- use of this label == needs a kill icon

		// Messages which contain no killer name
		switch ( mod )
		{
			// Environmental kills

			case MOD_FALLING:
				message = G_( "%s%s ^7fell to death\n" );
				break;

			case MOD_CRUSH:
				message = G_( "%s%s ^7was crushed to death\n" );
				break;

			case MOD_WATER:
				message = G_( "%s%s ^7drowned\n" );
				break;

			case MOD_SLIME:
				message = G_( "%s%s ^7melted\n" );
				break;

			case MOD_LAVA:
				message = G_( "%s%s ^7took a dip in some lava\n" );
				break;

			case MOD_TRIGGER_HURT:
				message = G_( "%s%s ^7was in the wrong place\n" );
				break;

			// Building explosions

			case MOD_HSPAWN:
				message = G_( "%s%s ^7was caught in the explosion\n" );
				break;

			case MOD_ASPAWN:
				message = G_( "%s%s ^7was caught in the acid\n" );
				break;

			// Attacked by a building

			case MOD_MGTURRET:
				message = G_( "%s%s ^7was gunned down by a turret\n" );
				messageAssisted = G_( "%s%s ^7was gunned down by a turret; %s%s^7 assisted\n" );
				break;

			case MOD_ROCKETPOD:
				message = G_( "%s%s ^7caught a rocket\n" );
				messageAssisted = G_( "%s%s ^7caught a rocket; %s%s^7 assisted\n" );
				break;

			case MOD_ATUBE:
				message = G_( "%s%s ^7was melted by an acid tube\n" );
				messageAssisted = G_( "%s%s ^7was melted by an acid tube; %s%s^7 assisted\n" );
				break;

			case MOD_SPIKER:
				message = G_( "%s%s ^7was flechetted by a spiker\n" );
				messageAssisted = G_( "%s%s ^7was flechetted by a spiker; %s%s^7 assisted\n" );
				break;

			case MOD_OVERMIND:
				message = G_( "%s%s ^7was whipped by the overmind\n" );
				messageAssisted = G_( "%s%s ^7was whipped by the overmind; %s%s^7 assisted\n" );
				break;

			case MOD_REACTOR:
				message = G_( "%s%s ^7was fried by the reactor\n" );
				messageAssisted = G_( "%s%s ^7was fried by the reactor; %s%s^7 assisted\n" );
				break;

			case MOD_SLOWBLOB:
				message = G_( "%s%s ^7couldn't avoid the granger\n" );
				messageAssisted = G_( "%s%s ^7couldn't avoid the granger; %s%s^7 assisted\n" );
				break;

			case MOD_SWARM:
				message = G_( "%s%s ^7was consumed by the swarm\n" );
				messageAssisted = G_( "%s%s ^7was consumed by the swarm; %s%s^7 assisted\n" );
				break;

			// Shouldn't happen

			case MOD_TARGET_LASER:
				message = G_( "%s%s ^7saw the light\n" );
				messageAssisted = G_( "%s%s ^7saw the light; %s%s^7 assisted\n" );
				break;

			default:
				message = nullptr;
				break;
		}

		if ( message )
		{
			if ( messageAssisted && assistantInfo )
			{
				CG_Printf( messageAssisted, teamTag[ ci->team ], targetName , teamTag[ assistantTeam ], assistantName);
			}
			else
			{
				CG_Printf( message, teamTag[ ci->team ], targetName );
			}

			return;
		}

		// Messages which contain the killer's name
		switch ( mod )
		{
			case MOD_PAINSAW:
				message = G_( "%s%s ^7was sawn by %s%s\n" );
				messageAssisted = G_( "%s%s ^7was sawn by %s%s^7; %s%s^7 assisted\n" );
				break;

			case MOD_BLASTER:
				message = G_( "%s%s ^7was blasted by %s%s\n" );
				messageAssisted = G_( "%s%s ^7was blasted by %s%s^7; %s%s^7 assisted\n" );
				break;

			case MOD_MACHINEGUN:
				message = G_( "%s%s ^7was machinegunned by %s%s\n" );
				messageAssisted = G_( "%s%s ^7was machinegunned by %s%s^7; %s%s^7 assisted\n" );
				break;

			case MOD_CHAINGUN:
				message = G_( "%s%s ^7was mowed down by %s%s\n" );
				messageAssisted = G_( "%s%s ^7was mowed down by %s%s^7; %s%s^7 assisted\n" );
				break;

			case MOD_SHOTGUN:
				message = G_( "%s%s ^7was gunned down by %s%s\n" );
				messageAssisted = G_( "%s%s ^7was gunned down by %s%s^7; %s%s^7 assisted\n" );
				break;

			case MOD_PRIFLE:
				message = G_( "%s%s ^7was seared by %s%s^7's pulse blast\n" );
				messageAssisted = G_( "%s%s ^7was seared by %s%s^7's pulse blast; %s%s^7 assisted\n" );
				break;

			case MOD_MDRIVER:
				message = G_( "%s%s ^7was sniped by %s%s\n" );
				messageAssisted = G_( "%s%s ^7was sniped by %s%s^7; %s%s^7 assisted\n" );
				break;

			case MOD_LASGUN:
				message = G_( "%s%s ^7was lasered by %s%s\n" );
				messageAssisted = G_( "%s%s ^7was lasered by %s%s^7; %s%s^7 assisted\n" );
				break;

			case MOD_FLAMER:
			case MOD_FLAMER_SPLASH:
				message = G_( "%s%s ^7was grilled by %s%s^7's flame\n" );
				messageAssisted = G_( "%s%s ^7was grilled by %s%s^7's flame; %s%s^7 assisted\n" );
				messageSuicide = G_( "%s%s ^7was charred to a crisp" );
				break;

			case MOD_BURN:
				message = G_( "%s%s ^7was burned by %s%s^7's fire\n" );
				messageAssisted = G_( "%s%s ^7was burned by %s%s^7's fire; %s%s^7 assisted\n" );
				messageSuicide = G_( "%s%s ^7was burned to death" );
				break;

			case MOD_LCANNON:
				message = G_( "%s%s ^7was annihilated by %s%s^7's plasma blast\n" );
				messageAssisted = G_( "%s%s ^7was annihilated by %s%s^7's plasma blast; %s%s^7 assisted\n" );
				break;

			case MOD_LCANNON_SPLASH:
				message = G_( "%s%s ^7was irradiated by %s%s^7's plasma blast\n" );
				messageAssisted = G_( "%s%s ^7was irradiated by %s%s^7's plasma blast; %s%s^7 assisted\n" );
				messageSuicide = G_( "%s%s ^7was irradiated" );
				break;

			case MOD_GRENADE:
				message = G_( "%s%s ^7was blown up by %s%s^7's grenade\n" );
				messageAssisted = G_( "%s%s ^7was blown up by %s%s^7's grenade; %s%s^7 assisted\n" );
				messageSuicide = G_( "%s%s ^7was blown up" );
				break;

			case MOD_FIREBOMB:
				message = G_( "%s%s ^7was incinerated by %s%s^7's firebomb\n" );
				messageAssisted = G_( "%s%s ^7was incinerated by %s%s^7's firebomb; %s%s^7 assisted\n" );
				messageSuicide = G_( "%s%s ^7was incinerated" );
				break;

			case MOD_ABUILDER_CLAW:
				message = G_( "%s%s ^7was gently nibbled by %s%s^7's granger\n" );
				messageAssisted = G_( "%s%s ^7was gently nibbled by %s%s^7's granger; %s%s^7 assisted\n" );
				break;

			case MOD_LEVEL0_BITE:
				message = G_( "%s%s ^7was bitten by %s%s\n" );
				messageAssisted = G_( "%s%s ^7was bitten by %s%s^7; %s%s^7 assisted\n" );
				break;

			case MOD_LEVEL1_CLAW:
				message = G_( "%s%s ^7was sliced by %s%s^7's %s\n" );
				messageAssisted = G_( "%s%s ^7was sliced by %s%s^7's %s^7; %s%s^7 assisted\n" );
				attackerClass = PCL_ALIEN_LEVEL1;
				break;

			case MOD_LEVEL2_CLAW:
				message = G_( "%s%s ^7was shredded by %s%s^7's %s\n" );
				messageAssisted = G_( "%s%s ^7was shredded by %s%s^7's %s^7; %s%s^7 assisted\n" );
				attackerClass = PCL_ALIEN_LEVEL2;
				break;

			case MOD_LEVEL2_ZAP:
				message = G_( "%s%s ^7was electrocuted by %s%s^7's %s\n" );
				messageAssisted = G_( "%s%s ^7was electrocuted by %s%s^7's %s^7; %s%s^7 assisted\n" );
				attackerClass = PCL_ALIEN_LEVEL2;
				break;

			case MOD_LEVEL3_CLAW:
				message = G_( "%s%s ^7was chomped by %s%s^7's %s\n" );
				messageAssisted = G_( "%s%s ^7was chomped by %s%s^7's %s^7; %s%s^7 assisted\n" );
				attackerClass = PCL_ALIEN_LEVEL3;
				break;

			case MOD_LEVEL3_POUNCE:
				message = G_( "%s%s ^7was pounced upon by %s%s^7's %s\n" );
				messageAssisted = G_( "%s%s ^7was pounced upon by %s%s^7's %s^7; %s%s^7 assisted\n" );
				attackerClass = PCL_ALIEN_LEVEL3;
				break;

			case MOD_LEVEL3_BOUNCEBALL:
				message = G_( "%s%s ^7was barbed by %s%s^7's %s\n" );
				messageAssisted = G_( "%s%s ^7was barbed by %s%s^7's %s^7; %s%s^7 assisted\n" );
				messageSuicide = G_( "%s%s ^7was barbed" );
				attackerClass = PCL_ALIEN_LEVEL3;
				break;

			case MOD_LEVEL4_CLAW:
				message = G_( "%s%s ^7was mauled by %s%s^7's %s\n" );
				messageAssisted = G_( "%s%s ^7was mauled by %s%s^7's %s^7; %s%s^7 assisted\n" );
				attackerClass = PCL_ALIEN_LEVEL4;
				break;

			case MOD_LEVEL4_TRAMPLE:
				message = G_( "%s%s ^7should have gotten out of the way of %s%s^7's %s\n" );
				messageAssisted = G_( "%s%s ^7should have gotten out of the way of %s%s^7's %s^7; %s%s^7 assisted\n" );
				attackerClass = PCL_ALIEN_LEVEL4;
				break;

			case MOD_WEIGHT_H:
			case MOD_WEIGHT_A:
				message = G_( "%s%s ^7was crushed under %s%s^7's weight\n" );
				messageAssisted = G_( "%s%s ^7was crushed under %s%s^7's weight; %s%s^7 assisted\n" );
				break;

			case MOD_POISON:
				message = G_( "%s%s ^7should have used a medkit against %s%s^7's poison\n" );
				messageAssisted = G_( "%s%s ^7should have used a medkit against %s%s^7's poison; %s%s^7 assisted\n" );
				break;

			case MOD_TELEFRAG:
				message = G_( "%s%s ^7tried to invade %s%s^7's personal space\n" );
				break;

			default:
				message = G_( "%s%s ^7was killed by %s%s\n" );
				messageAssisted = G_( "%s%s ^7was killed by %s%s^7 and %s%s\n" );
				messageSuicide = G_( "%s%s ^7committed suicide\n" );
				break;
		}

		if ( message )
		{
			// shouldn't need to do this here, but it avoids
			char attackerClassName[ 64 ];

			if ( attackerClass == -1 )
			{
				*attackerClassName = 0;
			}
			else
			{
				Q_strncpyz( attackerClassName, _( BG_ClassModelConfig( attackerClass )->humanName ), sizeof( attackerClassName ) );
			}

			// Argument order: victim, attacker, [class,] [assistant]. Each has team tag first.
			if ( messageSuicide && attacker == target )
			{
				CG_Printf( messageSuicide, teamTag[ ci->team ], targetName );
			}
			else if ( messageAssisted && assistantInfo )
			{
				if ( attackerClass != -1 )
				{
					CG_Printf( messageAssisted, teamTag[ ci->team ], targetName, teamTag[ attackerTeam ], attackerName, attackerClassName, teamTag[ assistantTeam ], assistantName );
				}
				else
				{
					CG_Printf( messageAssisted, teamTag[ ci->team ], targetName, teamTag[ attackerTeam ], attackerName, teamTag[ assistantTeam ], assistantName );
				}
			}
			else
			{
				CG_Printf( message, teamTag[ ci->team ], targetName, teamTag[ attackerTeam ], attackerName, attackerClassName );
			}

			if ( attackerTeam == ci->team && attacker == cg.clientNum && attacker != target )
			{
				CG_CenterPrint( va( _("You killed ^1TEAMMATE^7 %s"), targetName ),
						SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH );
			}

			return;
		}

		// we don't know what it was
		CG_Printf( G_( "%s%s^7 died\n" ), teamTag[ ci->team ], targetName );
	}
}
コード例 #18
0
ファイル: wordbreak.c プロジェクト: luapower/libunibreak
/**
 * Sets the word breaking information for a generic input string.
 *
 * @param[in]  s             input string
 * @param[in]  len           length of the input
 * @param[in]  lang          language of the input (reserved for future use)
 * @param[out] brks          pointer to the output breaking data, containing
 *                           #WORDBREAK_BREAK, #WORDBREAK_NOBREAK, or
 *                           #WORDBREAK_INSIDEACHAR
 * @param[in] get_next_char  function to get the next UTF-32 character
 */
static void set_wordbreaks(
        const void *s,
        size_t len,
        const char *lang,
        char *brks,
        get_next_char_t get_next_char)
{
    /* Counter of how many time we cam across RI */
    int riCounter = 0;
    enum WordBreakClass wbcLast = WBP_Undefined;
    /* wbcSeqStart is the class that started the current sequence.
     * WBP_Undefined is a special case that means "sot".
     * This value is the class that is at the start of the current rule
     * matching sequence. For example, in case of Numeric+MidNum+Numeric
     * it'll be Numeric all the way.
     */
    enum WordBreakClass wbcSeqStart = WBP_Undefined;
    utf32_t ch;
    size_t posNext = 0;
    size_t posCur = 0;
    size_t posLast = 0;

    /* TODO: Language-specific specialization. */
    (void) lang;

    /* Init brks. */
    memset(brks, WORDBREAK_BREAK, len);

    ch = get_next_char(s, len, &posNext);

    while (ch != EOS)
    {
        enum WordBreakClass wbcCur;
        wbcCur = get_char_wb_class(ch, wb_prop_default,
                                   ARRAY_LEN(wb_prop_default));

        switch (wbcCur)
        {
        case WBP_CR:
            /* WB3b */
            set_brks_to(s, brks, posLast, posCur, len,
                        WORDBREAK_BREAK, get_next_char);
            wbcSeqStart = wbcCur;
            posLast = posCur;
            break;

        case WBP_LF:
            if (wbcSeqStart == WBP_CR) /* WB3 */
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_NOBREAK, get_next_char);
                wbcSeqStart = wbcCur;
                posLast = posCur;
                break;
            }
            /* Fall off */

        case WBP_Newline:
            /* WB3a,3b */
            set_brks_to(s, brks, posLast, posCur, len,
                        WORDBREAK_BREAK, get_next_char);
            wbcSeqStart = wbcCur;
            posLast = posCur;
            break;

        case WBP_E_Base_GAZ:
        case WBP_Glue_After_Zwj:
            /* WB3c */
            if (wbcLast == WBP_ZWJ)
            {
               set_brks_to(s, brks, posLast, posCur, len,
                       WORDBREAK_NOBREAK, get_next_char);
            }
            /* No rule found, reset */
            else
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_BREAK, get_next_char);
            }
            wbcSeqStart = wbcCur;
            posLast = posCur;
            break;

        case WBP_ZWJ:
        case WBP_Extend:
        case WBP_Format:
            /* WB4 - If not the first char/after a newline (WB3a,3b), skip
             * this class, set it to be the same as the prev, and mark
             * brks not to break before them. */
            if ((wbcSeqStart == WBP_Undefined) || IS_WB3ab(wbcSeqStart))
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_BREAK, get_next_char);
                wbcSeqStart = wbcCur;
                posLast = posCur;
            }
            else
            {
                /* It's surely not the first */
                brks[posCur - 1] = WORDBREAK_NOBREAK;
                /* WB3c precedes 4, so no intervening Extend chars allowed. */
                if (wbcSeqStart != WBP_ZWJ)
                {
                    /* "inherit" the previous class. */
                    wbcCur = wbcLast;
                }
            }
            break;

        case WBP_Katakana:
            if ((wbcSeqStart == WBP_Katakana) || /* WB13 */
                    (wbcSeqStart == WBP_ExtendNumLet)) /* WB13b */
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_NOBREAK, get_next_char);
            }
            /* No rule found, reset */
            else
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_BREAK, get_next_char);
            }
            wbcSeqStart = wbcCur;
            posLast = posCur;
            break;

        case WBP_Hebrew_Letter:
        case WBP_ALetter:
            if ((wbcSeqStart == WBP_Hebrew_Letter) &&
                    (wbcLast == WBP_Double_Quote)) /* WB7b,c */
            {
               if (wbcCur == WBP_Hebrew_Letter)
                 {
                     set_brks_to(s, brks, posLast, posCur, len,
                             WORDBREAK_NOBREAK, get_next_char);
                 }
               else
                 {
                     set_brks_to(s, brks, posLast, posCur, len,
                             WORDBREAK_BREAK, get_next_char);
                 }
            }
            else if (((wbcSeqStart == WBP_ALetter) ||
                        (wbcSeqStart == WBP_Hebrew_Letter)) || /* WB5,6,7 */
                    (wbcLast == WBP_Numeric) || /* WB10 */
                    (wbcSeqStart == WBP_ExtendNumLet)) /* WB13b */
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_NOBREAK, get_next_char);
            }
            /* No rule found, reset */
            else
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_BREAK, get_next_char);
            }
            wbcSeqStart = wbcCur;
            posLast = posCur;
            break;

        case WBP_Single_Quote:
            if (wbcLast == WBP_Hebrew_Letter) /* WB7a */
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_NOBREAK, get_next_char);
                wbcSeqStart = wbcCur;
                posLast = posCur;
            }
            /* No break on purpose */
        case WBP_MidNumLet:
            if (((wbcLast == WBP_ALetter) ||
                        (wbcLast == WBP_Hebrew_Letter)) || /* WB6,7 */
                    (wbcLast == WBP_Numeric)) /* WB11,12 */
            {
                /* Go on */
            }
            else
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_BREAK, get_next_char);
                wbcSeqStart = wbcCur;
                posLast = posCur;
            }
            break;

        case WBP_MidLetter:
            if ((wbcLast == WBP_ALetter) ||
                    (wbcLast == WBP_Hebrew_Letter)) /* WB6,7 */
            {
                /* Go on */
            }
            else
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_BREAK, get_next_char);
                wbcSeqStart = wbcCur;
                posLast = posCur;
            }
            break;

        case WBP_MidNum:
            if (wbcLast == WBP_Numeric) /* WB11,12 */
            {
                /* Go on */
            }
            else
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_BREAK, get_next_char);
                wbcSeqStart = wbcCur;
                posLast = posCur;
            }
            break;

        case WBP_Numeric:
            if ((wbcSeqStart == WBP_Numeric) || /* WB8,11,12 */
                    ((wbcLast == WBP_ALetter) ||
                     (wbcLast == WBP_Hebrew_Letter)) || /* WB9 */
                    (wbcSeqStart == WBP_ExtendNumLet)) /* WB13b */
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_NOBREAK, get_next_char);
            }
            /* No rule found, reset */
            else
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_BREAK, get_next_char);
            }
            wbcSeqStart = wbcCur;
            posLast = posCur;
            break;

        case WBP_ExtendNumLet:
            /* WB13a,13b */
            if ((wbcSeqStart == wbcLast) &&
                ((wbcLast == WBP_ALetter) ||
                 (wbcLast == WBP_Hebrew_Letter) ||
                 (wbcLast == WBP_Numeric) ||
                 (wbcLast == WBP_Katakana) ||
                 (wbcLast == WBP_ExtendNumLet)))
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_NOBREAK, get_next_char);
            }
            /* No rule found, reset */
            else
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_BREAK, get_next_char);
            }
            wbcSeqStart = wbcCur;
            posLast = posCur;
            break;

        case WBP_E_Base:
            /* No rule found, reset */
            set_brks_to(s, brks, posLast, posCur, len,
                    WORDBREAK_BREAK, get_next_char);
            wbcSeqStart = wbcCur;
            posLast = posCur;
            break;

        case WBP_E_Modifier:
            /* WB14 */
            if ((wbcLast == WBP_E_Base) ||
                (wbcLast == WBP_E_Base_GAZ))
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_NOBREAK, get_next_char);
            }
            /* No rule found, reset */
            else
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_BREAK, get_next_char);
            }
            wbcSeqStart = wbcCur;
            posLast = posCur;
            break;

        case WBP_Regional_Indicator:
            /* WB15,16 */
            if ((wbcSeqStart == WBP_Regional_Indicator) &&
                ((riCounter % 2) == 1))
            {
                set_brks_to(s, brks, posLast, posCur, len,
                        WORDBREAK_NOBREAK, get_next_char);
                riCounter = 0; /* Reset the sequence */
            }
            /* No rule found, reset */
            else
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_BREAK, get_next_char);
                riCounter = 1;
            }
            wbcSeqStart = wbcCur;
            posLast = posCur;
            break;

        case WBP_Double_Quote:
            if (wbcLast == WBP_Hebrew_Letter) /* WB7b,c */
            {
               /* Go on */
            }
            else
            {
                set_brks_to(s, brks, posLast, posCur, len,
                            WORDBREAK_BREAK, get_next_char);
                wbcSeqStart = wbcCur;
                posLast = posCur;
            }
            break;

        case WBP_Any:
            /* Allow breaks and reset */
            set_brks_to(s, brks, posLast, posCur, len,
                        WORDBREAK_BREAK, get_next_char);
            wbcSeqStart = wbcCur;
            posLast = posCur;
            break;

        default:
            /* Error, should never get here! */
            assert(0);
            break;
        }

        wbcLast = wbcCur;
        posCur = posNext;
        ch = get_next_char(s, len, &posNext);
    }

    /* WB2 */
    set_brks_to(s, brks, posLast, posNext, len,
                WORDBREAK_BREAK, get_next_char);
}
コード例 #19
0
ファイル: cvar.cpp プロジェクト: TheSil/WhoracleMod
}

static const char *legacyCvars[] = {
	"bg_fighterAltControl",
	"g_dlURL",
	"g_synchronousClients",
	"jp_DlBaseURL",
	"pmove_fixed",
	"pmove_float",
	"pmove_msec",
	"vm_cgame",
	"vm_game",
	"vm_ui"
};

static const size_t numLegacyCvars = ARRAY_LEN( legacyCvars );

static bool FindLegacyCvar( const char *var_name ) {
	for ( size_t i=0; i<numLegacyCvars; i++ ) {
		if ( !Q_stricmp( legacyCvars[i], var_name ) )
			return true;
	}
	return false;
}

/*
============
Cvar_Server_Set

Set cvars from network server.
============
コード例 #20
0
ファイル: res_limit.c プロジェクト: Djcd/asterisk-opus
static char *handle_cli_ulimit(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	int resource;
	struct rlimit rlimit = { 0, 0 };

	switch (cmd) {
	case CLI_INIT:
		e->command = "ulimit";
		e->usage =
			"Usage: ulimit {data|"
#ifdef RLIMIT_RSS
			"limit|"
#endif
			"file|"
#ifdef RLIMIT_RSS
			"memory|"
#endif
			"stack|time|"
#ifdef RLIMIT_NPROC
			"processes|"
#endif
#ifdef VMEM_DEF
			"virtual|"
#endif
			"core|descriptors} [<num>]\n"
			"       Shows or sets the corresponding resource limit.\n"
			"         data          Process data segment [readonly]\n"
#ifdef RLIMIT_RSS
			"         lock          Memory lock size [readonly]\n"
#endif
			"         file          File size\n"
#ifdef RLIMIT_RSS
			"         memory        Process resident memory [readonly]\n"
#endif
			"         stack         Process stack size [readonly]\n"
			"         time          CPU usage [readonly]\n"
#ifdef RLIMIT_NPROC
			"         processes     Child processes\n"
#endif
#ifdef VMEM_DEF
			"         virtual       Process virtual memory [readonly]\n"
#endif
			"         core          Core dump file size\n"
			"         descriptors   Number of file descriptors\n";
		return NULL;
	case CLI_GENERATE:
		return complete_ulimit(a);
	}

	if (a->argc > 3)
		return CLI_SHOWUSAGE;

	if (a->argc == 1) {
		char arg2[15];
		const char * const newargv[2] = { "ulimit", arg2 };
		for (resource = 0; resource < ARRAY_LEN(limits); resource++) {
			struct ast_cli_args newArgs = { .argv = newargv, .argc = 2 };
			ast_copy_string(arg2, limits[resource].clicmd, sizeof(arg2));
			handle_cli_ulimit(e, CLI_HANDLER, &newArgs);
		}
		return CLI_SUCCESS;
	} else {
コード例 #21
0
	{ "GWeaponDamage", &CG_Rocket_DFGWeaponDamage },
	{ "GWeaponRange", &CG_Rocket_DFGWeaponRange },
	{ "GWeaponRateOfFire", &CG_Rocket_DFGWeaponRateOfFire },
	{ "LevelShot", &CG_Rocket_DFLevelShot },
	{ "PlayerName", &CG_Rocket_DFPlayerName },
	{ "Resolution", &CG_Rocket_DFResolution },
	{ "ServerLabel", &CG_Rocket_DFServerLabel },
	{ "ServerPing", &CG_Rocket_DFServerPing },
	{ "ServerPlayers", &CG_Rocket_DFServerPlayers },
	{ "UpgradeName", &CG_Rocket_DFUpgradeName },
	{ "VoteMap", &CG_Rocket_DFVoteMap },
	{ "VotePlayer", &CG_Rocket_DFVotePlayer },
	{ "WeaponName", &CG_Rocket_DFWeaponName },
};

static const size_t dataFormatterCmdListCount = ARRAY_LEN( dataFormatterCmdList );

static int dataFormatterCmdCmp( const void *a, const void *b )
{
	return Q_stricmp( ( const char * ) a, ( ( dataFormatterCmd_t * ) b )->name );
}

void CG_Rocket_FormatData( int handle )
{
	static char name[ 200 ], data[ BIG_INFO_STRING ];
	dataFormatterCmd_t *cmd;

	Rocket_DataFormatterRawData( handle, name, sizeof( name ), data, sizeof( data ) );

	cmd = (dataFormatterCmd_t*) bsearch( name, dataFormatterCmdList, dataFormatterCmdListCount, sizeof( dataFormatterCmd_t ), dataFormatterCmdCmp );
コード例 #22
0
ファイル: AmmoBox.cpp プロジェクト: Arc0re/lithtech
bool AmmoBox::ReadProp(ObjectCreateStruct *pStruct)
{
	GenericProp genProp;

	// Counts the number of ammo types we put in our box.
	int nNumAmmoTypes = 0;

	for (int i=0; i < AB_MAX_TYPES; i++)
	{
		char key[40];

		AMMO const* pAmmo = NULL;

		sprintf(key, "AmmoType%d", i+1);
        if (g_pLTServer->GetPropGeneric(key, &genProp) == LT_OK)
		{
			if (_stricmp(genProp.m_String, UNUSED_STRING) != 0)
			{
				pAmmo = g_pWeaponMgr->GetAmmo(genProp.m_String);
				if( pAmmo )
				{
					// See if this ammo was server restricted.
					if( pAmmo->bServerRestricted )
					{
						pAmmo = NULL;
					}
					else
					{
						m_nAmmoId[nNumAmmoTypes] = m_nOriginalAmmoId[nNumAmmoTypes] = pAmmo->nId;
					}
				}
			}
		}

		if( pAmmo )
		{
			sprintf(key, "AmmoCount%d", i+1);
			if (g_pLTServer->GetPropGeneric(key, &genProp) == LT_OK)
			{
				m_nAmmoCount[nNumAmmoTypes] = m_nOriginalAmmoCount[nNumAmmoTypes] = genProp.m_Long;
				if (m_nAmmoCount[nNumAmmoTypes] == 0)
				{
					 m_nAmmoCount[nNumAmmoTypes] = m_nOriginalAmmoCount[nNumAmmoTypes] = pAmmo->nSpawnedAmount;
				}
			}

			nNumAmmoTypes++;
		}
	}

	// See if there were no ammotypes that made it.  If so, then don't create this box.
	if( nNumAmmoTypes == 0 )
		return false;

	// Set up the appropriate pick up and respawn sounds...

	FREE_HSTRING(m_hstrSoundFile);
    m_hstrSoundFile = g_pLTServer->CreateString(AMMOBOX_PICKUP_SOUND);

	FREE_HSTRING(m_hstrRespawnSoundFile);
	m_hstrRespawnSoundFile = g_pLTServer->CreateString( AMMOBOX_RESPAWN_SOUND );
 
	char szTemp[32] = {0};

	g_pServerButeMgr->GetAmmoBoxAttributeString( SBMGR_AMMOBOX_POWERUPFX, szTemp, ARRAY_LEN( szTemp ));
	m_sPowerupFX = szTemp;

	g_pServerButeMgr->GetAmmoBoxAttributeString( SBMGR_AMMOBOX_RESPAWNWAITFX, szTemp, ARRAY_LEN( szTemp ));
	m_sRespawnWaitFX = szTemp;

	g_pServerButeMgr->GetAmmoBoxAttributeListReader( &m_blrRespawnWaitSkins, SBMGR_AMMOBOX_RESPAWNWAITSKIN, MAX_CS_FILENAME_LEN );
	g_pServerButeMgr->GetAmmoBoxAttributeListReader( &m_blrRespawnWaitRenderStyles, SBMGR_AMMOBOX_RESPAWNWAITRENDERSTYLE, MAX_CS_FILENAME_LEN );

	m_bRespawnWaitVisible		= !!(g_pServerButeMgr->GetAmmoBoxAttributeInt( SBMGR_AMMOBOX_RESPAWNWAITVISIBLE, false ));
	m_bRespawnWaitTranslucent	= !!(g_pServerButeMgr->GetAmmoBoxAttributeInt( SBMGR_AMMOBOX_RESPAWNWAITTRANSLUCENT, false ));

	m_sClientFX = m_sPowerupFX;

	return true;
}
コード例 #23
0
ファイル: cg_servercmds.c プロジェクト: Wookiee-/jaPRO
	{ "ltchat",				CG_Chat_f },
	{ "map_restart",		CG_MapRestart },
	{ "nfr",				CG_NewForceRank_f },
	{ "print",				CG_Print_f },
	{ "rcg",				CG_RestoreClientGhoul_f },
	{ "remapShader",		CG_RemapShader_f },
	{ "sb",					CG_SiegeBriefingDisplay_f },
	{ "scl",				CG_SiegeClassSelect_f },
	{ "scores",				CG_ParseScores },
	{ "spc",				CG_SiegeProfileMenu_f },
	{ "sxd",				CG_ParseSiegeExtendedData },
	{ "tchat",				CG_Chat_f },
	{ "tinfo",				CG_ParseTeamInfo },
};

static const size_t numCommands = ARRAY_LEN( commands );

/*
=================
CG_ServerCommand

The string has been tokenized and can be retrieved with
Cmd_Argc() / Cmd_Argv()
=================
*/
static void CG_ServerCommand( void ) {
	const char		*cmd = CG_Argv( 0 );
	serverCommand_t	*command = NULL;

	command = (serverCommand_t *)bsearch( cmd, commands, numCommands, sizeof( commands[0] ), svcmdcmp );
コード例 #24
0
};

#ifndef __COVERITY__
_Static_assert(CMD_TURRET_ADC_IDX == 3, "ADC mismatch");
_Static_assert(CMD_SHOULDER_ADC_IDX == 3, "ADC mismatch");
_Static_assert(CMD_ELBOW_ADC_IDX == 3, "ADC mismatch");
_Static_assert(CMD_WRIST_ADC_IDX == 3, "ADC mismatch");
_Static_assert(CMD_CLAMP_ADC_IDX == 3, "ADC mismatch");
#endif

#else
#error "one board has to be defined"
#endif

#ifndef __COVERITY__
_Static_assert(  ARRAY_LEN(analogIOS) == ADC_ADC3_NUM_CHANNELS,
		"analogIOS should be array of same"
		" length than macro ADC_ADCX_NUM_CHANNELS defined in board.h");

_Static_assert( SERVO_COUNT  == ADC_ADC3_NUM_CHANNELS,
		"ADC_ADC3_NUM_CHANNELS (analog position command) defined in board.h should be "
		"equal to SERVO_COUNT defined in servo_pwm.h");

#endif

/* PAL_MODE_RESET */
/* PAL_MODE_UNCONNECTED */
/* PAL_MODE_INPUT */
/* PAL_MODE_INPUT_PULLUP */
/* PAL_MODE_INPUT_PULLDOWN */
/* PAL_MODE_INPUT_ANALOG */
コード例 #25
0
void G_PlayerDie( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int meansOfDeath )
{
	gentity_t *ent;
	int       anim;
	int       killer;
	int       i;
	const char *killerName, *obit;

	const gentity_t *assistantEnt;
	int             assistant = ENTITYNUM_NONE;
	const char      *assistantName = nullptr;
	team_t          assistantTeam = TEAM_NONE;

	if ( self->client->ps.pm_type == PM_DEAD )
	{
		return;
	}

	if ( level.intermissiontime )
	{
		return;
	}

	self->client->ps.pm_type = PM_DEAD;
	self->suicideTime = 0;

	if ( attacker )
	{
		killer = attacker->s.number;

		if ( attacker->client )
		{
			killerName = attacker->client->pers.netname;
		}
		else
		{
			killerName = "<world>";
		}
	}
	else
	{
		killer = ENTITYNUM_WORLD;
		killerName = "<world>";
	}

	assistantEnt = G_FindKillAssist( self, attacker, &assistantTeam );

	if ( assistantEnt )
	{
		assistant = assistantEnt->s.number;

		if ( assistantEnt->client )
		{
			assistantName = assistantEnt->client->pers.netname;
		}
	}

	if ( meansOfDeath < 0 || meansOfDeath >= (int) ARRAY_LEN( modNames ) )
	{
		// fall back on the number
		obit = va( "%d", meansOfDeath );
	}
	else
	{
		obit = modNames[ meansOfDeath ];
	}

	if ( assistant != ENTITYNUM_NONE )
	{
		G_LogPrintf( "Die: %d %d %s %d %d: %s" S_COLOR_WHITE " killed %s" S_COLOR_WHITE "; %s" S_COLOR_WHITE " assisted\n",
		             killer,
		             ( int )( self - g_entities ),
		             obit,
		             assistant,
		             assistantTeam,
			     killerName,
			     self->client->pers.netname,
			     assistantName );
	}
	else
	{
		G_LogPrintf( "Die: %d %d %s: %s" S_COLOR_WHITE " killed %s\n",
		             killer,
		             ( int )( self - g_entities ),
		             obit,
		             killerName,
		             self->client->pers.netname );
	}

	// deactivate all upgrades
	for ( i = UP_NONE + 1; i < UP_NUM_UPGRADES; i++ )
	{
		BG_DeactivateUpgrade( i, self->client->ps.stats );
	}

	// broadcast the death event to everyone
	ent = G_NewTempEntity( self->r.currentOrigin, EV_OBITUARY );
	ent->s.eventParm = meansOfDeath;
	ent->s.otherEntityNum = self->s.number;
	ent->s.otherEntityNum2 = killer;
	ent->s.otherEntityNum3 = assistant;
	ent->s.generic1 = assistantTeam;
	ent->r.svFlags = SVF_BROADCAST; // send to everyone

	if ( attacker && attacker->client )
	{
		if ( ( attacker == self || G_OnSameTeam( self, attacker ) ) )
		{
			//punish team kills and suicides
			if ( attacker->client->pers.team == TEAM_ALIENS )
			{
				G_AddCreditToClient( attacker->client, -ALIEN_TK_SUICIDE_PENALTY, true );
				G_AddCreditsToScore( attacker, -ALIEN_TK_SUICIDE_PENALTY );
			}
			else if ( attacker->client->pers.team == TEAM_HUMANS )
			{
				G_AddCreditToClient( attacker->client, -HUMAN_TK_SUICIDE_PENALTY, true );
				G_AddCreditsToScore( attacker, -HUMAN_TK_SUICIDE_PENALTY );
			}
		}
		else if ( g_showKillerHP.integer )
		{
			trap_SendServerCommand( self - g_entities, va( "print_tr %s %s %3i", QQ( N_("Your killer, $1$^7, had $2$ HP.\n") ),
			                        Quote( killerName ),
			                        attacker->health ) );
		}
	}
	else if ( attacker->s.eType != ET_BUILDABLE )
	{
		if ( self->client->pers.team == TEAM_ALIENS )
		{
			G_AddCreditsToScore( self, -ALIEN_TK_SUICIDE_PENALTY );
		}
		else if ( self->client->pers.team == TEAM_HUMANS )
		{
			G_AddCreditsToScore( self, -HUMAN_TK_SUICIDE_PENALTY );
		}
	}

	// give credits for killing this player
	G_RewardAttackers( self );

	ScoreboardMessage( self );  // show scores

	// send updated scores to any clients that are following this one,
	// or they would get stale scoreboards
	for ( i = 0; i < level.maxclients; i++ )
	{
		gclient_t *client;

		client = &level.clients[ i ];

		if ( client->pers.connected != CON_CONNECTED )
		{
			continue;
		}

		if ( client->sess.spectatorState == SPECTATOR_NOT )
		{
			continue;
		}

		if ( client->sess.spectatorClient == self->s.number )
		{
			ScoreboardMessage( g_entities + i );
		}
	}

	VectorCopy( self->s.origin, self->client->pers.lastDeathLocation );

	self->takedamage = false; // can still be gibbed

	self->s.weapon = WP_NONE;
	if ( self->client->noclip )
	{
		self->client->cliprcontents = CONTENTS_CORPSE;
	}
	else
	{
		self->r.contents = CONTENTS_CORPSE;
	}

	self->s.angles[ PITCH ] = 0;
	self->s.angles[ ROLL ] = 0;
	self->s.angles[ YAW ] = self->s.apos.trBase[ YAW ];
	LookAtKiller( self, inflictor, attacker );

	VectorCopy( self->s.angles, self->client->ps.viewangles );

	self->s.loopSound = 0;

	self->r.maxs[ 2 ] = -8;

	// don't allow respawn until the death anim is done
	// g_forcerespawn may force spawning at some later time
	self->client->respawnTime = level.time + 1700;

	// clear misc
	memset( self->client->ps.misc, 0, sizeof( self->client->ps.misc ) );

	{
		static int i;

		if ( !( self->client->ps.persistant[ PERS_STATE ] & PS_NONSEGMODEL ) )
		{
			switch ( i )
			{
				case 0:
					anim = BOTH_DEATH1;
					break;

				case 1:
					anim = BOTH_DEATH2;
					break;

				case 2:
				default:
					anim = BOTH_DEATH3;
					break;
			}
		}
		else
		{
			switch ( i )
			{
				case 0:
					anim = NSPA_DEATH1;
					break;

				case 1:
					anim = NSPA_DEATH2;
					break;

				case 2:
				default:
					anim = NSPA_DEATH3;
					break;
			}
		}

		self->client->ps.legsAnim =
		  ( ( self->client->ps.legsAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT ) | anim;

		if ( !( self->client->ps.persistant[ PERS_STATE ] & PS_NONSEGMODEL ) )
		{
			self->client->ps.torsoAnim =
			  ( ( self->client->ps.torsoAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT ) | anim;
		}

		// use own entityid if killed by non-client to prevent uint8_t overflow
		G_AddEvent( self, EV_DEATH1 + i,
		            ( killer < MAX_CLIENTS ) ? killer : self - g_entities );

		// globally cycle through the different death animations
		i = ( i + 1 ) % 3;
	}

	Beacon::DetachTags( self );

	trap_LinkEntity( self );

	self->client->pers.infoChangeTime = level.time;
}
コード例 #26
0
ファイル: spinner_app.c プロジェクト: ytai/PixieGuitar
App * SpinnerAppInit(SpinnerApp * instance) {
  assert(instance);

  memset(instance, 0, sizeof(SpinnerApp));

  App * app = &instance->app;
  app->title = "Spinner";
  app->OnStart = SpinnerAppOnStart;
  app->OnResume = SpinnerAppOnResume;
  app->OnTick = SpinnerAppOnTick;

  instance->widgets[0] = NumberWidgetInit(&instance->brightness_widget,
                                          "Brightness",
                                          DISPLAY_WIDTH,
                                          16,
                                          20,
                                          5,
                                          0,
                                          100,
                                          RGB565_BLACK,
                                          RGB565_DARK_GRAY,
                                          RGB565_LIGHT_GRAY,
                                          RGB565_WHITE,
                                          0);

  instance->widgets[1] = NumberWidgetInit(&instance->speed_widget,
                                          "Speed",
                                          DISPLAY_WIDTH,
                                          16,
                                          2,
                                          1,
                                          1,
                                          10,
                                          RGB565_BLACK,
                                          RGB565_DARK_GRAY,
                                          RGB565_LIGHT_GRAY,
                                          RGB565_WHITE,
                                          0);

  instance->widgets[2] = NumberWidgetInit(&instance->collision_widget,
                                          "Collision",
                                          DISPLAY_WIDTH,
                                          16,
                                          40,
                                          5,
                                          0,
                                          100,
                                          RGB565_BLACK,
                                          RGB565_DARK_GRAY,
                                          RGB565_LIGHT_GRAY,
                                          RGB565_WHITE,
                                          0);

  instance->widgets[3] = TextWidgetInit(&instance->exit_widget,
                                        "Exit",
                                        DISPLAY_WIDTH,
                                        16,
                                        RGB565_BLACK,
                                        RGB565_DARK_GRAY,
                                        RGB565_LIGHT_GRAY,
                                        RGB565_WHITE,
                                        AppCommandPop());

  instance->widget = VerticalWidgetListInit(&instance->widget_list,
                                            instance->widgets,
                                            ARRAY_LEN(instance->widgets));

  return app;
}
コード例 #27
0
ファイル: g_spawn.c プロジェクト: Malchio/OpenJK
void G_ParseField( const char *key, const char *value, gentity_t *ent )
{
	field_t	*f;
	byte	*b;
	float	v;
	vec3_t	vec;

	f = (field_t *)bsearch( key, fields, ARRAY_LEN( fields ), sizeof( field_t ), fieldcmp );
	if ( f )
	{// found it
		b = (byte *)ent;

		switch( f->type ) {
		case F_STRING:
			*(char **)(b+f->ofs) = G_NewString (value);
			break;
		case F_VECTOR:
			if ( sscanf( value, "%f %f %f", &vec[0], &vec[1], &vec[2] ) == 3 ) {
				((float *)(b+f->ofs))[0] = vec[0];
				((float *)(b+f->ofs))[1] = vec[1];
				((float *)(b+f->ofs))[2] = vec[2];
			}
			else {
				trap->Print( "G_ParseField: Failed sscanf on F_VECTOR (key/value: %s/%s)\n", key, value );
				((float *)(b+f->ofs))[0] = ((float *)(b+f->ofs))[1] = ((float *)(b+f->ofs))[2] = 0.0f;
			}
			break;
		case F_INT:
			*(int *)(b+f->ofs) = atoi(value);
			break;
		case F_FLOAT:
			*(float *)(b+f->ofs) = atof(value);
			break;
		case F_ANGLEHACK:
			v = atof(value);
			((float *)(b+f->ofs))[0] = 0;
			((float *)(b+f->ofs))[1] = v;
			((float *)(b+f->ofs))[2] = 0;
			break;
		case F_PARM1:
		case F_PARM2:
		case F_PARM3:
		case F_PARM4:
		case F_PARM5:
		case F_PARM6:
		case F_PARM7:
		case F_PARM8:
		case F_PARM9:
		case F_PARM10:
		case F_PARM11:
		case F_PARM12:
		case F_PARM13:
		case F_PARM14:
		case F_PARM15:
		case F_PARM16:
			Q3_SetParm( ent->s.number, (f->type - F_PARM1), (char *) value );
			break;
		}
		return;
	}
}
コード例 #28
0
/*
 * Test case:
 *
 * PURPOSE:
 *     Check that
 *     globus_gram_protocol_unpack_message()
 *     correctly unpacks standard GRAM2 messages with escaped extensions
 *
 * STEPS:
 *     - Creates a message using server-side API.
 *     - Parses message to hash.
 *     - Verifies that all attributes we expect in the message are present in
 *       the parsed values.
 *     - Verifies that the number of attributes in the message match the count
 *       of ones we expect.
 */
static
int
unpack_test_with_extensions(void)
{
    globus_byte_t *                     message;
    globus_size_t                       message_size;
    globus_hashtable_t                  hashtable;
    globus_gram_protocol_extension_t *  entry;
    int                                 rc;
    char                                ext_text[] = "extension: \"hello\\\"\"\r\n";
    char *                              expected[] =
    {
            "protocol-version",
            "job-manager-url",
            "status",
            "failure-code",
            "extension"
    };
    int                                 i;

    rc = globus_gram_protocol_pack_status_update_message(
            job_id,
            GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE,
            0,
            &message,
            &message_size);
    test_assert(
            rc == GLOBUS_SUCCESS,
            ("# Error constructing test message: %d (%s)\n",
            rc,
            globus_gram_protocol_error_string(rc)));
    message = realloc(message, strlen(message) + strlen(ext_text) + 1);
    test_assert(
            message != NULL,
            ("# Error reallocing test message\n"));
    strcat(message, ext_text);
    message_size = strlen(message)+1;

    rc = globus_gram_protocol_unpack_message(
            message,
            message_size,
            &hashtable);
    test_assert(
            rc == GLOBUS_SUCCESS,
            ("# Error parsing test message: %d (%s)\n",
            rc,
            globus_gram_protocol_error_string(rc)));

    /* check that expected attributes were parsed */
    for (i = 0; i < ARRAY_LEN(expected); i++)
    {
        entry = globus_hashtable_lookup(&hashtable, expected[i]);
        test_assert(
                entry != NULL,
                ("# Missing expected attribute %s\n", expected[i]));
    }

    test_assert(ARRAY_LEN(expected) == globus_hashtable_size(&hashtable),
            ("# Hash table contains %d entries, expected %d",
             globus_hashtable_size(&hashtable),
             ARRAY_LEN(expected)));

    globus_gram_protocol_hash_destroy(&hashtable);

    free(message);

    return 0;
}
コード例 #29
0
ファイル: sdl_input.cpp プロジェクト: dkodnik/OpenJK
/*
===============
IN_JoyMove
===============
*/
static void IN_JoyMove( void )
{
	qboolean joy_pressed[ARRAY_LEN(joy_keys)];
	unsigned int axes = 0;
	unsigned int hats = 0;
	int total = 0;
	int i = 0;

	if (!stick)
		return;

	SDL_JoystickUpdate();

	memset(joy_pressed, '\0', sizeof (joy_pressed));

	// update the ball state.
	total = SDL_JoystickNumBalls(stick);
	if (total > 0)
	{
		int balldx = 0;
		int balldy = 0;
		for (i = 0; i < total; i++)
		{
			int dx = 0;
			int dy = 0;
			SDL_JoystickGetBall(stick, i, &dx, &dy);
			balldx += dx;
			balldy += dy;
		}
		if (balldx || balldy)
		{
			// !!! FIXME: is this good for stick balls, or just mice?
			// Scale like the mouse input...
			if (abs(balldx) > 1)
				balldx *= 2;
			if (abs(balldy) > 1)
				balldy *= 2;
			Sys_QueEvent( 0, SE_MOUSE, balldx, balldy, 0, NULL );
		}
	}

	// now query the stick buttons...
	total = SDL_JoystickNumButtons(stick);
	if (total > 0)
	{
		if (total > (int)ARRAY_LEN(stick_state.buttons))
			total = ARRAY_LEN(stick_state.buttons);
		for (i = 0; i < total; i++)
		{
			qboolean pressed = (qboolean)(SDL_JoystickGetButton(stick, i) != 0);
			if (pressed != stick_state.buttons[i])
			{
				Sys_QueEvent( 0, SE_KEY, A_JOY1 + i, pressed, 0, NULL );
				stick_state.buttons[i] = pressed;
			}
		}
	}

	// look at the hats...
	total = SDL_JoystickNumHats(stick);
	if (total > 0)
	{
		if (total > 4) total = 4;
		for (i = 0; i < total; i++)
		{
			((Uint8 *)&hats)[i] = SDL_JoystickGetHat(stick, i);
		}
	}

	// update hat state
	if (hats != stick_state.oldhats)
	{
		for( i = 0; i < 4; i++ ) {
			if( ((Uint8 *)&hats)[i] != ((Uint8 *)&stick_state.oldhats)[i] ) {
				// release event
				switch( ((Uint8 *)&stick_state.oldhats)[i] ) {
					case SDL_HAT_UP:
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 0], qfalse, 0, NULL );
						break;
					case SDL_HAT_RIGHT:
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 1], qfalse, 0, NULL );
						break;
					case SDL_HAT_DOWN:
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 2], qfalse, 0, NULL );
						break;
					case SDL_HAT_LEFT:
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 3], qfalse, 0, NULL );
						break;
					case SDL_HAT_RIGHTUP:
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 0], qfalse, 0, NULL );
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 1], qfalse, 0, NULL );
						break;
					case SDL_HAT_RIGHTDOWN:
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 2], qfalse, 0, NULL );
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 1], qfalse, 0, NULL );
						break;
					case SDL_HAT_LEFTUP:
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 0], qfalse, 0, NULL );
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 3], qfalse, 0, NULL );
						break;
					case SDL_HAT_LEFTDOWN:
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 2], qfalse, 0, NULL );
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 3], qfalse, 0, NULL );
						break;
					default:
						break;
				}
				// press event
				switch( ((Uint8 *)&hats)[i] ) {
					case SDL_HAT_UP:
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 0], qtrue, 0, NULL );
						break;
					case SDL_HAT_RIGHT:
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 1], qtrue, 0, NULL );
						break;
					case SDL_HAT_DOWN:
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 2], qtrue, 0, NULL );
						break;
					case SDL_HAT_LEFT:
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 3], qtrue, 0, NULL );
						break;
					case SDL_HAT_RIGHTUP:
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 0], qtrue, 0, NULL );
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 1], qtrue, 0, NULL );
						break;
					case SDL_HAT_RIGHTDOWN:
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 2], qtrue, 0, NULL );
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 1], qtrue, 0, NULL );
						break;
					case SDL_HAT_LEFTUP:
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 0], qtrue, 0, NULL );
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 3], qtrue, 0, NULL );
						break;
					case SDL_HAT_LEFTDOWN:
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 2], qtrue, 0, NULL );
						Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 3], qtrue, 0, NULL );
						break;
					default:
						break;
				}
			}
		}
	}

	// save hat state
	stick_state.oldhats = hats;

	// finally, look at the axes...
	total = SDL_JoystickNumAxes(stick);
	if (total > 0)
	{
		if (in_joystickUseAnalog->integer)
		{
			if (total > MAX_JOYSTICK_AXIS) total = MAX_JOYSTICK_AXIS;
			for (i = 0; i < total; i++)
			{
				Sint16 axis = SDL_JoystickGetAxis(stick, i);
				float f = ( (float) abs(axis) ) / 32767.0f;

				if( f < in_joystickThreshold->value ) axis = 0;

				if ( axis != stick_state.oldaaxes[i] )
				{
					Sys_QueEvent( 0, SE_JOYSTICK_AXIS, i, axis, 0, NULL );
					stick_state.oldaaxes[i] = axis;
				}
			}
		}
		else
		{
			if (total > 16) total = 16;
			for (i = 0; i < total; i++)
			{
				Sint16 axis = SDL_JoystickGetAxis(stick, i);
				float f = ( (float) axis ) / 32767.0f;
				if( f < -in_joystickThreshold->value ) {
					axes |= ( 1 << ( i * 2 ) );
				} else if( f > in_joystickThreshold->value ) {
					axes |= ( 1 << ( ( i * 2 ) + 1 ) );
				}
			}
		}
	}

	/* Time to update axes state based on old vs. new. */
	if (axes != stick_state.oldaxes)
	{
		for( i = 0; i < 16; i++ ) {
			if( ( axes & ( 1 << i ) ) && !( stick_state.oldaxes & ( 1 << i ) ) ) {
				Sys_QueEvent( 0, SE_KEY, joy_keys[i], qtrue, 0, NULL );
			}

			if( !( axes & ( 1 << i ) ) && ( stick_state.oldaxes & ( 1 << i ) ) ) {
				Sys_QueEvent( 0, SE_KEY, joy_keys[i], qfalse, 0, NULL );
			}
		}
	}

	/* Save for future generations. */
	stick_state.oldaxes = axes;
}
コード例 #30
0
	{ "+moveup",        N_( "Jump" ),                                  { -1, -1 } },
	{ "+movedown",      N_( "Crouch" ),                                { -1, -1 } },
	{ "+attack",        N_( "Primary Attack" ),                        { -1, -1 } },
	{ "+attack2",       N_( "Secondary Attack" ),                      { -1, -1 } },
	{ "reload",         N_( "Reload" ),                                { -1, -1 } },
	{ "buy ammo",       N_( "Buy Ammo" ),                              { -1, -1 } },
	{ "itemact medkit", N_( "Use Medkit" ),                            { -1, -1 } },
	{ "+activate",      N_( "Use Structure/Evolve" ),                  { -1, -1 } },
	{ "if alt \"/deconstruct marked\" /deconstruct",
                            N_( "Deconstruct Structure" ),                 { -1, -1 } },
	{ "weapprev",       N_( "Previous Upgrade" ),                      { -1, -1 } },
	{ "weapnext",       N_( "Next Upgrade" ),                          { -1, -1 } },
	{ "toggleconsole",  N_( "Toggle Console" ),                        { -1, -1 } }
};

static const size_t numBindings = ARRAY_LEN( bindings );

/*
=================
CG_GetBindings
=================
*/
static void CG_GetBindings( team_t team )
{
	unsigned  i, j, numKeys;
	char buffer[ MAX_STRING_CHARS ];

	for ( i = 0; i < numBindings; i++ )
	{
		bindings[ i ].keys[ 0 ] = bindings[ i ].keys[ 1 ] = K_NONE;
		numKeys = 0;