void SQFuncState::AddInstruction(SQInstruction &i)
{
	SQInteger size = _instructions.size();
	if(size > 0 && _optimization){ //simple optimizer
		SQInstruction &pi = _instructions[size-1];//previous instruction
		switch(i.op) {
		case _OP_RETURN:
			if( _parent && i._arg0 != MAX_FUNC_STACKSIZE && pi.op == _OP_CALL && _returnexp < size-1) {
				pi.op = _OP_TAILCALL;
			}
		break;
		case _OP_GET:
			if( pi.op == _OP_LOAD && pi._arg0 == i._arg2 && (!IsLocal(pi._arg0))){
				pi._arg1 = pi._arg1;
				pi._arg2 = (unsigned char)i._arg1;
				pi.op = _OP_GETK;
				pi._arg0 = i._arg0;

				return;
			}
		break;
		case _OP_PREPCALL:
			if( pi.op == _OP_LOAD  && pi._arg0 == i._arg1 && (!IsLocal(pi._arg0))){
				pi.op = _OP_PREPCALLK;
				pi._arg0 = i._arg0;
				pi._arg1 = pi._arg1;
				pi._arg2 = i._arg2;
				pi._arg3 = i._arg3;
				return;
			}
			break;
		case _OP_APPENDARRAY:
			if(pi.op == _OP_LOAD && pi._arg0 == i._arg1 && (!IsLocal(pi._arg0))){
				pi.op = _OP_APPENDARRAY;
				pi._arg0 = i._arg0;
				pi._arg1 = pi._arg1;
				pi._arg2 = MAX_FUNC_STACKSIZE;
				pi._arg3 = MAX_FUNC_STACKSIZE;
				return;
			}
			break;
		case _OP_MOVE:
			if((pi.op == _OP_GET || pi.op == _OP_ARITH || pi.op == _OP_BITW) && (pi._arg0 == i._arg1))
			{
				pi._arg0 = i._arg0;
				_optimization = false;
				return;
			}

			if(pi.op == _OP_MOVE)
			{
				pi.op = _OP_DMOVE;
				pi._arg2 = i._arg0;
				pi._arg3 = (unsigned char)i._arg1;
				return;
			}
			break;
		case _OP_LOAD:
			if(pi.op == _OP_LOAD && i._arg1 < 256) {
				pi.op = _OP_DLOAD;
				pi._arg2 = i._arg0;
				pi._arg3 = (unsigned char)i._arg1;
				return;
			}
			break;
		case _OP_EQ:case _OP_NE:
			if(pi.op == _OP_LOAD && pi._arg0 == i._arg1 && (!IsLocal(pi._arg0) ))
			{
				pi.op = i.op;
				pi._arg0 = i._arg0;
				pi._arg1 = pi._arg1;
				pi._arg2 = i._arg2;
				pi._arg3 = MAX_FUNC_STACKSIZE;
				return;
			}
			break;
		case _OP_LOADNULLS:
			if((pi.op == _OP_LOADNULLS && pi._arg0+pi._arg1 == i._arg0)) {

				pi._arg1 = pi._arg1 + 1;
				pi.op = _OP_LOADNULLS;
				return;
			}
            break;
		case _OP_LINE:
			if(pi.op == _OP_LINE) {
				_instructions.pop_back();
				_lineinfos.pop_back();
			}
			break;
		}
	}
	_optimization = true;
	_instructions.push_back(i);
}
void OrientConstRotation::Update(TimeValue t){
	Interval iv = FOREVER;
	ivalid = FOREVER;
	
	int ct = pblock->Count(orientation_target_list);
	int ctf = pblock->Count(orientation_target_weight);

	float total_orient_target_weight_prev = 0.0f, total_orient_target_weight_current = 0.0f;
	float orient_targ_Wt_current = 0.0f;
	Quat quat_prev, quat_current, lCurRot;
	INode *orient_target_prev= NULL, *orient_target_current= NULL;
	Matrix3 targetTM(1);
	Point3 trans, scaleP;

	quat_prev.Identity();
	quat_current.Identity();
	lCurRot.Identity();

		if (ct == 1){
			pblock->GetValue(orientation_target_list, t, orient_target_prev, iv, 0);
			pblock->GetValue(orientation_target_weight, t, orient_targ_Wt_current, iv, 0);
				ivalid &= iv;

				if (orient_target_prev == NULL){
					targetTM.IdentityMatrix();
				}
				else {
					targetTM = orient_target_prev->GetNodeTM(t, &ivalid);
				}

				if (IsLocal() && orient_target_prev != NULL) {
					targetTM = targetTM * Inverse(orient_target_prev->GetParentTM(t));
				}
				AffineParts comps;		// Requires header decomp.h
				decomp_affine(targetTM, &comps);
				quat_current = comps.q;
				quat_current.Normalize();
				quat_current.MakeClosest(quat_prev);

				lCurRot = quat_current;

				quat_prev = lCurRot;
				total_orient_target_weight_prev += orient_targ_Wt_current;
//			}
		}
		else if (ct > 1){

			pblock->GetValue(orientation_target_list, t, orient_target_prev, iv, 0);
			pblock->GetValue(orientation_target_weight, t, orient_targ_Wt_current, iv, 0);
//			if (orient_target_prev != NULL)
//			{
				ivalid &= iv;

				if (orient_target_prev == NULL){
					targetTM.IdentityMatrix();
				}
				else {
					targetTM = orient_target_prev->GetNodeTM(t, &ivalid);
				}

				if (IsLocal() && orient_target_prev != NULL) {
					targetTM = targetTM * Inverse(orient_target_prev->GetParentTM(t));
				}
				AffineParts comps;		// Requires header decomp.h
				decomp_affine(targetTM, &comps);
				quat_current = comps.q;
				quat_current.Normalize();
				quat_current.MakeClosest(quat_prev);

				lCurRot = quat_current;

				quat_prev = lCurRot;
				total_orient_target_weight_prev += orient_targ_Wt_current;
//			}

			for (int i = 0; i < ct -1; i++) {
//				ct = pblock->Count(orientation_target_list);
				pblock->GetValue(orientation_target_list, t, orient_target_current, iv, i+1);
				pblock->GetValue(orientation_target_weight, t, orient_targ_Wt_current, iv, i+1);
//				if (orient_target_current != NULL){
					ivalid &= iv;

					if (orient_target_current == NULL){
						targetTM.IdentityMatrix();
					}
					else {
						targetTM = orient_target_current->GetNodeTM(t, &ivalid);
					}

//					Matrix3 targetTM = orient_target_current->GetNodeTM(t, &ivalid);
					if (IsLocal() && orient_target_current != NULL) {
						targetTM = targetTM * Inverse(orient_target_current->GetParentTM(t));
					}
					AffineParts comps;		// Requires header decomp.h
					decomp_affine(targetTM, &comps);
					quat_current = comps.q;
					quat_current.Normalize();
					quat_current.MakeClosest(quat_prev);

					float slerp_wt = 0.0f;
					if ((total_orient_target_weight_prev + orient_targ_Wt_current) != 0.0){
						slerp_wt = orient_targ_Wt_current / (total_orient_target_weight_prev + orient_targ_Wt_current);
					}

					lCurRot = Slerp(quat_prev, quat_current, slerp_wt);
					lCurRot.Normalize();

					quat_prev = lCurRot;
					total_orient_target_weight_prev += orient_targ_Wt_current;
//				}
			}			//for (int i = 0; i < ct -1; i++)
		}				//else if (ct > 1)

		if (oldTargetNumber != ct) {
			InitialOrientQuat = lCurRot;
		}

		curRot = lCurRot;
		if (total_orient_target_weight_prev > 0.0){
			if (Relative()){
				if(IsLocal()){
					curRot =   baseRotQuatLocal * (lCurRot /InitialOrientQuat);
				}
				else{
					curRot =   baseRotQuatWorld * (lCurRot /InitialOrientQuat);
				}
			}
		}
		else {
			curRot = baseRotQuatLocal;
		}
		curRot.MakeClosest(IdentQuat());
		curRot.Normalize();
		oldTargetNumber = ct;
//	if (ivalid.Empty()) ivalid.SetInstant(t);
}
OGRErr OGRSpatialReference::exportToPanorama( long *piProjSys, long *piDatum,
                                              long *piEllips, long *piZone,
                                              double *padfPrjParams ) const

{
    CPLAssert( padfPrjParams );

    const char  *pszProjection = GetAttrValue("PROJECTION");

/* -------------------------------------------------------------------- */
/*      Fill all projection parameters with zero.                       */
/* -------------------------------------------------------------------- */
    int     i;

    *piDatum = 0L;
    *piEllips = 0L;
    *piZone = 0L;
    for ( i = 0; i < 7; i++ )
        padfPrjParams[i] = 0.0;

/* ==================================================================== */
/*      Handle the projection definition.                               */
/* ==================================================================== */
    if( IsLocal() )
        *piProjSys = PAN_PROJ_NONE;

    else if( pszProjection == NULL )
    {
#ifdef DEBUG
        CPLDebug( "OSR_Panorama",
                  "Empty projection definition, considered as Geographic" );
#endif
        *piProjSys = PAN_PROJ_NONE;
    }

    else if( EQUAL(pszProjection, SRS_PT_MERCATOR_1SP) )
    {
        *piProjSys = PAN_PROJ_MERCAT;
        padfPrjParams[3] =
            TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 );
        padfPrjParams[0] =
            TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 );
        padfPrjParams[4] = GetNormProjParm( SRS_PP_SCALE_FACTOR, 1.0 );
        padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_POLAR_STEREOGRAPHIC) )
    {
        *piProjSys = PAN_PROJ_PS;
        padfPrjParams[3] =
            TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 );
        padfPrjParams[2] =
            TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 );
        padfPrjParams[4] = GetNormProjParm( SRS_PP_SCALE_FACTOR, 1.0 );
        padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_POLYCONIC) )
    {
        *piProjSys = PAN_PROJ_POLYC;
        padfPrjParams[3] =
            TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 );
        padfPrjParams[2] =
            TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 );
        padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_EQUIDISTANT_CONIC) )
    {
        *piProjSys = PAN_PROJ_EC;
        padfPrjParams[0] =
            TO_RADIANS * GetNormProjParm( SRS_PP_STANDARD_PARALLEL_1, 0.0 );
        padfPrjParams[1] =
            TO_RADIANS * GetNormProjParm( SRS_PP_STANDARD_PARALLEL_2, 0.0 );
        padfPrjParams[3] =
            TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 );
        padfPrjParams[2] =
            TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 );
        padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP) )
    {
        *piProjSys = PAN_PROJ_LCC;
        padfPrjParams[0] =
            TO_RADIANS * GetNormProjParm( SRS_PP_STANDARD_PARALLEL_1, 0.0 );
        padfPrjParams[1] =
            TO_RADIANS * GetNormProjParm( SRS_PP_STANDARD_PARALLEL_2, 0.0 );
        padfPrjParams[3] =
            TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 );
        padfPrjParams[2] =
            TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 );
        padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_TRANSVERSE_MERCATOR) )
    {
        int bNorth;

        *piZone = GetUTMZone( &bNorth );

        if( *piZone != 0 )
        {
            *piProjSys = PAN_PROJ_UTM;
            if( !bNorth )
                *piZone = - *piZone;
        }
        else
        {
            *piProjSys = PAN_PROJ_TM;
            padfPrjParams[3] =
                TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 );
            padfPrjParams[2] =
                TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 );
            padfPrjParams[4] =
                GetNormProjParm( SRS_PP_SCALE_FACTOR, 1.0 );
            padfPrjParams[5] =
                GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
            padfPrjParams[6] =
                GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
        }
    }

    else if( EQUAL(pszProjection, SRS_PT_WAGNER_I) )
    {
        *piProjSys = PAN_PROJ_WAG1;
        padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_STEREOGRAPHIC) )
    {
        *piProjSys = PAN_PROJ_STEREO;
        padfPrjParams[3] =
            TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 );
        padfPrjParams[2] =
            TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 );
        padfPrjParams[4] = GetNormProjParm( SRS_PP_SCALE_FACTOR, 1.0 );
        padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_AZIMUTHAL_EQUIDISTANT) )
    {
        *piProjSys = PAN_PROJ_AE;
        padfPrjParams[3] =
            TO_RADIANS * GetNormProjParm( SRS_PP_LONGITUDE_OF_CENTER, 0.0 );
        padfPrjParams[0] =
            TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_CENTER, 0.0 );
        padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_GNOMONIC) )
    {
        *piProjSys = PAN_PROJ_GNOMON;
        padfPrjParams[3] =
            TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 );
        padfPrjParams[2] =
            TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 );
        padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_MOLLWEIDE) )
    {
        *piProjSys = PAN_PROJ_MOLL;
        padfPrjParams[3] =
            TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 );
        padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_LAMBERT_AZIMUTHAL_EQUAL_AREA) )
    {
        *piProjSys = PAN_PROJ_LAEA;
        padfPrjParams[3] =
            TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 );
        padfPrjParams[0] =
            TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 );
        padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_EQUIRECTANGULAR) )
    {
        *piProjSys = PAN_PROJ_EQC;
        padfPrjParams[3] =
            TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 );
        padfPrjParams[0] =
            TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 );
        padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_CYLINDRICAL_EQUAL_AREA) )
    {
        *piProjSys = PAN_PROJ_CEA;
        padfPrjParams[3] =
            TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 );
        padfPrjParams[2] =
            TO_RADIANS * GetNormProjParm( SRS_PP_STANDARD_PARALLEL_1, 0.0 );
        padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_IMW_POLYCONIC) )
    {
        *piProjSys = PAN_PROJ_IMWP;
        padfPrjParams[3] =
            TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 );
        padfPrjParams[0] =
            TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_1ST_POINT, 0.0 );
        padfPrjParams[1] =
            TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_2ND_POINT, 0.0 );
        padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    // Projection unsupported by "Panorama" GIS
    else
    {
        CPLDebug( "OSR_Panorama",
                  "Projection \"%s\" unsupported by \"Panorama\" GIS. "
                  "Geographic system will be used.", pszProjection );
        *piProjSys = PAN_PROJ_NONE;
    }

/* -------------------------------------------------------------------- */
/*      Translate the datum.                                            */
/* -------------------------------------------------------------------- */
    const char  *pszDatum = GetAttrValue( "DATUM" );

    if ( pszDatum == NULL )
    {
        *piDatum = PAN_DATUM_NONE;
        *piEllips = PAN_ELLIPSOID_NONE;
    }
    else if ( EQUAL( pszDatum, "Pulkovo_1942" ) )
    {
        *piDatum = PAN_DATUM_PULKOVO42;
        *piEllips = PAN_ELLIPSOID_KRASSOVSKY;
    }
    else if( EQUAL( pszDatum, SRS_DN_WGS84 ) )
    {
        *piDatum = PAN_DATUM_WGS84;
        *piEllips = PAN_ELLIPSOID_WGS84;
    }

    // If not found well known datum, translate ellipsoid
    else
    {
        double      dfSemiMajor = GetSemiMajor();
        double      dfInvFlattening = GetInvFlattening();

#ifdef DEBUG
        CPLDebug( "OSR_Panorama",
                  "Datum \"%s\" unsupported by \"Panorama\" GIS. "
                  "Trying to translate an ellipsoid definition.", pszDatum );
#endif

        for ( i = 0; i < NUMBER_OF_ELLIPSOIDS; i++ )
        {
            if ( aoEllips[i] )
            {
                double  dfSM = 0.0;
                double  dfIF = 1.0;

                if ( OSRGetEllipsoidInfo( aoEllips[i], NULL,
                                          &dfSM, &dfIF ) == OGRERR_NONE
                     && CPLIsEqual(dfSemiMajor, dfSM)
                     && CPLIsEqual(dfInvFlattening, dfIF) )
                {
                    *piEllips = i;
                    break;
                }
            }
        }

        if ( i == NUMBER_OF_ELLIPSOIDS )    // Didn't found matches.
        {
#ifdef DEBUG
            CPLDebug( "OSR_Panorama",
                      "Ellipsoid \"%s\" unsupported by \"Panorama\" GIS.",
                      pszDatum );
#endif
            *piDatum = PAN_DATUM_NONE;
            *piEllips = PAN_ELLIPSOID_NONE;
        }
    }

    return OGRERR_NONE;
}
void EjectedPilotClass::InitLocalData(AircraftClass *ac, int mode, int no){
	DrawableBSP		*acBSP;
	int				labelLen;

	_delayTime = SimLibElapsedTime + no * 2 * CampaignSeconds;
	// Initialize position, rotation, velocity, angular velocity.
	if (ac)
	{
		_pos = EP_VECTOR(ac->XPos(),ac->YPos(),ac->ZPos());

		_rot[I_ROLL] =	ac->Roll();
		_rot[I_PITCH] = ac->Pitch();
		_rot[I_YAW] = ac->Yaw();
		
		_vel = EP_VECTOR(ac->XDelta(),ac->YDelta(),ac->ZDelta());

		_aVel[I_ROLL] = ac->RollDelta();
		_aVel[I_PITCH] = ac->PitchDelta();
		_aVel[I_YAW] = ac->YawDelta();
	}
	else
	{

		_pos = EP_VECTOR(XPos(),YPos(),ZPos());

		_rot[I_ROLL] =	Roll();
		_rot[I_PITCH] = Pitch();
		_rot[I_YAW] = Yaw();
		
		_vel = EP_VECTOR(XDelta(),YDelta(),ZDelta());

		_aVel[I_ROLL] = RollDelta();
		_aVel[I_PITCH] = PitchDelta();
		_aVel[I_YAW] = YawDelta();
	}

	// Play with this value to change the signature of an
	// ejected pilot on the IR.
	SetPowerOutput(0);
	// sfr: not setters on this anymore
	//SetVt(0);
	//SetKias(0);

	// Initialize physical data.
	_pd = NULL;
	_stage = PD_START;

	// Initialize model data to NULL.
	_md = NULL;
	_model = MD_START;

	// Set the ejection mode.
	SetMode(mode);

	// Initialize run time and delta time.
	_runTime = 0.0;
	_deltaTime = 0.0;

	// We just set the type flag to "FalconSimEntity".
	SetTypeFlag(FalconEntity::FalconSimEntity);

	// Is it ourselves - Find out from the aircraft.
	if (ac && no == 0){
		_isPlayer = (SimDriver.GetPlayerEntity() == ac) ? TRUE : FALSE;
	}
	else {
		_isPlayer = FALSE;
	}

	// Is it a player - Find out from the aircraft.
	if (ac){
		_isDigital = ac->IsDigital() ? TRUE : FALSE;
	}
	else{
		_isDigital = TRUE;
	}

	// Set team/country
	if (ac){
      SetCountry (ac->GetCountry());
	}

	_endStageTimeAdjust = 
	(
		IsDigiPilot() ?
		0.0F :
		_pd->humanPilotEndStageTimeAdjust
	);
	
	// It hasn't hit the ground yet.
	_hitGround = FALSE;

	// The chute isn't collapsed yet.
	_collapseChute = FALSE;
	_chuteCollapsedTime = 1000000.0;

	// No death message yet.
	_deathMsg = NULL;

	// Update shared data.
	SetPosition(_pos[I_X], _pos[I_Y], _pos[I_Z]);
	SetDelta(_vel[I_X], _vel[I_Y], _vel[I_Z]);
	SetYPR(_rot[I_YAW], _rot[I_PITCH], _rot[I_ROLL]);
	SetYPRDelta(_aVel[I_YAW], _aVel[I_PITCH], _aVel[I_ROLL]);

	// Update matrices for geometry.
	CalcTransformMatrix((SimMoverClass *)this);

	// Set up our label.
	if (ac)
	{
		acBSP = (DrawableBSP *)ac->drawPointer;
		if(acBSP != NULL)
		{
			strncpy(_label, acBSP->Label(), 32);
			labelLen = strlen(acBSP->Label());
			if (no == 0){
			    strncat(_label, " Pilot", 32 - labelLen);
			}
			else {
			    char crewstr[20];
			    sprintf (crewstr, " Crew%d", no);
			    strncat(_label, crewstr, 32 - labelLen);
			}
			_label[31] = 0;
			_labelColor = acBSP->LabelColor();
		}
		else
		{
			_label[0] = 0;
			_labelColor = 0;
		}
	}
	else
	{
		strcpy(_label, "Pilot");
		labelLen = strlen(_label);
		_labelColor = 0;//acBSP->LabelColor();
	}
	
	_execCalledFromAircraft = FALSE;
	
	// Point to the aircraft that I ejected from.
	if (ac)
	{
		_aircraftId = ac->Id();
		_flightId = ac->GetCampaignObject()->Id();
	}

	// Update exec transfer synching data.
	_lastFrameCount = 0;
	//	_execCount = 0;

   // Act like a bomb, so nobody sees you
   // edg: yuck, we now have an eject pilot motion
   SetFlag(MOTION_BMB_AI);

   SetFlag(MOTION_EJECT_PILOT);

   if (IsLocal()) {
      SimVuDriver *drive = new SimVuDriver(this);
      drive->ExecDR(SimLibElapsedTime);
      SetDriver (drive);
   }
}
Exemple #5
0
bool CNetAddr::IsRoutable() const
{
    return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal() || IsInternal());
}
Exemple #6
0
OGRErr OGRSpatialReference::importFromOzi( const char * const* papszLines )
{
    int iLine;
    const char *pszDatum, *pszProj = NULL, *pszProjParms = NULL;

    Clear();

    int nLines = CSLCount((char**)papszLines);
    if( nLines < 5 )
        return OGRERR_NOT_ENOUGH_DATA;

    pszDatum = papszLines[4];

    for ( iLine = 5; iLine < nLines; iLine++ )
    {
        if ( EQUALN(papszLines[iLine], "Map Projection", 14) )
        {
            pszProj = papszLines[iLine];
        }
        else if ( EQUALN(papszLines[iLine], "Projection Setup", 16) )
        {
            pszProjParms = papszLines[iLine];
        }
    }

    if ( ! ( pszDatum && pszProj && pszProjParms ) )
        return OGRERR_NOT_ENOUGH_DATA;

/* -------------------------------------------------------------------- */
/*      Operate on the basis of the projection name.                    */
/* -------------------------------------------------------------------- */
    char    **papszProj = CSLTokenizeStringComplex( pszProj, ",", TRUE, TRUE );
    char    **papszProjParms = CSLTokenizeStringComplex( pszProjParms, ",", 
                                                         TRUE, TRUE );
    char    **papszDatum = NULL;
                                                         
    if (CSLCount(papszProj) < 2)
    {
        goto not_enough_data;
    }

    if ( EQUALN(papszProj[1], "Latitude/Longitude", 18) )
    {
    }

    else if ( EQUALN(papszProj[1], "Mercator", 8) )
    {
        if (CSLCount(papszProjParms) < 6) goto not_enough_data;
        double dfScale = CPLAtof(papszProjParms[3]);
        if (papszProjParms[3][0] == 0) dfScale = 1; /* if unset, default to scale = 1 */
        SetMercator( CPLAtof(papszProjParms[1]), CPLAtof(papszProjParms[2]),
                     dfScale,
                     CPLAtof(papszProjParms[4]), CPLAtof(papszProjParms[5]) );
    }

    else if ( EQUALN(papszProj[1], "Transverse Mercator", 19) )
    {
        if (CSLCount(papszProjParms) < 6) goto not_enough_data;
        SetTM( CPLAtof(papszProjParms[1]), CPLAtof(papszProjParms[2]),
               CPLAtof(papszProjParms[3]),
               CPLAtof(papszProjParms[4]), CPLAtof(papszProjParms[5]) );
    }

    else if ( EQUALN(papszProj[1], "Lambert Conformal Conic", 23) )
    {
        if (CSLCount(papszProjParms) < 8) goto not_enough_data;
        SetLCC( CPLAtof(papszProjParms[6]), CPLAtof(papszProjParms[7]),
                CPLAtof(papszProjParms[1]), CPLAtof(papszProjParms[2]),
                CPLAtof(papszProjParms[4]), CPLAtof(papszProjParms[5]) );
    }

    else if ( EQUALN(papszProj[1], "Sinusoidal", 10) )
    {
        if (CSLCount(papszProjParms) < 6) goto not_enough_data;
        SetSinusoidal( CPLAtof(papszProjParms[2]),
                       CPLAtof(papszProjParms[4]), CPLAtof(papszProjParms[5]) );
    }

    else if ( EQUALN(papszProj[1], "Albers Equal Area", 17) )
    {
        if (CSLCount(papszProjParms) < 8) goto not_enough_data;
        SetACEA( CPLAtof(papszProjParms[6]), CPLAtof(papszProjParms[7]),
                 CPLAtof(papszProjParms[1]), CPLAtof(papszProjParms[2]),
                 CPLAtof(papszProjParms[4]), CPLAtof(papszProjParms[5]) );
    }

    else if ( EQUALN(papszProj[1], "(UTM) Universal Transverse Mercator", 35) && nLines > 5 )
    {
        /* Look for the UTM zone in the calibration point data */
        for ( iLine = 5; iLine < nLines; iLine++ )
        {
            if ( EQUALN(papszLines[iLine], "Point", 5) )
            {
                char    **papszTok = NULL;
                papszTok = CSLTokenizeString2( papszLines[iLine], ",",
                                               CSLT_ALLOWEMPTYTOKENS
                                               | CSLT_STRIPLEADSPACES
                                               | CSLT_STRIPENDSPACES );
                if ( CSLCount(papszTok) < 17
                     || EQUAL(papszTok[2], "")
                     || EQUAL(papszTok[13], "")
                     || EQUAL(papszTok[14], "")
                     || EQUAL(papszTok[15], "")
                     || EQUAL(papszTok[16], "") )
                {
                    CSLDestroy(papszTok);
                    continue;
                }
                SetUTM( CPLAtofM(papszTok[13]), EQUAL(papszTok[16], "N") );
                CSLDestroy(papszTok);
                break;
            }
        }
        if ( iLine == nLines )    /* Try to guess the UTM zone */
        {
            float fMinLongitude = INT_MAX;
            float fMaxLongitude = INT_MIN;
            float fMinLatitude = INT_MAX;
            float fMaxLatitude = INT_MIN;
            int bFoundMMPLL = FALSE;
            for ( iLine = 5; iLine < nLines; iLine++ )
            {
                if ( EQUALN(papszLines[iLine], "MMPLL", 5) )
                {
                    char    **papszTok = NULL;
                    papszTok = CSLTokenizeString2( papszLines[iLine], ",",
                                                   CSLT_ALLOWEMPTYTOKENS
                                                   | CSLT_STRIPLEADSPACES
                                                   | CSLT_STRIPENDSPACES );
                    if ( CSLCount(papszTok) < 4 )
                    {
                        CSLDestroy(papszTok);
                        continue;
                    }
                    float fLongitude = CPLAtofM(papszTok[2]);
                    float fLatitude = CPLAtofM(papszTok[3]);
                    CSLDestroy(papszTok);

                    bFoundMMPLL = TRUE;

                    if ( fMinLongitude > fLongitude )
                        fMinLongitude = fLongitude;
                    if ( fMaxLongitude < fLongitude )
                        fMaxLongitude = fLongitude;
                    if ( fMinLatitude > fLatitude )
                        fMinLatitude = fLatitude;
                    if ( fMaxLatitude < fLatitude )
                        fMaxLatitude = fLatitude;
                }
            }
            float fMedianLatitude = ( fMinLatitude + fMaxLatitude ) / 2;
            float fMedianLongitude = ( fMinLongitude + fMaxLongitude ) / 2;
            if ( bFoundMMPLL && fMaxLatitude <= 90 )
            {
                int nUtmZone;
                if ( fMedianLatitude >= 56 && fMedianLatitude <= 64 && 
                     fMedianLongitude >= 3 && fMedianLongitude <= 12 )
                    nUtmZone = 32;                                             /* Norway exception */
                else if ( fMedianLatitude >= 72 && fMedianLatitude <= 84 && 
                         fMedianLongitude >= 0 && fMedianLongitude <= 42 )
                    nUtmZone = (int) ((fMedianLongitude + 3 ) / 12) * 2 + 31;  /* Svalbard exception */
                else
                    nUtmZone = (int) ((fMedianLongitude + 180 ) / 6) + 1;
                SetUTM( nUtmZone, fMedianLatitude >= 0 );
            }
            else
                CPLDebug( "OSR_Ozi", "UTM Zone not found");
        }
    }

    else if ( EQUALN(papszProj[1], "(I) France Zone I", 17) )
    {
        SetLCC1SP( 49.5, 2.337229167, 0.99987734, 600000, 1200000 );
    }

    else if ( EQUALN(papszProj[1], "(II) France Zone II", 19) )
    {
        SetLCC1SP( 46.8, 2.337229167, 0.99987742, 600000, 2200000 );
    }

    else if ( EQUALN(papszProj[1], "(III) France Zone III", 21) )
    {
        SetLCC1SP( 44.1, 2.337229167, 0.99987750, 600000, 3200000 );
    }

    else if ( EQUALN(papszProj[1], "(IV) France Zone IV", 19) )
    {
        SetLCC1SP( 42.165, 2.337229167, 0.99994471, 234.358, 4185861.369 );
    }

/*
 *  Note : The following projections have not been implemented yet
 *
 */

/*
    else if ( EQUALN(papszProj[1], "(BNG) British National Grid", 27) )
    {
    }

    else if ( EQUALN(papszProj[1], "(IG) Irish Grid", 15) )
    {
    }

    else if ( EQUALN(papszProj[1], "(NZG) New Zealand Grid", 22) )
    {
    }

    else if ( EQUALN(papszProj[1], "(NZTM2) New Zealand TM 2000", 27) )
    {
    }

    else if ( EQUALN(papszProj[1], "(SG) Swedish Grid", 27) )
    {
    }

    else if ( EQUALN(papszProj[1], "(SUI) Swiss Grid", 26) )
    {
    }

    else if ( EQUALN(papszProj[1], "(A)Lambert Azimuthual Equal Area", 32) )
    {
    }

    else if ( EQUALN(papszProj[1], "(EQC) Equidistant Conic", 23) )
    {
    }

    else if ( EQUALN(papszProj[1], "Polyconic (American)", 20) )
    {
    }

    else if ( EQUALN(papszProj[1], "Van Der Grinten", 15) )
    {
    }

    else if ( EQUALN(papszProj[1], "Vertical Near-Sided Perspective", 31) )
    {
    }

    else if ( EQUALN(papszProj[1], "(WIV) Wagner IV", 15) )
    {
    }

    else if ( EQUALN(papszProj[1], "Bonne", 5) )
    {
    }

    else if ( EQUALN(papszProj[1], "(MT0) Montana State Plane Zone 2500", 35) )
    {
    }

    else if ( EQUALN(papszProj[1], "ITA1) Italy Grid Zone 1", 23) )
    {
    }

    else if ( EQUALN(papszProj[1], "ITA2) Italy Grid Zone 2", 23) )
    {
    }

    else if ( EQUALN(papszProj[1], "(VICMAP-TM) Victoria Aust.(pseudo AMG)", 38) )
    {
    }

    else if ( EQUALN(papszProj[1], "VICGRID) Victoria Australia", 27) )
    {
    }

    else if ( EQUALN(papszProj[1], "(VG94) VICGRID94 Victoria Australia", 35) )
    {
    }

    else if ( EQUALN(papszProj[1], "Gnomonic", 8) )
    {
    }
*/

    else
    {
        CPLDebug( "OSR_Ozi", "Unsupported projection: \"%s\"", papszProj[1] );
        SetLocalCS( CPLString().Printf("\"Ozi\" projection \"%s\"",
                                       papszProj[1]) );
    }

/* -------------------------------------------------------------------- */
/*      Try to translate the datum/spheroid.                            */
/* -------------------------------------------------------------------- */
    papszDatum = CSLTokenizeString2( pszDatum, ",",
                                               CSLT_ALLOWEMPTYTOKENS
                                               | CSLT_STRIPLEADSPACES
                                               | CSLT_STRIPENDSPACES );
    if ( papszDatum == NULL)
        goto not_enough_data;
        
    if ( !IsLocal() )
    {

/* -------------------------------------------------------------------- */
/*      Verify that we can find the CSV file containing the datums      */
/* -------------------------------------------------------------------- */
        if( CSVScanFileByName( CSVFilename( "ozi_datum.csv" ),
                            "EPSG_DATUM_CODE",
                            "4326", CC_Integer ) == NULL )
        {
            CPLError( CE_Failure, CPLE_OpenFailed,
                    "Unable to open OZI support file %s.\n"
                    "Try setting the GDAL_DATA environment variable to point\n"
                    "to the directory containing OZI csv files.",
                    CSVFilename( "ozi_datum.csv" ) );
            goto other_error;
        }

/* -------------------------------------------------------------------- */
/*      Search for matching datum                                       */
/* -------------------------------------------------------------------- */
        const char *pszOziDatum = CSVFilename( "ozi_datum.csv" );
        CPLString osDName = CSVGetField( pszOziDatum, "NAME", papszDatum[0],
                                    CC_ApproxString, "NAME" );
        if( strlen(osDName) == 0 )
        {
            CPLError( CE_Failure, CPLE_AppDefined,
                    "Failed to find datum %s in ozi_datum.csv.",
                    papszDatum[0] );
            goto other_error;
        }

        int nDatumCode = atoi( CSVGetField( pszOziDatum, "NAME", papszDatum[0],
                                            CC_ApproxString, "EPSG_DATUM_CODE" ) );

        if ( nDatumCode > 0 ) // There is a matching EPSG code
        {
            OGRSpatialReference oGCS;
            oGCS.importFromEPSG( nDatumCode );
            CopyGeogCSFrom( &oGCS );
        }
        else // We use the parameters from the CSV files
        {
            CPLString osEllipseCode = CSVGetField( pszOziDatum, "NAME", papszDatum[0],
                                                CC_ApproxString, "ELLIPSOID_CODE" );
            double dfDeltaX = CPLAtof(CSVGetField( pszOziDatum, "NAME", papszDatum[0],
                                                CC_ApproxString, "DELTAX" ) );
            double dfDeltaY = CPLAtof(CSVGetField( pszOziDatum, "NAME", papszDatum[0],
                                                CC_ApproxString, "DELTAY" ) );
            double dfDeltaZ = CPLAtof(CSVGetField( pszOziDatum, "NAME", papszDatum[0],
                                                CC_ApproxString, "DELTAZ" ) );


    /* -------------------------------------------------------------------- */
    /*      Verify that we can find the CSV file containing the ellipsoids  */
    /* -------------------------------------------------------------------- */
            if( CSVScanFileByName( CSVFilename( "ozi_ellips.csv" ),
                                "ELLIPSOID_CODE",
                                "20", CC_Integer ) == NULL )
            {
                CPLError( CE_Failure, CPLE_OpenFailed,
                    "Unable to open OZI support file %s.\n"
                    "Try setting the GDAL_DATA environment variable to point\n"
                    "to the directory containing OZI csv files.",
                    CSVFilename( "ozi_ellips.csv" ) );
                goto other_error;
            }

    /* -------------------------------------------------------------------- */
    /*      Lookup the ellipse code.                                        */
    /* -------------------------------------------------------------------- */
            const char *pszOziEllipse = CSVFilename( "ozi_ellips.csv" );

            CPLString osEName = CSVGetField( pszOziEllipse, "ELLIPSOID_CODE", osEllipseCode,
                                        CC_ApproxString, "NAME" );
            if( strlen(osEName) == 0 )
            {
                CPLError( CE_Failure, CPLE_AppDefined,
                        "Failed to find ellipsoid %s in ozi_ellips.csv.",
                        osEllipseCode.c_str() );
                goto other_error;
            }

            double dfA = CPLAtof(CSVGetField( pszOziEllipse, "ELLIPSOID_CODE", osEllipseCode,
                                        CC_ApproxString, "A" ));
            double dfInvF = CPLAtof(CSVGetField( pszOziEllipse, "ELLIPSOID_CODE", osEllipseCode,
                                            CC_ApproxString, "INVF" ));

    /* -------------------------------------------------------------------- */
    /*      Create geographic coordinate system.                            */
    /* -------------------------------------------------------------------- */

            SetGeogCS( osDName, osDName, osEName, dfA, dfInvF );
            SetTOWGS84( dfDeltaX, dfDeltaY, dfDeltaZ );

        }
    }

/* -------------------------------------------------------------------- */
/*      Grid units translation                                          */
/* -------------------------------------------------------------------- */
    if( IsLocal() || IsProjected() )
        SetLinearUnits( SRS_UL_METER, 1.0 );

    FixupOrdering();

    CSLDestroy(papszProj);
    CSLDestroy(papszProjParms);
    CSLDestroy(papszDatum);

    return OGRERR_NONE;

not_enough_data:

    CSLDestroy(papszProj);
    CSLDestroy(papszProjParms);
    CSLDestroy(papszDatum);

    return OGRERR_NOT_ENOUGH_DATA;

other_error:

    CSLDestroy(papszProj);
    CSLDestroy(papszProjParms);
    CSLDestroy(papszDatum);

    return OGRERR_FAILURE;
}
Exemple #7
0
void UUnb
( AbstractDistMatrix<F>& APre,
  AbstractDistMatrix<F>& householderScalarsPre )
{
    DEBUG_CSE

    DistMatrixReadWriteProxy<F,F,MC,MR> AProx( APre );
    DistMatrixWriteProxy<F,F,STAR,STAR>
      householderScalarsProx( householderScalarsPre );
    auto& A = AProx.Get();
    auto& householderScalars = householderScalarsProx.Get();

    const Grid& g = A.Grid();
    const Int n = A.Height();
    const Int householderScalarsHeight = Max(n-1,0);
    householderScalars.SetGrid( g );
    householderScalars.Resize( householderScalarsHeight, 1 );

    DistMatrix<F,MC,STAR> a21_MC(g);
    DistMatrix<F,MR,STAR> a21_MR(g);
    DistMatrix<F,MC,STAR> x1_MC(g); 
    DistMatrix<F,MR,STAR> x12Adj_MR(g);

    for( Int k=0; k<n-1; ++k )
    {
        const Range<Int> ind1( k,   k+1 ),
                         ind2( k+1, n   );

        auto a21 = A( ind2,    ind1 );
        auto A22 = A( ind2,    ind2 );
        auto A2  = A( IR(0,n), ind2 );

        auto alpha21T = A( IR(k+1,k+2), ind1 );
        auto a21B     = A( IR(k+2,n),   ind1 );

        // Find tau and v such that
        //  / I - tau | 1 | | 1, v^H | \ | alpha21T | = | beta |
        //  \         | v |            / |     a21B |   |    0 |
        const F tau = LeftReflector( alpha21T, a21B );
        householderScalars.Set(k,0,tau);

        // Temporarily set a21 := | 1 |
        //                        | v |
        F beta=0;
        if( alpha21T.IsLocal(0,0) )
            beta = alpha21T.GetLocal(0,0);
        alpha21T.Set(0,0,F(1));

        // A2 := A2 Hous(a21,tau)^H
        //     = A2 (I - conj(tau) a21 a21^H)
        //     = A2 - conj(tau) (A2 a21) a21^H
        // -----------------------------------
        // x1 := A2 a21
        a21_MR.AlignWith( A2 );
        a21_MR = a21;
        x1_MC.AlignWith( A2 );
        Zeros( x1_MC, n, 1 );
        LocalGemv( NORMAL, F(1), A2, a21_MR, F(0), x1_MC );
        El::AllReduce( x1_MC, A2.RowComm() );
        // A2 := A2 - conj(tau) x1 a21^H
        LocalGer( -Conj(tau), x1_MC, a21_MR, A2 ); 

        // A22 := Hous(a21,tau) A22
        //      = (I - tau a21 a21^H) A22
        //      = A22 - tau a21 (A22^H a21)^H
        // ----------------------------------
        // x12^H := (a21^H A22)^H = A22^H a21
        a21_MC.AlignWith( A22 );
        a21_MC = a21;
        x12Adj_MR.AlignWith( A22 );
        Zeros( x12Adj_MR, A22.Width(), 1 );
        LocalGemv( ADJOINT, F(1), A22, a21_MC, F(0), x12Adj_MR );
        El::AllReduce( x12Adj_MR, A22.ColComm() );
        // A22 := A22 - tau a21 x12
        LocalGer( -tau, a21_MC, x12Adj_MR, A22 );

        // Put beta back 
        if( alpha21T.IsLocal(0,0) )
            alpha21T.SetLocal(0,0,beta);
    }
}
Exemple #8
0
/** \fn PreviewGenerator::RunReal(void)
 *  \brief This call creates a preview without starting a new thread.
 */
bool PreviewGenerator::RunReal(void)
{
    QString msg;
    QTime tm = QTime::currentTime();
    bool ok = false;
    bool is_local = IsLocal();

    if (!is_local && !!(mode & kRemote))
    {
        LOG(VB_GENERAL, LOG_ERR, LOC + QString("Run() file not local: '%1'")
                .arg(pathname));
    }
    else if (!(mode & kLocal) && !(mode & kRemote))
    {
        LOG(VB_GENERAL, LOG_ERR, LOC + QString("Run() Preview of '%1' failed "
                                               "because mode was invalid 0x%2")
                .arg(pathname).arg((int)mode,0,16));
    }
    else if (is_local && !!(mode & kLocal) && LocalPreviewRun())
    {
        ok = true;
        msg = QString("Generated on %1 in %2 seconds, starting at %3")
            .arg(gCoreContext->GetHostName())
            .arg(tm.elapsed()*0.001)
            .arg(tm.toString(Qt::ISODate));
    }
    else if (!!(mode & kRemote))
    {
        if (is_local && (mode & kLocal))
        {
            LOG(VB_GENERAL, LOG_WARNING, LOC + "Failed to save preview."
                    "\n\t\t\tYou may need to check user and group ownership on"
                    "\n\t\t\tyour frontend and backend for quicker previews.\n"
                    "\n\t\t\tAttempting to regenerate preview on backend.\n");
        }
        ok = RemotePreviewRun();
        if (ok)
        {
            msg = QString("Generated remotely in %1 seconds, starting at %2")
                .arg(tm.elapsed()*0.001)
                .arg(tm.toString(Qt::ISODate));
        }
        else
        {
            msg = "Remote preview failed";
        }
    }
    else
    {
        msg = "Could not access recording";
    }

    QMutexLocker locker(&previewLock);
    if (listener)
    {
        QString output_fn = outFileName.isEmpty() ?
            (programInfo.GetPathname()+".png") : outFileName;

        QDateTime dt;
        if (ok)
        {
            QFileInfo fi(output_fn);
            if (fi.exists())
                dt = fi.lastModified();
        }

        QString message = (ok) ? "PREVIEW_SUCCESS" : "PREVIEW_FAILED";
        QStringList list;
        list.push_back(programInfo.MakeUniqueKey());
        list.push_back(output_fn);
        list.push_back(msg);
        list.push_back(dt.isValid()?dt.toString(Qt::ISODate):"");
        list.push_back(token);
        QCoreApplication::postEvent(listener, new MythEvent(message, list));
    }

    return ok;
}
Exemple #9
0
bool PreviewGenerator::Run(void)
{
    QString msg;
    QDateTime dtm = QDateTime::currentDateTime();
    QTime tm = QTime::currentTime();
    bool ok = false;
    QString command = GetInstallPrefix() + "/bin/mythpreviewgen";
    bool local_ok = ((IsLocal() || !!(mode & kForceLocal)) &&
                     (!!(mode & kLocal)) &&
                     QFileInfo(command).isExecutable());
    if (!local_ok)
    {
        if (!!(mode & kRemote))
        {
            ok = RemotePreviewRun();
            if (ok)
            {
                msg =
                    QString("Generated remotely in %1 seconds, starting at %2")
                    .arg(tm.elapsed()*0.001)
                    .arg(tm.toString(Qt::ISODate));
            }
        }
        else
        {
            LOG(VB_GENERAL, LOG_ERR, LOC +
                QString("Run() cannot generate preview locally for: '%1'")
                    .arg(pathname));
            msg = "Failed, local preview requested for remote file.";
        }
    }
    else
    {
        // This is where we fork and run mythpreviewgen to actually make preview
        command += QString(" --size %1x%2")
            .arg(outSize.width()).arg(outSize.height());
        if (captureTime >= 0)
        {
            if (timeInSeconds)
                command += QString(" --seconds %1").arg(captureTime);
            else
                command += QString(" --frame %1").arg(captureTime);
        }
        command += QString(" --chanid %1").arg(programInfo.GetChanID());
        command += QString(" --starttime %1")
            .arg(programInfo.GetRecordingStartTime(MythDate));

        if (!outFileName.isEmpty())
            command += QString(" --outfile \"%1\"").arg(outFileName);

        command += logPropagateArgs;
        if (!logPropagateQuiet())
            command += " --quiet";

        // Timeout in 30s
        uint ret = myth_system(command, kMSDontBlockInputDevs |
                                        kMSDontDisableDrawing |
                                        kMSProcessEvents, 30);
        if (ret != GENERIC_EXIT_OK)
        {
            LOG(VB_GENERAL, LOG_ERR, LOC + 
                QString("Encountered problems running '%1' (%2)")
                    .arg(command) .arg(ret));
        }
        else
        {
            LOG(VB_PLAYBACK, LOG_INFO, LOC + "Preview process returned 0.");
            QString outname = (!outFileName.isEmpty()) ?
                outFileName : (pathname + ".png");

            QString lpath = QFileInfo(outname).fileName();
            if (lpath == outname)
            {
                StorageGroup sgroup;
                QString tmpFile = sgroup.FindFile(lpath);
                outname = (tmpFile.isEmpty()) ? outname : tmpFile;
            }

            QFileInfo fi(outname);
            ok = (fi.exists() && fi.isReadable() && fi.size());
            if (ok)
            {
                LOG(VB_PLAYBACK, LOG_INFO, LOC + "Preview process ran ok.");
                msg = QString("Generated on %1 in %2 seconds, starting at %3")
                    .arg(gCoreContext->GetHostName())
                    .arg(tm.elapsed()*0.001)
                    .arg(tm.toString(Qt::ISODate));
            }
            else
            {
                LOG(VB_GENERAL, LOG_ERR, LOC + "Preview process not ok." +
                    QString("\n\t\t\tfileinfo(%1)").arg(outname) +
                    QString(" exists: %1").arg(fi.exists()) +
                    QString(" readable: %1").arg(fi.isReadable()) +
                    QString(" size: %1").arg(fi.size()));
                LOG(VB_GENERAL, LOG_ERR, LOC +
                    QString("Despite command '%1' returning success")
                        .arg(command));
                msg = QString("Failed to read preview image despite "
                              "preview process returning success.");
            }
        }
    }

    QMutexLocker locker(&previewLock);

    // Backdate file to start of preview time in case a bookmark was made
    // while we were generating the preview.
    QString output_fn = outFileName.isEmpty() ?
        (programInfo.GetPathname()+".png") : outFileName;

    QDateTime dt;
    if (ok)
    {
        QFileInfo fi(output_fn);
        if (fi.exists())
            dt = fi.lastModified();
    }

    QString message = (ok) ? "PREVIEW_SUCCESS" : "PREVIEW_FAILED";
    if (listener)
    {
        QStringList list;
        list.push_back(programInfo.MakeUniqueKey());
        list.push_back(outFileName.isEmpty() ?
                       (programInfo.GetPathname()+".png") : outFileName);
        list.push_back(msg);
        list.push_back(dt.isValid()?dt.toString(Qt::ISODate):"");
        list.push_back(token);
        QCoreApplication::postEvent(listener, new MythEvent(message, list));
    }

    return ok;
}
Exemple #10
0
OGRErr OGRSpatialReference::exportToUSGS( long *piProjSys, long *piZone,
                                          double **ppadfPrjParams,
                                          long *piDatum ) const

{
    const char  *pszProjection = GetAttrValue("PROJECTION");

/* -------------------------------------------------------------------- */
/*      Fill all projection parameters with zero.                       */
/* -------------------------------------------------------------------- */
    int         i;

    *ppadfPrjParams = (double *)CPLMalloc( 15 * sizeof(double) );
    for ( i = 0; i < 15; i++ )
        (*ppadfPrjParams)[i] = 0.0;

    *piZone = 0L;

/* ==================================================================== */
/*      Handle the projection definition.                               */
/* ==================================================================== */
    if( IsLocal() )
        *piProjSys = GEO;

    else if( pszProjection == NULL )
    {
#ifdef DEBUG
        CPLDebug( "OSR_USGS",
                  "Empty projection definition, considered as Geographic" );
#endif
        *piProjSys = GEO;
    }

    else if( EQUAL(pszProjection, SRS_PT_ALBERS_CONIC_EQUAL_AREA) )
    {
        *piProjSys = ALBERS;
        (*ppadfPrjParams)[2] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_STANDARD_PARALLEL_1, 0.0 ) );
        (*ppadfPrjParams)[3] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_STANDARD_PARALLEL_2, 0.0 ) );
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ) );
        (*ppadfPrjParams)[5] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP) )
    {
        *piProjSys = LAMCC;
        (*ppadfPrjParams)[2] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_STANDARD_PARALLEL_1, 0.0 ) );
        (*ppadfPrjParams)[3] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_STANDARD_PARALLEL_2, 0.0 ) );
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ) );
        (*ppadfPrjParams)[5] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_MERCATOR_1SP) )
    {
        *piProjSys = MERCAT;
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ) );
        (*ppadfPrjParams)[5] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_POLAR_STEREOGRAPHIC) )
    {
        *piProjSys = PS;
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ) );
        (*ppadfPrjParams)[5] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_POLYCONIC) )
    {
        *piProjSys = POLYC;
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ) );
        (*ppadfPrjParams)[5] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_EQUIDISTANT_CONIC) )
    {
        *piProjSys = EQUIDC;
        (*ppadfPrjParams)[2] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_STANDARD_PARALLEL_1, 0.0 ) );
        (*ppadfPrjParams)[3] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_STANDARD_PARALLEL_2, 0.0 ) );
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ) );
        (*ppadfPrjParams)[5] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
        (*ppadfPrjParams)[8] = 1.0;
    }

    else if( EQUAL(pszProjection, SRS_PT_TRANSVERSE_MERCATOR) )
    {
        int bNorth;

        *piZone = GetUTMZone( &bNorth );

        if( *piZone != 0 )
        {
            *piProjSys = UTM;
            if( !bNorth )
                *piZone = - *piZone;
        }            
        else
        {
            *piProjSys = TM;
            (*ppadfPrjParams)[2] = GetNormProjParm( SRS_PP_SCALE_FACTOR, 1.0 );
            (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
                GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ) );
            (*ppadfPrjParams)[5] = CPLDecToPackedDMS(
                GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ) );
            (*ppadfPrjParams)[6] =
                GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
            (*ppadfPrjParams)[7] =
                GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
        }
    }

    else if( EQUAL(pszProjection, SRS_PT_STEREOGRAPHIC) )
    {
        *piProjSys = STEREO;
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ) );
        (*ppadfPrjParams)[5] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_LAMBERT_AZIMUTHAL_EQUAL_AREA) )
    {
        *piProjSys = LAMAZ;
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ) );
        (*ppadfPrjParams)[5] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_AZIMUTHAL_EQUIDISTANT) )
    {
        *piProjSys = AZMEQD;
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LONGITUDE_OF_CENTER, 0.0 ) );
        (*ppadfPrjParams)[5] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LATITUDE_OF_CENTER, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_GNOMONIC) )
    {
        *piProjSys = GNOMON;
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ) );
        (*ppadfPrjParams)[5] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_ORTHOGRAPHIC) )
    {
        *piProjSys = ORTHO;
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ) );
        (*ppadfPrjParams)[5] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_SINUSOIDAL) )
    {
        *piProjSys = SNSOID;
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LONGITUDE_OF_CENTER, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_EQUIRECTANGULAR) )
    {
        *piProjSys = EQRECT;
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ) );
        (*ppadfPrjParams)[5] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_STANDARD_PARALLEL_1, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_MILLER_CYLINDRICAL) )
    {
        *piProjSys = MILLER;
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LONGITUDE_OF_CENTER, 0.0 ) );
        (*ppadfPrjParams)[5] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LATITUDE_OF_CENTER, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_VANDERGRINTEN) )
    {
        *piProjSys = VGRINT;
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LONGITUDE_OF_CENTER, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_HOTINE_OBLIQUE_MERCATOR) )
    {
        *piProjSys = HOM;
        (*ppadfPrjParams)[2] = GetNormProjParm( SRS_PP_SCALE_FACTOR, 1.0 );
        (*ppadfPrjParams)[3] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_AZIMUTH, 0.0 ) );
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LONGITUDE_OF_CENTER, 0.0 ) );
        (*ppadfPrjParams)[5] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LATITUDE_OF_CENTER, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
        (*ppadfPrjParams)[12] = 1.0;
    }

    else if( EQUAL(pszProjection,
                   SRS_PT_HOTINE_OBLIQUE_MERCATOR_TWO_POINT_NATURAL_ORIGIN) )
    {
        *piProjSys = HOM;
        (*ppadfPrjParams)[2] = GetNormProjParm( SRS_PP_SCALE_FACTOR, 1.0 );
        (*ppadfPrjParams)[5] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LATITUDE_OF_CENTER, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
        (*ppadfPrjParams)[8] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LONGITUDE_OF_POINT_1, 0.0 ) );
        (*ppadfPrjParams)[9] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LATITUDE_OF_POINT_1, 0.0 ) );
        (*ppadfPrjParams)[10] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LONGITUDE_OF_POINT_2, 0.0 ) );
        (*ppadfPrjParams)[11] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LATITUDE_OF_POINT_2, 0.0 ) );
        (*ppadfPrjParams)[12] = 0.0;
    }

    else if( EQUAL(pszProjection, SRS_PT_ROBINSON) )
    {
        *piProjSys = ROBIN;
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_LONGITUDE_OF_CENTER, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_MOLLWEIDE) )
    {
        *piProjSys = MOLL;
        (*ppadfPrjParams)[4] = CPLDecToPackedDMS(
            GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ) );
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_WAGNER_IV) )
    {
        *piProjSys = WAGIV;
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    else if( EQUAL(pszProjection, SRS_PT_WAGNER_VII) )
    {
        *piProjSys = WAGVII;
        (*ppadfPrjParams)[6] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 );
        (*ppadfPrjParams)[7] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 );
    }

    // Projection unsupported by GCTP
    else
    {
        CPLDebug( "OSR_USGS",
                  "Projection \"%s\" unsupported by USGS GCTP. "
                  "Geographic system will be used.", pszProjection );
        *piProjSys = GEO;
    }
 
/* -------------------------------------------------------------------- */
/*      Translate the datum.                                            */
/* -------------------------------------------------------------------- */
    const char  *pszDatum = GetAttrValue( "DATUM" );

    if ( pszDatum )
    {
        if( EQUAL( pszDatum, SRS_DN_NAD27 ) )
            *piDatum = CLARKE1866;

        else if( EQUAL( pszDatum, SRS_DN_NAD83 ) )
            *piDatum = GRS1980;

        else if( EQUAL( pszDatum, SRS_DN_WGS84 ) )
            *piDatum = WGS84;

        // If not found well known datum, translate ellipsoid
        else
        {
            double      dfSemiMajor = GetSemiMajor();
            double      dfInvFlattening = GetInvFlattening();

#ifdef DEBUG
            CPLDebug( "OSR_USGS",
                      "Datum \"%s\" unsupported by USGS GCTP. "
                      "Try to translate ellipsoid definition.", pszDatum );
#endif
            
            for ( i = 0; i < NUMBER_OF_ELLIPSOIDS; i++ )
            {
                double  dfSM;
                double  dfIF;

                if ( OSRGetEllipsoidInfo( aoEllips[i], NULL,
                                          &dfSM, &dfIF ) == OGRERR_NONE
                    && CPLIsEqual( dfSemiMajor, dfSM )
                    && CPLIsEqual( dfInvFlattening, dfIF ) )
                {
                    *piDatum = i;
                    break;
                }
            }

            if ( i == NUMBER_OF_ELLIPSOIDS )    // Didn't found matches; set
            {                                   // custom ellipsoid parameters
#ifdef DEBUG
                CPLDebug( "OSR_USGS",
                          "Ellipsoid \"%s\" unsupported by USGS GCTP. "
                          "Custom ellipsoid definition will be used.",
                          pszDatum );
#endif
                *piDatum = -1;
                (*ppadfPrjParams)[0] = dfSemiMajor;
                if ( ABS( dfInvFlattening ) < 0.000000000001 )
                {
                    (*ppadfPrjParams)[1] = dfSemiMajor;
                }
                else
                {
                    (*ppadfPrjParams)[1] =
                        dfSemiMajor * (1.0 - 1.0/dfInvFlattening);
                }
            }
        }
    }
    else
        *piDatum = -1;

    return OGRERR_NONE;
}
Exemple #11
0
bool PreviewGenerator::Run(void)
{
    QString msg;
    QDateTime dtm = MythDate::current();
    QTime tm = QTime::currentTime();
    bool ok = false;
    QString command = GetAppBinDir() + "mythpreviewgen";
    bool local_ok = ((IsLocal() || !!(m_mode & kForceLocal)) &&
                     (!!(m_mode & kLocal)) &&
                     QFileInfo(command).isExecutable());
    if (!local_ok)
    {
        if (!!(m_mode & kRemote))
        {
            ok = RemotePreviewRun();
            if (ok)
            {
                msg =
                    QString("Generated remotely in %1 seconds, starting at %2")
                    .arg(tm.elapsed()*0.001)
                    .arg(tm.toString(Qt::ISODate));
            }
        }
        else
        {
            LOG(VB_GENERAL, LOG_ERR, LOC +
                QString("Run() cannot generate preview locally for: '%1'")
                    .arg(m_pathname));
            msg = "Failed, local preview requested for remote file.";
        }
    }
    else
    {
        // This is where we fork and run mythpreviewgen to actually make preview
        QStringList cmdargs;

        cmdargs << "--size"
                << QString("%1x%2").arg(m_outSize.width()).arg(m_outSize.height());
        if (m_captureTime >= 0)
        {
            if (m_timeInSeconds)
                cmdargs << "--seconds";
            else
                cmdargs << "--frame";
            cmdargs << QString::number(m_captureTime);
        }
        cmdargs << "--chanid"
                << QString::number(m_programInfo.GetChanID())
                << "--starttime"
                << m_programInfo.GetRecordingStartTime(MythDate::kFilename);

        if (!m_outFileName.isEmpty())
            cmdargs << "--outfile" << m_outFileName;

        // Timeout in 30s
        MythSystemLegacy *ms = new MythSystemLegacy(command, cmdargs,
                                        kMSDontBlockInputDevs |
                                        kMSDontDisableDrawing |
                                        kMSProcessEvents      |
                                        kMSAutoCleanup        |
                                        kMSPropagateLogs);
        ms->SetNice(10);
        ms->SetIOPrio(7);

        ms->Run(30);
        uint ret = ms->Wait();
        delete ms;

        if (ret != GENERIC_EXIT_OK)
        {
            LOG(VB_GENERAL, LOG_ERR, LOC +
                QString("Encountered problems running '%1 %2' - (%3)")
                    .arg(command).arg(cmdargs.join(" ")).arg(ret));
        }
        else
        {
            LOG(VB_PLAYBACK, LOG_INFO, LOC + "Preview process returned 0.");
            QString outname = (!m_outFileName.isEmpty()) ?
                m_outFileName : (m_pathname + ".png");

            QString lpath = QFileInfo(outname).fileName();
            if (lpath == outname)
            {
                StorageGroup sgroup;
                QString tmpFile = sgroup.FindFile(lpath);
                outname = (tmpFile.isEmpty()) ? outname : tmpFile;
            }

            QFileInfo fi(outname);
            ok = (fi.exists() && fi.isReadable() && fi.size());
            if (ok)
            {
                LOG(VB_PLAYBACK, LOG_INFO, LOC + "Preview process ran ok.");
                msg = QString("Generated on %1 in %2 seconds, starting at %3")
                    .arg(gCoreContext->GetHostName())
                    .arg(tm.elapsed()*0.001)
                    .arg(tm.toString(Qt::ISODate));
            }
            else
            {
                LOG(VB_GENERAL, LOG_ERR, LOC + "Preview process not ok." +
                    QString("\n\t\t\tfileinfo(%1)").arg(outname) +
                    QString(" exists: %1").arg(fi.exists()) +
                    QString(" readable: %1").arg(fi.isReadable()) +
                    QString(" size: %1").arg(fi.size()));
                LOG(VB_GENERAL, LOG_ERR, LOC +
                    QString("Despite command '%1' returning success")
                        .arg(command));
                msg = QString("Failed to read preview image despite "
                              "preview process returning success.");
            }
        }
    }

    QMutexLocker locker(&m_previewLock);

    // Backdate file to start of preview time in case a bookmark was made
    // while we were generating the preview.
    QString output_fn = m_outFileName.isEmpty() ?
        (m_programInfo.GetPathname()+".png") : m_outFileName;

    QDateTime dt;
    if (ok)
    {
        QFileInfo fi(output_fn);
        if (fi.exists())
            dt = fi.lastModified();
    }

    QString message = (ok) ? "PREVIEW_SUCCESS" : "PREVIEW_FAILED";
    if (m_listener)
    {
        QStringList list;
        list.push_back(QString::number(m_programInfo.GetRecordingID()));
        list.push_back(output_fn);
        list.push_back(msg);
        list.push_back(dt.isValid()?dt.toUTC().toString(Qt::ISODate):"");
        list.push_back(m_token);
        QCoreApplication::postEvent(m_listener, new MythEvent(message, list));
    }

    return ok;
}
Exemple #12
0
OGRErr OGRSpatialReference::importFromUSGS( long iProjSys, long iZone,
                                            double *padfPrjParams,
                                            long iDatum, 
                                            int nUSGSAngleFormat  )

{
    if( !padfPrjParams )
        return OGRERR_CORRUPT_DATA;

    double (*pfnUnpackAnglesFn)(double) = NULL;

    if (nUSGSAngleFormat == USGS_ANGLE_DECIMALDEGREES )
        pfnUnpackAnglesFn = OGRSpatialReferenceUSGSUnpackNoOp;
    else if (nUSGSAngleFormat == USGS_ANGLE_RADIANS )
        pfnUnpackAnglesFn = OGRSpatialReferenceUSGSUnpackRadian;
    else
        pfnUnpackAnglesFn = CPLPackedDMSToDec;

/* -------------------------------------------------------------------- */
/*      Operate on the basis of the projection code.                    */
/* -------------------------------------------------------------------- */
    switch ( iProjSys )
    {
        case GEO:
            break;

        case UTM:
            {
                int bNorth = TRUE;

                if ( !iZone )
                {
                    if ( padfPrjParams[2] != 0.0 )
                        iZone = (long) padfPrjParams[2];
                    else if (padfPrjParams[0] != 0.0 && padfPrjParams[1] != 0.0)
                    {
                        iZone = (long)(((pfnUnpackAnglesFn(padfPrjParams[0])
                                         + 180.0) / 6.0) + 1.0);
                        if ( pfnUnpackAnglesFn(padfPrjParams[0]) < 0 )
                            bNorth = FALSE;
                    }
                }

                if ( iZone < 0 )
                {
                    iZone = -iZone;
                    bNorth = FALSE;
                }
                SetUTM( iZone, bNorth );
            }
            break;

        case SPCS:
            {
                int bNAD83 = TRUE;

                if ( iDatum == 0 )
                    bNAD83 = FALSE;
                else if ( iDatum != 8 )
                    CPLError( CE_Warning, CPLE_AppDefined,
                              "Wrong datum for State Plane projection %d. "
                              "Should be 0 or 8.", (int) iDatum );
                
                SetStatePlane( iZone, bNAD83 );
            }
            break;

        case ALBERS:
            SetACEA( pfnUnpackAnglesFn(padfPrjParams[2]),
                     pfnUnpackAnglesFn(padfPrjParams[3]),
                     pfnUnpackAnglesFn(padfPrjParams[5]),
                     pfnUnpackAnglesFn(padfPrjParams[4]),
                     padfPrjParams[6], padfPrjParams[7] );
            break;

        case LAMCC:
            SetLCC( pfnUnpackAnglesFn(padfPrjParams[2]),
                    pfnUnpackAnglesFn(padfPrjParams[3]),
                    pfnUnpackAnglesFn(padfPrjParams[5]),
                    pfnUnpackAnglesFn(padfPrjParams[4]),
                    padfPrjParams[6], padfPrjParams[7] );
            break;

        case MERCAT:
            SetMercator( pfnUnpackAnglesFn(padfPrjParams[5]),
                         pfnUnpackAnglesFn(padfPrjParams[4]),
                         1.0,
                         padfPrjParams[6], padfPrjParams[7] );
            break;

        case PS:
            SetPS( pfnUnpackAnglesFn(padfPrjParams[5]),
                   pfnUnpackAnglesFn(padfPrjParams[4]),
                   1.0,
                   padfPrjParams[6], padfPrjParams[7] );

            break;

        case POLYC:
            SetPolyconic( pfnUnpackAnglesFn(padfPrjParams[5]),
                          pfnUnpackAnglesFn(padfPrjParams[4]),
                          padfPrjParams[6], padfPrjParams[7] );
            break;

        case EQUIDC:
            if ( padfPrjParams[8] )
            {
                SetEC( pfnUnpackAnglesFn(padfPrjParams[2]),
                       pfnUnpackAnglesFn(padfPrjParams[3]),
                       pfnUnpackAnglesFn(padfPrjParams[5]),
                       pfnUnpackAnglesFn(padfPrjParams[4]),
                       padfPrjParams[6], padfPrjParams[7] );
            }
            else
            {
                SetEC( pfnUnpackAnglesFn(padfPrjParams[2]),
                       pfnUnpackAnglesFn(padfPrjParams[2]),
                       pfnUnpackAnglesFn(padfPrjParams[5]),
                       pfnUnpackAnglesFn(padfPrjParams[4]),
                       padfPrjParams[6], padfPrjParams[7] );
            }
            break;

        case TM:
            SetTM( pfnUnpackAnglesFn(padfPrjParams[5]),
                   pfnUnpackAnglesFn(padfPrjParams[4]),
                   padfPrjParams[2],
                   padfPrjParams[6], padfPrjParams[7] );
            break;

        case STEREO:
            SetStereographic( pfnUnpackAnglesFn(padfPrjParams[5]),
                              pfnUnpackAnglesFn(padfPrjParams[4]),
                              1.0,
                              padfPrjParams[6], padfPrjParams[7] );
            break;

        case LAMAZ:
            SetLAEA( pfnUnpackAnglesFn(padfPrjParams[5]),
                     pfnUnpackAnglesFn(padfPrjParams[4]),
                     padfPrjParams[6], padfPrjParams[7] );
            break;

        case AZMEQD:
            SetAE( pfnUnpackAnglesFn(padfPrjParams[5]),
                   pfnUnpackAnglesFn(padfPrjParams[4]),
                   padfPrjParams[6], padfPrjParams[7] );
            break;

        case GNOMON:
            SetGnomonic( pfnUnpackAnglesFn(padfPrjParams[5]),
                         pfnUnpackAnglesFn(padfPrjParams[4]),
                         padfPrjParams[6], padfPrjParams[7] );
            break;

        case ORTHO:
            SetOrthographic( pfnUnpackAnglesFn(padfPrjParams[5]),
                             pfnUnpackAnglesFn(padfPrjParams[4]),
                             padfPrjParams[6], padfPrjParams[7] );
            break;

        // FIXME: GVNSP --- General Vertical Near-Side Perspective skipped

        case SNSOID:
            SetSinusoidal( pfnUnpackAnglesFn(padfPrjParams[4]),
                           padfPrjParams[6], padfPrjParams[7] );
            break;

        case EQRECT:
            SetEquirectangular2( 0.0,
                                 pfnUnpackAnglesFn(padfPrjParams[4]),
                                 pfnUnpackAnglesFn(padfPrjParams[5]),
                                 padfPrjParams[6], padfPrjParams[7] );
            break;

        case MILLER:
            SetMC( pfnUnpackAnglesFn(padfPrjParams[5]),
                   pfnUnpackAnglesFn(padfPrjParams[4]),
                   padfPrjParams[6], padfPrjParams[7] );
            break;

        case VGRINT:
            SetVDG( pfnUnpackAnglesFn(padfPrjParams[4]),
                    padfPrjParams[6], padfPrjParams[7] );
            break;

        case HOM:
            if ( padfPrjParams[12] )
            {
                SetHOM( pfnUnpackAnglesFn(padfPrjParams[5]),
                        pfnUnpackAnglesFn(padfPrjParams[4]),
                        pfnUnpackAnglesFn(padfPrjParams[3]),
                        0.0, padfPrjParams[2],
                        padfPrjParams[6],  padfPrjParams[7] );
            }
            else
            {
                SetHOM2PNO( pfnUnpackAnglesFn(padfPrjParams[5]),
                            pfnUnpackAnglesFn(padfPrjParams[9]),
                            pfnUnpackAnglesFn(padfPrjParams[8]),
                            pfnUnpackAnglesFn(padfPrjParams[11]),
                            pfnUnpackAnglesFn(padfPrjParams[10]),
                            padfPrjParams[2],
                            padfPrjParams[6],  padfPrjParams[7] );
            }
            break;

        case ROBIN:
            SetRobinson( pfnUnpackAnglesFn(padfPrjParams[4]),
                         padfPrjParams[6], padfPrjParams[7] );
            break;

        // FIXME: SOM --- Space Oblique Mercator skipped

        // FIXME: ALASKA --- Alaska Conformal skipped

        // FIXME: GOODE --- Interrupted Goode skipped

        case MOLL:
            SetMollweide( pfnUnpackAnglesFn(padfPrjParams[4]),
                          padfPrjParams[6], padfPrjParams[7] );
            break;

        // FIXME: IMOLL --- Interrupted Mollweide skipped

        // FIXME: HAMMER --- Hammer skipped

        case WAGIV:
            SetWagner( 4, 0.0, padfPrjParams[6], padfPrjParams[7] );
            break;

        case WAGVII:
            SetWagner( 7, 0.0, padfPrjParams[6], padfPrjParams[7] );
            break;

        // FIXME: OBEQA --- Oblated Equal Area skipped

        // FIXME: ISINUS1 --- Integerized Sinusoidal Grid (the same as 99) skipped
        
        // FIXME: CEA --- Cylindrical Equal Area skipped (Grid corners set in meters for EASE grid)

        // FIXME: BCEA --- Cylindrical Equal Area skipped (Grid corners set in DMS degs for EASE grid)

        // FIXME: ISINUS --- Integrized Sinusoidal skipped

        default:
            CPLDebug( "OSR_USGS", "Unsupported projection: %ld", iProjSys );
            SetLocalCS( CPLString().Printf("GCTP projection number %ld", iProjSys) );
            break;
            
    }

/* -------------------------------------------------------------------- */
/*      Try to translate the datum/spheroid.                            */
/* -------------------------------------------------------------------- */

    if ( !IsLocal() )
    {
        char    *pszName = NULL;
        double  dfSemiMajor, dfInvFlattening;

        if ( iDatum < 0  ) // Use specified ellipsoid parameters
        {
            if ( padfPrjParams[0] > 0.0 )
            {
                if ( padfPrjParams[1] > 1.0 )
                {
                    if( ABS(padfPrjParams[0] - padfPrjParams[1]) < 0.01 )
                        dfInvFlattening = 0.0;
                    else
                    {
                        dfInvFlattening = padfPrjParams[0]
                            / ( padfPrjParams[0] - padfPrjParams[1] );
                    }
                }
                else if ( padfPrjParams[1] > 0.0 )
                {
                    dfInvFlattening =
                        1.0 / ( 1.0 - sqrt(1.0 - padfPrjParams[1]) );
                }
                else
                    dfInvFlattening = 0.0;

                SetGeogCS( "Unknown datum based upon the custom spheroid",
                           "Not specified (based on custom spheroid)",
                           "Custom spheroid", padfPrjParams[0], dfInvFlattening,
                           NULL, 0, NULL, 0 );
            }
            else if ( padfPrjParams[1] > 0.0 )  // Clarke 1866
            {
                if ( OSRGetEllipsoidInfo( 7008, &pszName, &dfSemiMajor,
                                          &dfInvFlattening ) == OGRERR_NONE )
                {
                    SetGeogCS( CPLString().Printf(
                                    "Unknown datum based upon the %s ellipsoid",
                                    pszName ),
                               CPLString().Printf( 
                                    "Not specified (based on %s spheroid)",
                                    pszName ),
                               pszName, dfSemiMajor, dfInvFlattening,
                               NULL, 0.0, NULL, 0.0 );
                    SetAuthority( "SPHEROID", "EPSG", 7008 );
                }
            }
            else                              // Sphere, rad 6370997 m
            {
                if ( OSRGetEllipsoidInfo( 7047, &pszName, &dfSemiMajor,
                                     &dfInvFlattening ) == OGRERR_NONE )
                {
                    SetGeogCS( CPLString().Printf(
                                    "Unknown datum based upon the %s ellipsoid",
                                    pszName ),
                               CPLString().Printf(
                                    "Not specified (based on %s spheroid)",
                                    pszName ),
                               pszName, dfSemiMajor, dfInvFlattening,
                               NULL, 0.0, NULL, 0.0 );
                    SetAuthority( "SPHEROID", "EPSG", 7047 );
                }
            }

        }
        else if ( iDatum < NUMBER_OF_ELLIPSOIDS && aoEllips[iDatum] )
        {
            if( OSRGetEllipsoidInfo( aoEllips[iDatum], &pszName,
                                     &dfSemiMajor, &dfInvFlattening ) == OGRERR_NONE )
            {
                SetGeogCS( CPLString().Printf("Unknown datum based upon the %s ellipsoid",
                                              pszName ),
                           CPLString().Printf( "Not specified (based on %s spheroid)",
                                               pszName ),
                           pszName, dfSemiMajor, dfInvFlattening,
                           NULL, 0.0, NULL, 0.0 );
                SetAuthority( "SPHEROID", "EPSG", aoEllips[iDatum] );
            }
            else
            {
                CPLError( CE_Warning, CPLE_AppDefined,
                          "Failed to lookup datum code %d, likely due to missing GDAL gcs.csv\n"
                          " file.  Falling back to use WGS84.", 
                          (int) iDatum );
                SetWellKnownGeogCS("WGS84" );
            }
        }
        else
        {
            CPLError( CE_Warning, CPLE_AppDefined,
                      "Wrong datum code %d. Supported datums 0--%d only.\n"
                      "Setting WGS84 as a fallback.",
                      (int) iDatum, NUMBER_OF_ELLIPSOIDS );
            SetWellKnownGeogCS( "WGS84" );
        }

        if ( pszName )
            CPLFree( pszName );
    }

/* -------------------------------------------------------------------- */
/*      Grid units translation                                          */
/* -------------------------------------------------------------------- */
    if( IsLocal() || IsProjected() )
        SetLinearUnits( SRS_UL_METER, 1.0 );

    FixupOrdering();

    return OGRERR_NONE;
}
Exemple #13
0
int GroundTaskingManagerClass::Task (void)
{               
	int			done = 0;
	int			count=0,collect;
	int			action;

	// Don't do this if we're not active, or not owned by this machine
	if (!(TeamInfo[owner]->flags & TEAM_ACTIVE) || !IsLocal())
		return 0;

	action = TeamInfo[owner]->GetGroundActionType();

	// Check for offensive grinding to a halt
	if (action == GACTION_OFFENSIVE && TeamInfo[owner]->GetGroundAction()->actionPoints == 0)
	{
		TeamInfo[owner]->SelectGroundAction();
		action = TeamInfo[owner]->GetGroundActionType();
	}

#ifdef DEBUG
	ulong	time;//,newtime;
	time = GetTickCount();
#endif

	Cleanup();

	// Choose types of orders we can give
	collect = COLLECT_AIRDEFENSE | COLLECT_SUPPORT | COLLECT_REPAIR | COLLECT_RESERVE | COLLECT_DEFEND | COLLECT_RADAR;
	if (action == GACTION_OFFENSIVE)
		collect |= COLLECT_CAPTURE | COLLECT_ASSAULT | COLLECT_AIRBORNE | COLLECT_COMMANDO | COLLECT_SECURE;
	else if (action == GACTION_MINOROFFENSIVE)
		collect |= COLLECT_SECURE;
	else if (action == GACTION_CONSOLIDATE)
		collect |= COLLECT_SECURE;

#ifdef KEV_GDEBUG
	ulong	ltime;
	ltime = GetTickCount();
#endif

	if (CollectGroundAssets(collect))
	{
#ifdef KEV_GDEBUG
		ListBuildTime = GetTickCount() - ltime;
#endif
		// Give orders based on action type
		switch (action)
		{
				case GACTION_OFFENSIVE:
						// Full offensive - priorities are offensive, securing, then defense
						AssignUnits (GORD_CAPTURE, GTM_MODE_FASTEST);
						//				if (NavalSuperiority(owner) >= STATE_CONTESTED)
						AssignUnits (GORD_ASSAULT, GTM_MODE_BEST);
						//				if (AirSuperiority(owner) >= STATE_CONTESTED)
						{
							AssignUnits (GORD_AIRBORNE, GTM_MODE_BEST);
							AssignUnits (GORD_COMMANDO, GTM_MODE_BEST);
						}
						AssignUnits (GORD_SECURE, GTM_MODE_FASTEST);
						AssignUnits (GORD_DEFEND, GTM_MODE_BEST);
						break;
				case GACTION_MINOROFFENSIVE:
						// Consolidation/Counterattack phase - priorities are securing objectives then defense
						AssignUnits (GORD_SECURE, GTM_MODE_BEST);
						AssignUnits (GORD_DEFEND, GTM_MODE_BEST);
				case GACTION_CONSOLIDATE:	
						// Cautious consolidation phase - priorities are defense, then securing objectives
						AssignUnits (GORD_DEFEND, GTM_MODE_FASTEST);
						AssignUnits (GORD_SECURE, GTM_MODE_BEST);
						break;
				case GACTION_DEFENSIVE:
				default:
						// Defensive posture - priorities are defense only
						AssignUnits (GORD_DEFEND, GTM_MODE_FASTEST);
						break;
		}

		// Now do the things we do all the time:
		AssignUnits (GORD_AIRDEFENSE, GTM_MODE_FASTEST);
		AssignUnits (GORD_SUPPORT, GTM_MODE_FASTEST);
		AssignUnits (GORD_REPAIR, GTM_MODE_FASTEST);
		AssignUnits (GORD_RADAR, GTM_MODE_FASTEST);
		AssignUnits (GORD_RESERVE, GTM_MODE_BEST);
	}

	// Check if our tasking failed to meet at least 50 of our offensive requests
	if (sOffensiveDesired && sOffensiveAssigned < sOffensiveDesired/2)
		TeamInfo[owner]->GetGroundAction()->actionPoints = 0;

#ifdef KEV_GDEBUG
	int i;
	MonoPrint("Assigned:     ");
	for (i=0; i<GORD_LAST; i++)
		MonoPrint("%3d  ",AssignedCount[i]);
	MonoPrint("%3d\n",Assigned);
	MonoPrint("Time (s):     ");
	for (i=0; i<GORD_LAST; i++)
		MonoPrint("%3.1f  ",(float)(Time[i]/1000.0F));
	MonoPrint("\n");
#endif

	Cleanup();

#ifdef KEV_GDEBUG
	newtime = GetTickCount();
	MonoPrint("Ground tasking for team %d: %d ms\n",owner,newtime-time);
#endif

	return Assigned;
}
Exemple #14
0
void GroundTaskingManagerClass::DoCalculations(void)
{
	Objective		o;
	int				score,fs,es,i;
	float			d;
	Team			t;
	GridIndex		x,y;
	POData			pd;

	// Don't do this if we're not active, or not owned by this machine
	if (!(TeamInfo[owner]->flags & TEAM_ACTIVE) || !IsLocal())
		return;

	topPriority = 0;
	VuListIterator	poit(POList);
	o = GetFirstObjective(&poit);
	while (o != NULL)
	{
		// Get score for proximity to front
		o->GetLocation(&x,&y);
		d = DistanceToFront(x,y);
		fs = FloatToInt32((200.0F - d) * 0.2F);

		t = o->GetTeam();
		pd = GetPOData(o);
		es = 0;
		// Get score for enemy strength
		if (d < 100.0F)
		{
			for (i=1; i<NUM_TEAMS; i++)
			{
				if (GetRoE(owner,i,ROE_GROUND_FIRE))
					es += pd->ground_assigned[i]/50;	// 1 assignment pt = 1 vehicle, so 1 enemy strength pt per 50 vehs..
			}
			if (es > 30)
				es = 30;								// Cap enemy strength after 1500 vehicles
			if (owner != t)
				es = -es + (rand()%5) - 2;
		}

		score = fs + es + (rand()%5);
		if (o->GetObjectivePriority() > 95)
			score += 50;
		if (o->GetObjectivePriority() > 90)
			score += 20;
		else
			score += o->GetObjectivePriority() - 80;

		//		os = (o->GetObjectivePriority()-80)*3;
		//		score = os + fs + es + (rand()%5);

		if (score < 0)
			score = 0;
		if (score > 100)
			score = 100;
		// Minimum of 1 priority if it's owned by us.
		if (!score && t == owner)
			score = 1;

		// KCK: AI's air and ground priorities are identical for now
		if (!(pd->flags & GTMOBJ_SCRIPTED_PRIORITY))
		{
			pd->ground_priority[owner] = score;
			pd->air_priority[owner] = score;
			// KCK: player_priority only used now if it's >= 0
			//			if (!(pd->flags & GTMOBJ_PLAYER_SET_PRIORITY))
			//				pd->player_priority[owner] = pd->air_priority[owner];
		}

		if (!GetRoE(owner,t,ROE_GROUND_CAPTURE) && owner != t)
			pd->ground_priority[owner] = 0;
		if (!GetRoE(owner,t,ROE_AIR_ATTACK) && owner != t)
			pd->air_priority[owner] = 0;

		if (score > topPriority)
		{
			topPriority = score;
			priorityObj = o->GetCampID();
		}
		o = GetNextObjective(&poit);
	}
}
/*
** GroundClass Exec() function.
** NOTE: returns TRUE if we've processed this frame.  FALSE if we're to do
** dead reckoning (in VU)
*/
int GroundClass::Exec (void)
{
	//RV - I-Hawk - Added a 0 vector for RV new PS calls
	Tpoint PSvec;
	PSvec.x = 0;
	PSvec.y = 0;
	PSvec.z = 0;

	Tpoint pos;
    Tpoint vec;
	float speedScale;
	float groundZ;
	float	labelLOD;
	float	drawLOD;
	RadarClass *radar = NULL;
	
	SoundPos.UpdatePos((SimBaseClass *)this);

	//Cobra
	pos.x = 0.0f;
	pos.y = 0.0f;
	pos.z = 0.0f;
	
	// MLR 5/23/2004 -
	pos.x = XPos();
	pos.y = YPos();
	pos.z = OTWDriver.GetApproxGroundLevel( pos.x, pos.y );
//	pos.z = -10.0f;//Cobra trying to fix the stupid uninit CTD
	SetPosition(pos.x, pos.y, pos.z);

	// dead? -- we do nothing
	if ( IsDead() ){
		return FALSE;
	}

    // if damaged 
	if ( pctStrength < 0.5f ){
		if (sfxTimer > 1.5f - gai->distLOD * 1.3){
			// reset the timer
			sfxTimer = 0.0f;
			pos.z -= 10.0f;

			// VP_changes this shoud be checked why have GetGroundLevel been subtracted by 10.0F
			// Sometimes the trails seem strange
			vec.x = PRANDFloat() * 20.0f;
			vec.y = PRANDFloat() * 20.0f;
			vec.z = PRANDFloat() * 20.0f;
			
			/*
			OTWDriver.AddSfxRequest(
				new SfxClass(
					SFX_TRAILSMOKE,			// type
					SFX_MOVES | SFX_NO_GROUND_CHECK,						// flags
					&pos,							// world pos
					&vec,							// vector
					3.5f,							// time to live
					4.5f					// scale
				)
			);
					*/
			DrawableParticleSys::PS_AddParticleEx((SFX_TRAILSMOKE + 1),
									&pos,
									&vec);
			
		}
	}
	
	if (IsExploding()){
		// KCK: I've never seen this section of code executed. Maybe it gets hit, but I doubt
		// it.
		if (!IsSetFlag( SHOW_EXPLOSION )){
			// Show the explosion
			Tpoint pos, vec;
			Falcon4EntityClassType *classPtr = (Falcon4EntityClassType *)EntityType();
			//DrawableGroundVehicle *destroyedPtr; // FRB

			//Cobra TJL 11/07/04 CTD point initialize here
			pos.x = 0.0f;
			pos.y = 0.0f;
			pos.z = 0.0f;
			
			// MLR 5/23/2004 - uncommented out the x, y
			pos.x = XPos();
			pos.y = YPos();
			pos.z = OTWDriver.GetApproxGroundLevel( pos.x, pos.y ) - 10.0f;
			
			vec.x = 0.0f;
			vec.y = 0.0f;
			vec.z = 0.0f;
			
			// create a new drawable for destroyed vehicle
			// sometimes.....

           //RV - I-Hawk - Commenting all this if statement... not necessary

			/*
			if ( rand() & 1 ){
				destroyedPtr = new DrawableGroundVehicle(
					classPtr->visType[3],
					&pos,
					Yaw(),
					1.0f 
				);
				
				groundZ = PRANDFloatPos() * 60.0f + 15.0f;
				
				/*
				OTWDriver.AddSfxRequest(
					new SfxClass (
						SFX_BURNING_PART,				// type
						&pos,							// world pos
						&vec,							// 
						(DrawableBSP *)destroyedPtr,
						groundZ,							// time to live
						1.0f 	// scale
					)
				);	
						*/
			/*
				DrawableParticleSys::PS_AddParticleEx((SFX_BURNING_PART + 1),
									&pos,
									&vec);
				
				
				pos.z += 10.0f;
				/*
				OTWDriver.AddSfxRequest(
					new SfxClass(
						SFX_FEATURE_EXPLOSION,				// type
						&pos,							// world pos
						groundZ,							// time to live
						100.0f 		// scale
					) 
				);
						*/
			/*
				DrawableParticleSys::PS_AddParticleEx((SFX_FEATURE_EXPLOSION + 1),
									&pos,
									&PSvec);

			}
			*/
			//RV - I-Hawk - seperating explosion type for ground/sea domains. also
			//adding a check so soldiers will not explode like ground vehicles...

            if (GetDomain() == DOMAIN_LAND && GetType() != TYPE_FOOT)
			{		
				//pos.z -= 20.0f;
				/*
				OTWDriver.AddSfxRequest(
					new SfxClass(
						SFX_VEHICLE_EXPLOSION,				// type
						&pos,							// world pos
						1.5f,							// time to live
						100.0f 		// scale
					)
				);
					*/
				DrawableParticleSys::PS_AddParticleEx((SFX_VEHICLE_EXPLOSION + 1),
										&pos,
										&PSvec);
			}
			else if ( GetDomain() == DOMAIN_SEA )
			{
				DrawableParticleSys::PS_AddParticleEx((SFX_WATER_FIREBALL + 1),
										&pos,
										&PSvec);
			}

			// make sure we don't do it again...
			SetFlag( SHOW_EXPLOSION );
			
			// we can now kill it immediately
			SetDead(TRUE);  
		}
		return FALSE;
	}
	
	// exec any base functionality
	SimVehicleClass::Exec();
	
	// Sept 30, 2002
	// VP_changes: Frequently Z value is not in the correct place. It should follow the terrain.
	if ( drawPointer ){
		drawPointer->GetPosition( &pos );
	}
	else {
		return FALSE;
	}

	//JAM 27Sep03 - Let's try this
	groundZ = pos.z;		// - 0.7f; KCK: WTF is this?

	//VP_changes Sept 25
	groundZ = OTWDriver.GetGroundLevel( pos.x, pos.y );


	// Movement/Targeting for local entities
	if (IsLocal() && SimDriver.MotionOn())
	{
		//I commented this out, because it is done in gai->ProcessTargeting down below DSP 4/30/99
		// Refresh our target pointer (if any)
		//SetTarget( SimCampHandoff( targetPtr, targetList, HANDOFF_RANDOM ) );
		// Look for someone to do radar fire control for us
		FindBattalionFireControl();

		// RV - Biker - Switch on lights for ground/naval vehicles
		int isNight = TimeOfDayGeneral(TheCampaign.CurrentTime) < TOD_DAWNDUSK ? true : false;

		if (drawPointer && ((DrawableBSP *)drawPointer)->GetNumSwitches() >= AIRDEF_LIGHT_SWITCH) 
		{
			if (isShip) 
			{
				isNight = (TimeOfDayGeneral(TheCampaign.CurrentTime) <= TOD_DAWNDUSK || realWeather->weatherCondition == INCLEMENT) ? true : false;

				if (pctStrength > 0.50f) 
				{
					((DrawableBSP *)drawPointer)->SetSwitchMask(0, isNight);
					((DrawableBSP *)drawPointer)->SetSwitchMask(AIRDEF_LIGHT_SWITCH, isNight);
				}
			}
			else if (GetVt() > 1.0f) 
			{
				VuListIterator	vehicleWalker(SimDriver.combinedList);
				FalconEntity* object = (FalconEntity*)vehicleWalker.GetFirst();
				bool hasThreat = false;
				float range = 999.9f * NM_TO_FT;

				// Consider each potential target in our environment
				while (object && !hasThreat) 
				{
					// Skip sleeping sim objects
					if (object->IsSim()) 
					{
						if (!((SimBaseClass*)object)->IsAwake()) 
						{
							object = (FalconEntity*)vehicleWalker.GetNext();
							continue;
						}
					}

					// Fow now we skip missles -- might want to display them eventually...
					if (object->IsMissile() || object->IsBomb()) 
					{
						object = (FalconEntity*)vehicleWalker.GetNext();
						continue;
					}

					if (object->GetTeam() == GetTeam()) 
					{
						object = (FalconEntity*)vehicleWalker.GetNext();
						continue;
					}

					float dx = object->XPos() - XPos();
					float dy = object->YPos() - YPos();
					float dz = object->ZPos() - ZPos();

					range = (float)sqrt(dx*dx + dy*dy + dz*dz);

					if (range < 5.0f * NM_TO_FT)
						hasThreat = true;

					object = (FalconEntity*)vehicleWalker.GetNext();
				}

				// If no enemy nearby and not heavy damaged switch on lights
				if (!hasThreat && pctStrength > 0.75f) {
					((DrawableBSP *)drawPointer)->SetSwitchMask(AIRDEF_LIGHT_SWITCH, isNight);
				}
				else 
				{
					((DrawableBSP *)drawPointer)->SetSwitchMask(AIRDEF_LIGHT_SWITCH, 0);
				}	
			}
			else 
			{
				((DrawableBSP *)drawPointer)->SetSwitchMask(AIRDEF_LIGHT_SWITCH, 0);
			}
		}

		// RV - Biker - Do also switch on lights for tractor vehicles
		if (truckDrawable && truckDrawable->GetNumSwitches() >= AIRDEF_LIGHT_SWITCH) 
		{
			if (GetVt() > 1.0f) 
			{
				VuListIterator	vehicleWalker(SimDriver.combinedList);
				FalconEntity* object = (FalconEntity*)vehicleWalker.GetFirst();
				bool hasThreat = false;
				float range = 999.9f * NM_TO_FT;

				// Consider each potential target in our environment
				while (object && !hasThreat) 
				{
					// Skip sleeping sim objects
					if (object->IsSim()) 
					{
						if (!((SimBaseClass*)object)->IsAwake()) 
						{
							object = (FalconEntity*)vehicleWalker.GetNext();
							continue;
						}
					}

					// Fow now we skip missles -- might want to display them eventually...
					if (object->IsMissile() || object->IsBomb()) 
					{
						object = (FalconEntity*)vehicleWalker.GetNext();
						continue;
					}

					if (object->GetTeam() == GetTeam()) 
					{
						object = (FalconEntity*)vehicleWalker.GetNext();
						continue;
					}

					float dx = object->XPos() - XPos();
					float dy = object->YPos() - YPos();
					float dz = object->ZPos() - ZPos();

					range = (float)sqrt(dx*dx + dy*dy + dz*dz);

					if (range < 5.0f * NM_TO_FT)
						hasThreat = true;

					object = (FalconEntity*)vehicleWalker.GetNext();
				}

				// If no enemy nearby and not heavy damaged switch on lights
				if (!hasThreat && pctStrength > 0.75f) {
					truckDrawable->SetSwitchMask(AIRDEF_LIGHT_SWITCH, isNight);
				}
				else 
				{
					truckDrawable->SetSwitchMask(AIRDEF_LIGHT_SWITCH, 0);
				}
			}
			else 
			{
				truckDrawable->SetSwitchMask(AIRDEF_LIGHT_SWITCH, 0);
			}
		}
		
		// RV - Biker - Shut down ship radar if damaged
		if (isShip && radarDown == false && pctStrength < 0.9f && rand()%50 > (pctStrength - 0.50f)*100) 
		{
			isEmitter = false;
			RadarClass *radar = (RadarClass*)FindSensor(this, SensorClass::Radar);
			if (radar) 
			{
				radarDown = true;
				radar->SetDesiredTarget(NULL);
				radar->SetEmitting(FALSE);
			}

			if (targetPtr) 
			{
				SelectWeapon(true);
			}
		}
		
		// 2001-03-26 ADDED BY S.G. NEED TO KNOW IF THE RADAR CALLED SetSpotted
		// RV - Biker - Rotate radars
		float deltaDOF;
		float curDOF = GetDOFValue(5);
		
		deltaDOF = 180.0f * DTR * SimLibMajorFrameTime;
		curDOF += deltaDOF;
		
		if ( curDOF > 360.0f * DTR )
	  		curDOF -= 360.0f * DTR;

		SetDOF(5, curDOF);
		int spottedSet = FALSE;
		// END OF ADDED SECTION

		// 2002-03-21 ADDED BY S.G. 
		// If localData only has zeros, 
		// there is a good chance they are not valid (should not happen here though)... 
		if (targetPtr) {
			SimObjectLocalData* localData= targetPtr->localData;
			if (
				localData->ataFrom == 0.0f && 
				localData->az == 0.0f  && 
				localData->el == 0.0f && 
				localData->range == 0.0f
			) {
				CalcRelAzElRangeAta(this, targetPtr);
			}
		}
		// END OF ADDED SECTION 2002-03-21

		// check for sending radar emmisions
		// 2002-02-26 MODIFIED BY S.G.
		// Added the nextTargetUpdate check to prevent the radar code to run on every frame!
		if ( isEmitter && nextTargetUpdate < SimLibElapsedTime){
			// 2002-02-26 ADDED BY S.G. Next radar scan is 1 sec for aces, 2 for vets, etc ...
			nextTargetUpdate = SimLibElapsedTime + (5 - gai->skillLevel) * SEC_TO_MSEC; 

			radar = (RadarClass*)FindSensor( this, SensorClass::Radar );
			ShiAssert( radar );
			if (radar){
				radar->Exec( targetList );
			}

			// 2001-03-26 ADDED BY S.G. 
			// IF WE CAN SEE THE RADAR'S TARGET AND WE ARE A AIR DEFENSE THINGY 
			// NOT IN A BKOGEN MORAL STATE, MARK IT AS SPOTTED IF WE'RE BRIGHT ENOUGH
			if (
				radar && 
				radar->CurrentTarget() && 
				gai->skillLevel >= 3 && 
				((UnitClass *)GetCampaignObject())->GetSType() == STYPE_UNIT_AIR_DEFENSE && 
				!((UnitClass *)GetCampaignObject())->Broken()
			){
				CampBaseClass *campBaseObj;
				if (radar->CurrentTarget()->BaseData()->IsSim()){
					campBaseObj = ((SimBaseClass *)radar->CurrentTarget()->BaseData())->GetCampaignObject();
				}
				else{
					campBaseObj = (CampBaseClass *)radar->CurrentTarget()->BaseData();
				}

				// JB 011002 If campBaseObj is NULL the target may be chaff
				if (campBaseObj && !(campBaseObj->GetSpotted(GetTeam())) && campBaseObj->IsFlight()){
					RequestIntercept((FlightClass *)campBaseObj, GetTeam());
				}

				spottedSet = TRUE;
				if (campBaseObj && radar->GetRadarDatFile()){
					campBaseObj->SetSpotted(
						GetTeam(), TheCampaign.CurrentTime, 
						(radar->radarData->flag & RAD_NCTR) != 0 && 
						radar->CurrentTarget()->localData && 
						radar->CurrentTarget()->localData->ataFrom < 45.0f * DTR && 
						radar->CurrentTarget()->localData->range < 
						radar->GetRadarDatFile()->MaxNctrRange / (2.0f * (16.0f - (float)gai->skillLevel) / 16.0f)
					);
				}
				// 2002-03-05 MODIFIED BY S.G. target's aspect and skill used in the equation
			}
		// END OF ADDED SECTION
		}

		// 2001-03-26 ADDED BY S.G. 
		// IF THE BATTALION LEAD HAS LOS 
		// ON IT AND WE ARE A AIR DEFENSE THINGY NOT IN A BKOGEN MORAL STATE, 
		// MARK IT AS SPOTTED IF WE'RE BRIGHT ENOUGH
		// 2002-02-11 MODIFED BY S.G. 
		// Since I only identify visually, need to perform this even if spotted by radar in case I can ID it.
		if (
			/*!spottedSet &&  gai->skillLevel >= 3 && */
			((UnitClass *)GetCampaignObject())->GetSType() == STYPE_UNIT_AIR_DEFENSE && 
			gai == gai->battalionCommand && 
			!((UnitClass *)GetCampaignObject())->Broken() && 
			gai->GetAirTargetPtr() && 
			CheckLOS(gai->GetAirTargetPtr())
		){
			CampBaseClass *campBaseObj;
			if (gai->GetAirTargetPtr()->BaseData()->IsSim())
				campBaseObj = ((SimBaseClass *)gai->GetAirTargetPtr()->BaseData())->GetCampaignObject();
			else
				campBaseObj = (CampBaseClass *)gai->GetAirTargetPtr()->BaseData();

			// JB 011002 If campBaseObj is NULL the target may be chaff

			if (!spottedSet && campBaseObj && !(campBaseObj->GetSpotted(GetTeam())) && campBaseObj->IsFlight())
				RequestIntercept((FlightClass *)campBaseObj, GetTeam());

			if (campBaseObj)
				campBaseObj->SetSpotted(GetTeam(),TheCampaign.CurrentTime, 1);
				// 2002-02-11 MODIFIED BY S.G. Visual detection means identified as well
		}
		// END OF ADDED SECTION

		// KCK: When should we run a target update cycle?
		if (SimLibElapsedTime > lastProcess){
			gai->ProcessTargeting();
			lastProcess = SimLibElapsedTime + processRate;
		}

		// KCK: Check if it's ok to think
		if (SimLibElapsedTime > lastThought ){
			// do movement and (possibly) firing....
			gai->Process ();
			lastThought = SimLibElapsedTime + thoughtRate;
		}

		// RV - Biker - Only allow SAM fire if radar still does work
		SimWeaponClass *theWeapon = Sms->GetCurrentWeapon();

		// FRB - This version seems to give SAMs a little more activity
		if(SimLibElapsedTime > nextSamFireTime  && !allowSamFire){
			allowSamFire = TRUE;
		}

		// Biker's version
		//if(SimLibElapsedTime > nextSamFireTime  && !allowSamFire)
		//{
		//	if (radarDown == false || (theWeapon && theWeapon->IsMissile() && theWeapon->sensorArray[0]->Type() == SensorClass::IRST))
		//		allowSamFire = TRUE;
		//}

		// Move and update delta;
		gai->Move_Towards_Dest();
		
		// edg: always insure that our Z position is valid for the entity.
		// the draw pointer should have this value
		// KCK NOTE: The Z we have is actually LAST FRAME's Z. Probably not a big deal.
		SetPosition(
			XPos() + XDelta() * SimLibMajorFrameTime,
			YPos() + YDelta() * SimLibMajorFrameTime,
			groundZ 
		);
		// do firing
		// this also does weapon keep alive
		if ( Sms ){
			gai->Fire();
		}
	}

	// KCK: I simplified this some. This is now speed squared.
	speedScale = XDelta()*XDelta() + YDelta()*YDelta();
	
	// set our level of detail
	if ( gai == gai->battalionCommand ){
		gai->SetDistLOD();
	}
	else{
		gai->distLOD = gai->battalionCommand->distLOD;
	}
	
	// do some extra LOD stuff: if the unit is not a lead veh amd the
	// distLOD is less than a certain value, remove it from the draw
	// list.
	if (drawPointer && gai->rank != GNDAI_BATTALION_COMMANDER){
		// distLOD cutoff by ranking (KCK: This is explicit for testing, could be a formula/table)
		if (gai->rank & GNDAI_COMPANY_LEADER){
			labelLOD = .5F;
			drawLOD = .25F;
		}
		else if (gai->rank & GNDAI_PLATOON_LEADER){
			labelLOD = .925F;
			drawLOD = .5F;
		}
		else {
			labelLOD = 1.1F;
			drawLOD = .75F;
		}

		// RV - Biker - Why do this maybe helpful knowing which vehicle has problems
		// Determine wether to draw label or not
		if (gai->distLOD < labelLOD){
			if (!IsSetLocalFlag(NOT_LABELED)){
				drawPointer->SetLabel ("", 0xff00ff00);		// Don't label
				SetLocalFlag(NOT_LABELED);
			}
		}
		else if (IsSetLocalFlag(NOT_LABELED)){
			SetLabel(this);
			UnSetLocalFlag(NOT_LABELED);
		}

		//if (IsSetLocalFlag(NOT_LABELED)) {
		//	SetLabel(this);
		//	UnSetLocalFlag(NOT_LABELED);
		//}
	}
	
	if (!targetPtr){
		//rotate turret to be pointing forward again
		float maxAz = TURRET_ROTATE_RATE * SimLibMajorFrameTime;
		float maxEl = TURRET_ELEVATE_RATE * SimLibMajorFrameTime;
		float newEl;
		if (isAirDefense){
			newEl = 60.0F*DTR;
		}
		else {
			newEl = 0.0F;
		}

		float delta = newEl - GetDOFValue(AIRDEF_ELEV);
		if(delta > 180.0F*DTR){
			delta -= 180.0F*DTR;
		}
		else if(delta < -180.0F*DTR){
			delta += 180.0F*DTR;
		}

		// Do elevation adjustments
		if (delta > maxEl){
		    SetDOFInc(AIRDEF_ELEV, maxEl);
		}
		else if (delta < -maxEl){
		    SetDOFInc(AIRDEF_ELEV, -maxEl);
		}
		else {
		    SetDOF(AIRDEF_ELEV, newEl);
		}

		SetDOF(AIRDEF_ELEV, min(85.0F*DTR, max(GetDOFValue(AIRDEF_ELEV), 0.0F)));
		SetDOF(AIRDEF_ELEV2, GetDOFValue(AIRDEF_ELEV));
		
		delta = 0.0F - GetDOFValue(AIRDEF_AZIMUTH);
		
		if(delta > 180.0F*DTR){
		    delta -= 180.0F*DTR;
		}
		else if(delta < -180.0F*DTR){
		    delta += 180.0F*DTR;
		}
		
		// Now do the azmuth adjustments
		if (delta > maxAz){
		    SetDOFInc(AIRDEF_AZIMUTH, maxAz);
		}
		else if (delta < -maxAz){
		    SetDOFInc(AIRDEF_AZIMUTH, -maxAz);
		}
		// RV - Biker - Don't do this
		//else
		//	SetDOF(AIRDEF_AZIMUTH, 0.0F);
	}
	
	// Special shit by ground type
	if ( isFootSquad ){
		if ( speedScale > 0.0f ){
			// Couldn't this be done in the drawable class's update function???
			((DrawableGuys*)drawPointer)->SetSquadMoving( TRUE );
		}
		else {
			// Couldn't this be done in the drawable class's update function???
			((DrawableGuys*)drawPointer)->SetSquadMoving( FALSE );
		}
		
		// If we're less than 80% of the way from "FAR" toward the viewer, just draw one guy
		// otherwise, put 5 guys in a squad.
		if (gai->distLOD < 0.8f) {
			((DrawableGuys*)drawPointer)->SetNumInSquad( 1 );
		} 
		else {
			((DrawableGuys*)drawPointer)->SetNumInSquad( 5 );
		}
	} 
	// We're not a foot squad, so do the vehicle stuff
	else if ( !IsSetLocalFlag( IS_HIDDEN ) && speedScale > 300.0f )
	{
		// speedScale /= ( 900.0f * KPH_TO_FPS * KPH_TO_FPS);		// essentially 1.0F at 30 mph

	    // JPO - for engine noise
	    VehicleClassDataType *vc = GetVehicleClassData(Type() - VU_LAST_ENTITY_TYPE);
	    ShiAssert(FALSE == F4IsBadReadPtr(vc, sizeof *vc));
		// (a) Make sound:
		// everything sounds like a tank right now
		if ( GetCampaignObject()->IsBattalion() ){
		    //if (vc)
			if (vc && vc->EngineSound!=34){ // kludge prevent 34 from playing
				SoundPos.Sfx( vc->EngineSound, 0, 1.0, 0); // MLR 5/16/2004 - 
			}
			else{
				SoundPos.Sfx( SFX_TANK, 0, 1.0, 0); // MLR 5/16/2004 - 
			}
			
			// (b) Make dust
			// dustTimer += SimLibMajorFrameTime;
			// if ( dustTimer > max( 0.2f,  4.5f - speedScale - gai->distLOD * 3.3f ) )
			if ( ((rand() & 7) == 7) &&
				gSfxCount[ SFX_GROUND_DUSTCLOUD ] < gSfxLODCutoff &&
				gTotSfx < gSfxLODTotCutoff 
			){
				// reset the timer
				// dustTimer = 0.0f;
				
				pos.x += PRANDFloat() * 5.0f;
				pos.y += PRANDFloat() * 5.0f;
				pos.z = groundZ;

				// RV - Biker - Move that smoke more behind the vehicle 
				mlTrig		trig;
				mlSinCos (&trig, Yaw());

				pos.x -= 15.0f*trig.cos;
				pos.y -= 15.0f*trig.sin;

				vec.x = PRANDFloat() * 5.0f;
				vec.y = PRANDFloat() * 5.0f;
				vec.z = -20.0f;
				
				//JAM 24Oct03 - No dust trails when it's raining.
				if(realWeather->weatherCondition < INCLEMENT){
					/*
					OTWDriver.AddSfxRequest(
						new SfxClass (SFX_VEHICLE_DUST,				// type //JAM 03Oct03
	//					new SfxClass (SFX_GROUND_DUSTCLOUD,			// type
						SFX_USES_GRAVITY | SFX_NO_DOWN_VECTOR | SFX_MOVES | SFX_NO_GROUND_CHECK,
						&pos,							// world pos
						&vec,
						1.0f,							// time to live
						1.f)); //JAM 03Oct03 8.5f ));		// scale
						*/
					DrawableParticleSys::PS_AddParticleEx((SFX_VEHICLE_DUST + 1),
									&pos,
									&vec);
				}
			}
			
			// (c) Make sure we're using our 'Moving' model (i.e. Trucked artillery, APC, etc)
			if (truckDrawable){
				// Keep truck 20 feet behind us (HACK HACK)
				Tpoint		truckPos;
				mlTrig		trig;
				mlSinCos (&trig, Yaw());
				truckPos.x = XPos()-20.0F*trig.cos;
				truckPos.y = YPos()-20.0F*trig.sin;
				truckPos.z = ZPos();
				truckDrawable->Update(&truckPos, Yaw()+PI);
			}

			if (isTowed || hasCrew){
				SetSwitch(0,0x2);
			}
		}
		else // itsa task force
		{
			if (vc){
				SoundPos.Sfx( vc->EngineSound, 0, 1.0, 0);
			}
			else {
				SoundPos.Sfx( SFX_SHIP, 0, 1.0, 0);
			}
			
			//RV - I-Hawk - Do wakes only at some cases
			if ( (rand() & 7) == 7 )
			{
				//I-Hawk - not using all this anymore
				//
				// reset the timer
				// dustTimer = 0.0f;
				//float ttl;
				//static float trailspd = 5.0f;
				//static float bowfx = 0.92f;
				//static float sternfx = 0.75f;
				//float spdratio = GetVt() / ((UnitClass*)GetCampaignObject())->GetMaxSpeed();

				float radius;
				if ( drawPointer ){
					radius = drawPointer->Radius(); // JPO from 0.15 - now done inline
				}
				else{
					radius = 90.0f;
				}
				
				//I-Hawk - Fixed position for ships wakes, effect "delay" in position is 
				//handled by PS now. No more the "V shape" of water wakes.

				pos.x = XPos() + XDelta() * SimLibMajorFrameTime;
				pos.y = YPos() + YDelta() * SimLibMajorFrameTime;
				pos.z = groundZ;

				//// JPO - think this is sideways on.
				///*
				//vec.x = dmx[1][0] * spdratio * PRANDFloat() * trailspd;
				//vec.y = dmx[1][1] * spdratio * PRANDFloat() * trailspd;
				//vec.z = 0.5f; // from -20 JPO
				//*/

				//I-Hawk - More correct vector for wakes
				vec.x = XDelta();
				vec.y = YDelta();
				vec.z = 0.0f;


				//I-Hawk - Separate wake effect for different ships size
				int theSFX;
			
				if ( radius < 200.0f )
				{
					theSFX = SFX_WATER_WAKE_SMALL;
				}

				else if ( radius >= 200.0f && radius < 400.0f )
				{
					theSFX = SFX_WATER_WAKE_MEDIUM;
				}

				else if ( radius >= 400.0f )
				{
					theSFX = SFX_WATER_WAKE_LARGE;
				}
	
				//I-Hawk - The PS
				DrawableParticleSys::PS_AddParticleEx((theSFX + 1),
									&pos,
									&vec);
			}
		}
	}
	// Otherwise, we're not moving or are hidden. Do some stuff
	else {
		// (b) Make sure we're using our 'Holding' model (i.e. Unlimbered artillery, troops prone, etc)
		if (truckDrawable){
			// Once we stop, our truck doesn't move at all - but sits further away than when moving
			Tpoint truckPos;
			truckPos.x = XPos() + 40.0F;
			truckPos.y = YPos();
			truckPos.z = 0.0F;
			truckDrawable->Update(&truckPos, Yaw());
		}
		if (isTowed || hasCrew){
			SetSwitch(0,0x1);
		}
	}
	
	// ACMI Output
    if (gACMIRec.IsRecording() && (SimLibFrameCount & 0x0f ) == 0){
		ACMIGenPositionRecord genPos;
		genPos.hdr.time = SimLibElapsedTime * MSEC_TO_SEC + OTWDriver.todOffset;
		genPos.data.type = Type();
		genPos.data.uniqueID = ACMIIDTable->Add(Id(),NULL,TeamInfo[GetTeam()]->GetColor());//.num_;
		genPos.data.x = XPos();
		genPos.data.y = YPos();
		genPos.data.z = ZPos();
		genPos.data.roll = Roll();
		genPos.data.pitch = Pitch();
		genPos.data.yaw = Yaw();
		// Remove		genPos.data.teamColor = TeamInfo[GetTeam()]->GetColor();
		gACMIRec.GenPositionRecord( &genPos );
	}

	return IsLocal();
}
Exemple #16
0
////////////////////////////////////////////////////////////////////
//                                                                //
// Implementation: CefRequestHandler::OnBeforeResourceLoad        //
// http://magpcss.org/ceforum/apidocs3/projects/(default)/CefRequestHandler.html#OnBeforeResourceLoad(CefRefPtr%3CCefBrowser%3E,CefRefPtr%3CCefFrame%3E,CefRefPtr%3CCefRequest%3E) //
//                                                                //
////////////////////////////////////////////////////////////////////
CefRequestHandler::ReturnValue CWebView::OnBeforeResourceLoad ( CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request, CefRefPtr<CefRequestCallback> callback )
{
    // Mostly the same as CWebView::OnBeforeBrowse
    CefURLParts urlParts;
    if ( !CefParseURL ( request->GetURL (), urlParts ) )
        return RV_CANCEL; // Cancel if invalid URL (this line will normally not be executed)

    // Add some information to the HTTP header
    {
        CefRequest::HeaderMap headerMap;
        request->GetHeaderMap ( headerMap );
        auto iter = headerMap.find ( "User-Agent" );

        if ( iter != headerMap.end () )
        {
            // Add MTA:SA "watermark"
            iter->second = iter->second.ToString () + "; " MTA_CEF_USERAGENT;

            // Add 'Android' to get the mobile version
            SString strPropertyValue;
            if ( GetProperty ( "mobile", strPropertyValue ) && strPropertyValue == "1" )
                iter->second = iter->second.ToString () + "; Mobile Android";

            request->SetHeaderMap ( headerMap );
        }
    }

    WString scheme = urlParts.scheme.str;
    if ( scheme == L"http" || scheme == L"https" )
    {
        SString domain = UTF16ToMbUTF8 ( urlParts.host.str );
        if ( domain != "mta" )
        {
            if ( IsLocal () )
                return RV_CANCEL; // Block remote requests in local mode generally

            eURLState urlState = g_pCore->GetWebCore ()->GetURLState ( domain, true );
            if ( urlState != eURLState::WEBPAGE_ALLOWED )
            {
                // Trigger onClientBrowserResourceBlocked event
                auto func = std::bind ( &CWebBrowserEventsInterface::Events_OnResourceBlocked, m_pEventsInterface,
                    SString ( request->GetURL () ), domain, urlState == eURLState::WEBPAGE_NOT_LISTED ? 0 : 1 );
                g_pCore->GetWebCore ()->AddEventToEventQueue ( func, this, "OnResourceBlocked" );

                return RV_CANCEL; // Block if explicitly forbidden
            }

            // Allow
            return RV_CONTINUE;
        }
        else
            return RV_CONTINUE;
    }
    else if ( scheme == L"mtalocal" )
    {
        // Allow :)
        return RV_CONTINUE;
    }

     // Trigger onClientBrowserResourceBlocked event
    auto func = std::bind ( &CWebBrowserEventsInterface::Events_OnResourceBlocked, m_pEventsInterface, SString ( request->GetURL () ), "", 2 ); // reason 1 := blocked protocol scheme
    g_pCore->GetWebCore ()->AddEventToEventQueue ( func, this, "OnResourceBlocked" );

    // Block everything else
    return RV_CANCEL;
}
Exemple #17
0
OGRErr OGRSpatialReference::importFromOzi( const char *pszDatum,
                                           const char *pszProj,
                                           const char *pszProjParms )

{
    Clear();

/* -------------------------------------------------------------------- */
/*      Operate on the basis of the projection name.                    */
/* -------------------------------------------------------------------- */
    char    **papszProj = CSLTokenizeStringComplex( pszProj, ",", TRUE, TRUE );
    char    **papszProjParms = CSLTokenizeStringComplex( pszProjParms, ",", 
                                                         TRUE, TRUE );
    char    **papszDatum = NULL;
                                                         
    if (CSLCount(papszProj) < 2)
    {
        goto not_enough_data;
    }

    if ( EQUALN(papszProj[1], "Latitude/Longitude", 18) )
    {
    }

    else if ( EQUALN(papszProj[1], "Mercator", 8) )
    {
        if (CSLCount(papszProjParms) < 6) goto not_enough_data;
        double dfScale = CPLAtof(papszProjParms[3]);
        if (papszProjParms[3][0] == 0) dfScale = 1; /* if unset, default to scale = 1 */
        SetMercator( CPLAtof(papszProjParms[1]), CPLAtof(papszProjParms[2]),
                     dfScale,
                     CPLAtof(papszProjParms[4]), CPLAtof(papszProjParms[5]) );
    }

    else if ( EQUALN(papszProj[1], "Transverse Mercator", 19) )
    {
        if (CSLCount(papszProjParms) < 6) goto not_enough_data;
        SetTM( CPLAtof(papszProjParms[1]), CPLAtof(papszProjParms[2]),
               CPLAtof(papszProjParms[3]),
               CPLAtof(papszProjParms[4]), CPLAtof(papszProjParms[5]) );
    }

    else if ( EQUALN(papszProj[1], "Lambert Conformal Conic", 23) )
    {
        if (CSLCount(papszProjParms) < 8) goto not_enough_data;
        SetLCC( CPLAtof(papszProjParms[6]), CPLAtof(papszProjParms[7]),
                CPLAtof(papszProjParms[1]), CPLAtof(papszProjParms[2]),
                CPLAtof(papszProjParms[4]), CPLAtof(papszProjParms[5]) );
    }

    else if ( EQUALN(papszProj[1], "Sinusoidal", 10) )
    {
        if (CSLCount(papszProjParms) < 6) goto not_enough_data;
        SetSinusoidal( CPLAtof(papszProjParms[2]),
                       CPLAtof(papszProjParms[4]), CPLAtof(papszProjParms[5]) );
    }

    else if ( EQUALN(papszProj[1], "Albers Equal Area", 17) )
    {
        if (CSLCount(papszProjParms) < 8) goto not_enough_data;
        SetACEA( CPLAtof(papszProjParms[6]), CPLAtof(papszProjParms[7]),
                 CPLAtof(papszProjParms[1]), CPLAtof(papszProjParms[2]),
                 CPLAtof(papszProjParms[4]), CPLAtof(papszProjParms[5]) );
    }

    else
    {
        CPLDebug( "OSR_Ozi", "Unsupported projection: \"%s\"", papszProj[1] );
        SetLocalCS( CPLString().Printf("\"Ozi\" projection \"%s\"",
                                       papszProj[1]) );
    }

/* -------------------------------------------------------------------- */
/*      Try to translate the datum/spheroid.                            */
/* -------------------------------------------------------------------- */
    papszDatum = CSLTokenizeString2( pszDatum, ",",
                                               CSLT_ALLOWEMPTYTOKENS
                                               | CSLT_STRIPLEADSPACES
                                               | CSLT_STRIPENDSPACES );
    if ( papszDatum == NULL)
        goto not_enough_data;
        
    if ( !IsLocal() )
    {
        const OZIDatums   *paoDatum = aoDatums;

        // Search for matching datum
        while ( paoDatum->pszOziDatum )
        {
            if ( EQUAL( papszDatum[0], paoDatum->pszOziDatum ) )
            {
                OGRSpatialReference oGCS;
                oGCS.importFromEPSG( paoDatum->nEPSGCode );
                CopyGeogCSFrom( &oGCS );
                break;
            }
            paoDatum++;
        }

        if ( !paoDatum->pszOziDatum )
        {
            CPLError( CE_Warning, CPLE_AppDefined,
                      "Wrong datum name \"%s\". Setting WGS84 as a fallback.",
                      papszDatum[0] );
            SetWellKnownGeogCS( "WGS84" );
        }
    }

/* -------------------------------------------------------------------- */
/*      Grid units translation                                          */
/* -------------------------------------------------------------------- */
    if( IsLocal() || IsProjected() )
        SetLinearUnits( SRS_UL_METER, 1.0 );

    FixupOrdering();
    
    CSLDestroy(papszProj);
    CSLDestroy(papszProjParms);
    CSLDestroy(papszDatum);

    return OGRERR_NONE;
    
not_enough_data:

    CSLDestroy(papszProj);
    CSLDestroy(papszProjParms);
    CSLDestroy(papszDatum);
    
    return OGRERR_NOT_ENOUGH_DATA;
}
Exemple #18
0
static void
wipeout_channel(struct chanNode *cNode, time_t new_time, char **modes, unsigned int modec) {
    unsigned int orig_limit;
    chan_mode_t orig_modes;
    char orig_key[KEYLEN+1];
    char orig_apass[KEYLEN+1];
    char orig_upass[KEYLEN+1];
    unsigned int nn, argc;

    /* nuke old topic */
    cNode->topic[0] = '\0';
    cNode->topic_nick[0] = '\0';
    cNode->topic_time = 0;

    /* remember the old modes, and update them with the new */
    orig_modes = cNode->modes;
    orig_limit = cNode->limit;
    strcpy(orig_key, cNode->key);
    strcpy(orig_upass, cNode->upass);
    strcpy(orig_apass, cNode->apass);
    cNode->modes = 0;
    mod_chanmode(NULL, cNode, modes, modec, 0);
    cNode->timestamp = new_time;

    /* remove our old ban list, replace it with the new one */
    for (nn=0; nn<cNode->banlist.used; nn++)
        free(cNode->banlist.list[nn]);
    cNode->banlist.used = 0;

    /* remove our old exe,[t list, replace it with the new one */
    for (nn=0; nn<cNode->exemptlist.used; nn++)
        free(cNode->exemptlist.list[nn]);
    cNode->exemptlist.used = 0;

    /* deop anybody in the channel now, but count services to reop */
    for (nn=argc=0; nn<cNode->members.used; nn++) {
        struct modeNode *mn = cNode->members.list[nn];
        if ((mn->modes & MODE_CHANOP) && IsService(mn->user) && IsLocal(mn->user))
            argc++;
    }

    if (argc) {
        struct mod_chanmode *change;

        change = mod_chanmode_alloc(argc);
        change->modes_clear = 0;
        change->modes_set = orig_modes;
        change->new_limit = orig_limit;
        strcpy(change->new_key, orig_key);
        strcpy(change->new_upass, orig_upass);
        strcpy(change->new_apass, orig_apass);
        for (nn = argc = 0; nn < cNode->members.used; ++nn) {
            struct modeNode *mn = cNode->members.list[nn];
            if ((mn->modes & MODE_CHANOP) && IsService(mn->user) && IsLocal(mn->user)) {
                change->args[argc].mode = MODE_CHANOP;
                change->args[argc].u.member = mn;
                argc++;
            }
        }
        assert(argc == change->argc);
        change->args[0].u.member->modes &= ~MODE_CHANOP;
        mod_chanmode_announce(change->args[0].u.member->user, cNode, change);
        mod_chanmode_free(change);
    }
}
int FalconTrackMessage::Process(uchar autodisp)
{
	if (autodisp){
		return 0;
	}

	FalconEntity *theEntity = static_cast<FalconEntity*>(Entity());
	if (!theEntity){
		return 0;
	}
	FalconEntity *taggedEntity = static_cast<FalconEntity*>(vuDatabase->Find(dataBlock.id));

	// 2002-02-25 ADDED BY S.G. 'Entity' can be a campaign object if the missile being launch 
	// (ie, dataBlock.trackType is Launch) is a SARH and its platform is still aggregated since 
	// the platform becomes the launching object. Get in if it's a Mover class only...
	if (theEntity->IsMover()){
		SimMoverClass *mEntity = static_cast<SimMoverClass*>(theEntity);
		if (
			!mEntity->IsLocal () && 
			mEntity->numSensors > 1 && 
			// MN 2002-03-03 CTD
			mEntity->sensorArray[1] && 
			// JB 010604 CTD
			mEntity->IsAirplane()
		){
#if NO_REMOTE_BUGGED_TARGET
			// sfr: there should be a higher level function for doing this all...
			if (dataBlock.trackType == Track_Lock){
				SimObjectType *nt = new SimObjectType(taggedEntity);
				mEntity->sensorArray[1]->SetSensorTarget(nt);
				//mEntity->SetTarget(nt);
			}
			else if (dataBlock.trackType == Track_Unlock){
				mEntity->sensorArray[1]->SetSensorTarget(NULL);
				//mEntity->SetTarget(NULL);
			}
#else
			if (dataBlock.trackType == Track_Lock){
				mEntity->sensorArray[1]->RemoteBuggedTarget = taggedEntity;
			}
			else if (dataBlock.trackType == Track_Unlock){
				mEntity->sensorArray[1]->RemoteBuggedTarget = NULL ;
			}
#endif
		}
	}

	if (taggedEntity){
		// HACK HACK HACK!  This should be status info on the aircraft concerned...
		// check for smoke on/off messages
		if (dataBlock.trackType == Track_SmokeOn){
			((AircraftClass *)taggedEntity)->playerSmokeOn = TRUE;
		}
		else if (dataBlock.trackType == Track_SmokeOff){
			((AircraftClass *)taggedEntity)->playerSmokeOn = FALSE;
		}
		else if (dataBlock.trackType == Track_JettisonAll){
			if ((!IsLocal ()) && (taggedEntity->IsAirplane ())){
				//MonoPrint ("JettisonAll %08x\n", dataBlock.id, dataBlock.hardpoint);
				((AircraftClass*)taggedEntity)->Sms->EmergencyJettison ();
			}
		}
		else if (dataBlock.trackType == Track_JettisonWeapon){
			if ((!IsLocal ()) && (taggedEntity->IsAirplane ())){
				//MonoPrint ("Jettison Weapon %08x %d\n", dataBlock.id, dataBlock.hardpoint);
				((AircraftClass*)taggedEntity)->Sms->JettisonWeapon (dataBlock.hardpoint);
			}
		}
		else if (dataBlock.trackType == Track_RemoveWeapon){
			if ((!IsLocal ()) && (taggedEntity->IsAirplane ())){
				//MonoPrint ("RemoveWeapon %08x %d\n", dataBlock.id, dataBlock.hardpoint);
				((AircraftClass*)taggedEntity)->Sms->RemoveWeapon (dataBlock.hardpoint);
			}
		}
		else if (taggedEntity->IsLocal()){
			// 2002-02-09 COMMENT BY S.G. 
			// In here, hardpoint will be used to specify the kind of radar mode the radar was in when.
			if (taggedEntity->IsAirplane()){
				// Find RWR and/or HTS
				for (int j=0; j<((SimVehicleClass*)taggedEntity)->numSensors; j++){
					if (((SimVehicleClass*)taggedEntity)->sensorArray[j]->Type() == SensorClass::RWR){
						((RwrClass*)((SimVehicleClass*)taggedEntity)->sensorArray[j])->ObjectDetected(
							theEntity, dataBlock.trackType, dataBlock.hardpoint
						); // 2002-02-09 MODIFIED BY S.G. Added hardpoint to ObjectDetected
					}
					if (((SimVehicleClass*)taggedEntity)->sensorArray[j]->Type() == SensorClass::HTS){
						((RwrClass*)((SimVehicleClass*)taggedEntity)->sensorArray[j])->ObjectDetected(
							theEntity, dataBlock.trackType, dataBlock.hardpoint
						);  // 2002-02-09 MODIFIED BY S.G. Added hardpoint to ObjectDetected
					}
				}
			}
			else if (taggedEntity->IsFlight()){
				if ((dataBlock.trackType == Track_Lock) || (dataBlock.trackType == Track_Launch)){
					// Tell the campaign entity that it's being locked on to.
					((Flight)taggedEntity)->RegisterLock(theEntity);
				}
			}
		}
	}
	return 1;
}
Exemple #20
0
bool CNetAddr::IsRoutable() const
{
    if (!IsValid())
        return false;
    if (!fAllowPrivateNet && IsRFC1918())
        return false;
    return !(IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal());
}
Exemple #21
0
CefRefPtr<CefResourceHandler> CWebApp::Create(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& scheme_name,
                                              CefRefPtr<CefRequest> request)
{
    // browser or frame are NULL if the request does not orginate from a browser window
    // This is for exmaple true for the application cache or CEFURLRequests
    // (http://www.html5rocks.com/en/tutorials/appcache/beginner/)
    if (!browser || !frame)
        return nullptr;

    CWebCore* pWebCore = static_cast<CWebCore*>(g_pCore->GetWebCore());
    auto      pWebView = pWebCore->FindWebView(browser);
    if (!pWebView || !pWebView->IsLocal())
        return nullptr;

    CefURLParts urlParts;
    if (!CefParseURL(request->GetURL(), urlParts))
        return nullptr;

    if (scheme_name == "mtalocal")            // Backward compatibility
    {
        // Get full path
        SString path = UTF16ToMbUTF8(urlParts.path.str).substr(2);

        // Check if we're dealing with an external resource
        if (path[0] == ':')
        {
            size_t end = path.find_first_of('/');
            if (end != std::string::npos)
            {
                SString resourceName = path.substr(1, end - 1);
                SString resourcePath = path.substr(end);

                // Call this function recursively and use the mta scheme instead
                request->SetURL("http://mta/local/" + resourceName + resourcePath);
                return Create(browser, frame, "http", request);
            }
            return HandleError("404 - Not found", 404);
        }

        // Redirect mtalocal://* to http://mta/local/*, call recursively
        request->SetURL("http://mta/local/" + path);
        return Create(browser, frame, "http", request);
    }

    SString host = UTF16ToMbUTF8(urlParts.host.str);
    if (scheme_name == "http" && host == "mta")
    {
        // Scheme format: http://mta/resourceName/file.html or http://mta/local/file.html for the current resource

        // Get resource name and path
        SString path = UTF16ToMbUTF8(urlParts.path.str).substr(1);            // Remove slash at the front
        size_t  slashPos = path.find('/');
        if (slashPos == std::string::npos)
            return HandleError("404 - Not found", 404);

        SString resourceName = path.substr(0, slashPos);
        SString resourcePath = path.substr(slashPos + 1);

        if (resourcePath.empty())
            return HandleError("404 - Not found", 404);

        // Get mime type from extension
        CefString mimeType;
        size_t    pos = resourcePath.find_last_of('.');
        if (pos != std::string::npos)
            mimeType = CefGetMimeType(resourcePath.substr(pos + 1));

        // Make sure we provide a mime type, even
        // when we cannot deduct it from the file extension
        if (mimeType.empty())
            mimeType = "application/octet-stream";

        if (pWebView->HasAjaxHandler(resourcePath))
        {
            std::vector<SString> vecGet;
            std::vector<SString> vecPost;

            if (urlParts.query.str != nullptr)
            {
                SString              strGet = UTF16ToMbUTF8(urlParts.query.str);
                std::vector<SString> vecTmp;
                strGet.Split("&", vecTmp);

                SString key;
                SString value;
                for (auto&& param : vecTmp)
                {
                    param.Split("=", &key, &value);
                    vecGet.push_back(key);
                    vecGet.push_back(value);
                }
            }

            CefPostData::ElementVector vecPostElements;
            auto                       postData = request->GetPostData();
            if (postData.get())
            {
                request->GetPostData()->GetElements(vecPostElements);

                SString key;
                SString value;
                for (auto&& post : vecPostElements)
                {
                    // Limit to 5MiB and allow byte data only
                    size_t bytesCount = post->GetBytesCount();
                    if (bytesCount > 5 * 1024 * 1024 || post->GetType() != CefPostDataElement::Type::PDE_TYPE_BYTES)
                        continue;

                    // Make string from buffer
                    std::unique_ptr<char[]> buffer{new char[bytesCount]};
                    post->GetBytes(bytesCount, buffer.get());
                    SStringX param(buffer.get(), bytesCount);

                    // Parse POST data into vector
                    std::vector<SString> vecTmp;
                    param.Split("&", vecTmp);

                    for (auto&& param : vecTmp)
                    {
                        param.Split("=", &key, &value);
                        vecPost.push_back(key);
                        vecPost.push_back(value);
                    }
                }
            }

            auto handler = new CAjaxResourceHandler(vecGet, vecPost, mimeType);
            pWebView->HandleAjaxRequest(resourcePath, handler);
            return handler;
        }
        else
        {
            // Calculate MTA resource path
            if (resourceName != "local")
                path = ":" + resourceName + "/" + resourcePath;
            else
                path = resourcePath;

            // Calculate absolute path
            if (!pWebView->GetFullPathFromLocal(path))
                return HandleError("404 - Not found", 404);

            // Verify local files
            if (!pWebView->VerifyFile(path))
                return HandleError("403 - Access Denied", 403);

            // Finally, load the file stream
            auto stream = CefStreamReader::CreateForFile(path);
            if (stream.get())
                return new CefStreamResourceHandler(mimeType, stream);
            return HandleError("404 - Not found", 404);
        }
    }

    // Return null if there is no matching scheme
    // This falls back to letting CEF handle the request
    return nullptr;
}
Exemple #22
0
OGRErr OGRSpatialReference::importFromOzi( const char *pszDatum,
                                           const char *pszProj,
                                           const char *pszProjParms )

{
    Clear();

/* -------------------------------------------------------------------- */
/*      Operate on the basis of the projection name.                    */
/* -------------------------------------------------------------------- */
    char    **papszProj = CSLTokenizeStringComplex( pszProj, ",", TRUE, TRUE );
    char    **papszProjParms = CSLTokenizeStringComplex( pszProjParms, ",", 
                                                         TRUE, TRUE );
    char    **papszDatum = NULL;
                                                         
    if (CSLCount(papszProj) < 2)
    {
        goto not_enough_data;
    }

    if ( EQUALN(papszProj[1], "Latitude/Longitude", 18) )
    {
    }

    else if ( EQUALN(papszProj[1], "Mercator", 8) )
    {
        if (CSLCount(papszProjParms) < 6) goto not_enough_data;
        double dfScale = CPLAtof(papszProjParms[3]);
        if (papszProjParms[3][0] == 0) dfScale = 1; /* if unset, default to scale = 1 */
        SetMercator( CPLAtof(papszProjParms[1]), CPLAtof(papszProjParms[2]),
                     dfScale,
                     CPLAtof(papszProjParms[4]), CPLAtof(papszProjParms[5]) );
    }

    else if ( EQUALN(papszProj[1], "Transverse Mercator", 19) )
    {
        if (CSLCount(papszProjParms) < 6) goto not_enough_data;
        SetTM( CPLAtof(papszProjParms[1]), CPLAtof(papszProjParms[2]),
               CPLAtof(papszProjParms[3]),
               CPLAtof(papszProjParms[4]), CPLAtof(papszProjParms[5]) );
    }

    else if ( EQUALN(papszProj[1], "Lambert Conformal Conic", 23) )
    {
        if (CSLCount(papszProjParms) < 8) goto not_enough_data;
        SetLCC( CPLAtof(papszProjParms[6]), CPLAtof(papszProjParms[7]),
                CPLAtof(papszProjParms[1]), CPLAtof(papszProjParms[2]),
                CPLAtof(papszProjParms[4]), CPLAtof(papszProjParms[5]) );
    }

    else if ( EQUALN(papszProj[1], "Sinusoidal", 10) )
    {
        if (CSLCount(papszProjParms) < 6) goto not_enough_data;
        SetSinusoidal( CPLAtof(papszProjParms[2]),
                       CPLAtof(papszProjParms[4]), CPLAtof(papszProjParms[5]) );
    }

    else if ( EQUALN(papszProj[1], "Albers Equal Area", 17) )
    {
        if (CSLCount(papszProjParms) < 8) goto not_enough_data;
        SetACEA( CPLAtof(papszProjParms[6]), CPLAtof(papszProjParms[7]),
                 CPLAtof(papszProjParms[1]), CPLAtof(papszProjParms[2]),
                 CPLAtof(papszProjParms[4]), CPLAtof(papszProjParms[5]) );
    }

    else
    {
        CPLDebug( "OSR_Ozi", "Unsupported projection: \"%s\"", papszProj[1] );
        SetLocalCS( CPLString().Printf("\"Ozi\" projection \"%s\"",
                                       papszProj[1]) );
    }

/* -------------------------------------------------------------------- */
/*      Try to translate the datum/spheroid.                            */
/* -------------------------------------------------------------------- */
    papszDatum = CSLTokenizeString2( pszDatum, ",",
                                               CSLT_ALLOWEMPTYTOKENS
                                               | CSLT_STRIPLEADSPACES
                                               | CSLT_STRIPENDSPACES );
    if ( papszDatum == NULL)
        goto not_enough_data;
        
    if ( !IsLocal() )
    {

/* -------------------------------------------------------------------- */
/*      Verify that we can find the CSV file containing the datums      */
/* -------------------------------------------------------------------- */
        if( CSVScanFileByName( CSVFilename( "ozi_datum.csv" ),
                            "EPSG_DATUM_CODE",
                            "4326", CC_Integer ) == NULL )
        {
            CPLError( CE_Failure, CPLE_OpenFailed,
                    "Unable to open OZI support file %s.\n"
                    "Try setting the GDAL_DATA environment variable to point\n"
                    "to the directory containing OZI csv files.",
                    CSVFilename( "ozi_datum.csv" ) );
            goto other_error;
        }

/* -------------------------------------------------------------------- */
/*      Search for matching datum                                       */
/* -------------------------------------------------------------------- */
        const char *pszOziDatum = CSVFilename( "ozi_datum.csv" );
        CPLString osDName = CSVGetField( pszOziDatum, "NAME", papszDatum[0],
                                    CC_ApproxString, "NAME" );
        if( strlen(osDName) == 0 )
        {
            CPLError( CE_Failure, CPLE_AppDefined,
                    "Failed to find datum %s in ozi_datum.csv.",
                    papszDatum[0] );
            goto other_error;
        }

        int nDatumCode = atoi( CSVGetField( pszOziDatum, "NAME", papszDatum[0],
                                            CC_ApproxString, "EPSG_DATUM_CODE" ) );

        if ( nDatumCode > 0 ) // There is a matching EPSG code
        {
            OGRSpatialReference oGCS;
            oGCS.importFromEPSG( nDatumCode );
            CopyGeogCSFrom( &oGCS );
        }
        else // We use the parameters from the CSV files
        {
            CPLString osEllipseCode = CSVGetField( pszOziDatum, "NAME", papszDatum[0],
                                                CC_ApproxString, "ELLIPSOID_CODE" );
            double dfDeltaX = CPLAtof(CSVGetField( pszOziDatum, "NAME", papszDatum[0],
                                                CC_ApproxString, "DELTAX" ) );
            double dfDeltaY = CPLAtof(CSVGetField( pszOziDatum, "NAME", papszDatum[0],
                                                CC_ApproxString, "DELTAY" ) );
            double dfDeltaZ = CPLAtof(CSVGetField( pszOziDatum, "NAME", papszDatum[0],
                                                CC_ApproxString, "DELTAZ" ) );


    /* -------------------------------------------------------------------- */
    /*      Verify that we can find the CSV file containing the ellipsoids  */
    /* -------------------------------------------------------------------- */
            if( CSVScanFileByName( CSVFilename( "ozi_ellips.csv" ),
                                "ELLIPSOID_CODE",
                                "20", CC_Integer ) == NULL )
            {
                CPLError( CE_Failure, CPLE_OpenFailed,
                    "Unable to open OZI support file %s.\n"
                    "Try setting the GDAL_DATA environment variable to point\n"
                    "to the directory containing OZI csv files.",
                    CSVFilename( "ozi_ellips.csv" ) );
                goto other_error;
            }

    /* -------------------------------------------------------------------- */
    /*      Lookup the ellipse code.                                        */
    /* -------------------------------------------------------------------- */
            const char *pszOziEllipse = CSVFilename( "ozi_ellips.csv" );

            CPLString osEName = CSVGetField( pszOziEllipse, "ELLIPSOID_CODE", osEllipseCode,
                                        CC_ApproxString, "NAME" );
            if( strlen(osEName) == 0 )
            {
                CPLError( CE_Failure, CPLE_AppDefined,
                        "Failed to find ellipsoid %s in ozi_ellips.csv.",
                        osEllipseCode.c_str() );
                goto other_error;
            }

            double dfA = CPLAtof(CSVGetField( pszOziEllipse, "ELLIPSOID_CODE", osEllipseCode,
                                        CC_ApproxString, "A" ));
            double dfInvF = CPLAtof(CSVGetField( pszOziEllipse, "ELLIPSOID_CODE", osEllipseCode,
                                            CC_ApproxString, "INVF" ));

    /* -------------------------------------------------------------------- */
    /*      Create geographic coordinate system.                            */
    /* -------------------------------------------------------------------- */

            SetGeogCS( osDName, osDName, osEName, dfA, dfInvF );
            SetTOWGS84( dfDeltaX, dfDeltaY, dfDeltaZ );

        }
    }

/* -------------------------------------------------------------------- */
/*      Grid units translation                                          */
/* -------------------------------------------------------------------- */
    if( IsLocal() || IsProjected() )
        SetLinearUnits( SRS_UL_METER, 1.0 );

    FixupOrdering();

    CSLDestroy(papszProj);
    CSLDestroy(papszProjParms);
    CSLDestroy(papszDatum);

    return OGRERR_NONE;

not_enough_data:

    CSLDestroy(papszProj);
    CSLDestroy(papszProjParms);
    CSLDestroy(papszDatum);

    return OGRERR_NOT_ENOUGH_DATA;

other_error:

    CSLDestroy(papszProj);
    CSLDestroy(papszProjParms);
    CSLDestroy(papszDatum);

    return OGRERR_FAILURE;
}
int EjectedPilotClass::Exec()
{
   	ACMIGenPositionRecord genPos;
	ACMISwitchRecord acmiSwitch;

	SoundPos.UpdatePos(this);

	if (IsDead())
		return TRUE;
	
		// Call superclass Exec.
		SimMoverClass::Exec();

      if (!SimDriver.MotionOn())
         return IsLocal();

      if (_delayTime > SimLibElapsedTime) { // not time yet
		RunJettisonCanopy(); // stay with it
		return IsLocal();
      }

		// Advance time
		AdvanceTime();

		// Simulate the ejected pilot here.
		switch(_stage)
		{
			case PD_JETTISON_CANOPY :
			{
				RunJettisonCanopy();
				
				break;
			}
			case PD_EJECT_SEAT :
			{
				RunEjectSeat();

				break;
			}
			case PD_FREE_FALL_WITH_SEAT :
			{
				RunFreeFall();

				break;
			}
			case PD_CHUTE_OPENING :
			{
				RunFreeFall();

				// Here we run our little switch based animation...
				static const int NUM_FRAMES = 31;

				float percent = (_runTime             - StageEndTime(_stage-1)) /
					            (StageEndTime(_stage) - StageEndTime(_stage-1));
				int	frame = FloatToInt32(percent * (NUM_FRAMES-0.5f));

				if ( frame < 0 )
					frame = 0;
				else if ( frame > NUM_FRAMES )
					frame = NUM_FRAMES;

				percent = ((_runTime  - _deltaTime )           - StageEndTime(_stage-1)) /
					       (StageEndTime(_stage) - StageEndTime(_stage-1));

				int	prevframe = FloatToInt32(percent * ((float)NUM_FRAMES-0.5f));
				if ( prevframe < 0 )
					prevframe = 0;
				else if ( prevframe > NUM_FRAMES )
					prevframe = NUM_FRAMES;

				if ( gACMIRec.IsRecording() && prevframe != frame)
				{
						acmiSwitch.hdr.time = SimLibElapsedTime * MSEC_TO_SEC + OTWDriver.todOffset;
						acmiSwitch.data.type = Type();
						acmiSwitch.data.uniqueID = ACMIIDTable->Add(Id(),NULL,0);//.num_;
						acmiSwitch.data.switchNum = 0;
						acmiSwitch.data.prevSwitchVal = 1<<prevframe;
						acmiSwitch.data.switchVal = 1<<frame;
						gACMIRec.SwitchRecord( &acmiSwitch );
				}
					
				if ( drawPointer )
					((DrawableBSP*)drawPointer)->SetSwitchMask( 0, 1<<frame );

				break;
			}
			case PD_FREE_FALL_WITH_OPEN_CHUTE :
			{
				RunFreeFallWithOpenChute();
	
				break;
			}
			case PD_FREE_FALL_WITH_COLLAPSED_CHUTE :
			{
				RunFreeFall();
	
				break;
			}
			case PD_SAFE_LANDING :
			{
				RunSafeLanding();

				_stageTimer += _deltaTime;

				static const int NUM_FRAMES = 13;
				float percent = _stageTimer/2.0f;
				int	frame = FloatToInt32(percent * ((float)NUM_FRAMES-0.5f));

				if ( frame < 0 )
					frame = 0;
				else if ( frame > NUM_FRAMES )
					frame = NUM_FRAMES;

				if ( drawPointer )
					((DrawableBSP*)drawPointer)->SetSwitchMask( 0, 1<<frame );
	
				break;
			}
			case PD_CRASH_LANDING :
			{
				RunCrashLanding();

				_stageTimer += _deltaTime;

				static const int NUM_FRAMES = 12;
				float percent = _stageTimer/2.0f;
				int	frame = FloatToInt32(percent * ((float)NUM_FRAMES-0.5f));

				if ( frame < 0 )
					frame = 0;
				else if ( frame > NUM_FRAMES )
					frame = NUM_FRAMES;

				if ( drawPointer )
					((DrawableBSP*)drawPointer)->SetSwitchMask( 0, 1<<frame );
	
				break;
			}
			default :
			{
				ShiWarning ("Bad Eject Mode");
			}
		}

		// Make sure all components of orientation are in range ( 0 <= n <= TWO_PI).
		FixOrientationRange();

		// Update shared data.
		SetPosition(_pos[I_X], _pos[I_Y], _pos[I_Z]);
		SetDelta(_vel[I_X], _vel[I_Y], _vel[I_Z]);
		SetYPR(_rot[I_YAW], _rot[I_PITCH], _rot[I_ROLL]);
		SetYPRDelta(_aVel[I_YAW], _aVel[I_PITCH], _aVel[I_ROLL]);
		if (gACMIRec.IsRecording() && (SimLibFrameCount & 3 ) == 0)
		{
			genPos.hdr.time = SimLibElapsedTime * MSEC_TO_SEC + OTWDriver.todOffset;
			genPos.data.type = Type();
			genPos.data.uniqueID = ACMIIDTable->Add(Id(),NULL,TeamInfo[GetTeam()]->GetColor());//.num_;
			genPos.data.x = XPos();
			genPos.data.y = YPos();
			genPos.data.z = ZPos();
			genPos.data.roll = Roll();
			genPos.data.pitch = Pitch();
			genPos.data.yaw = Yaw();
// remove			genPos.data.teamColor = TeamInfo[GetTeam()]->GetColor();
			gACMIRec.GenPositionRecord( &genPos );
		}

		// Update matrices for geometry.
		CalcTransformMatrix((SimMoverClass *)this);

		// See if it hit the ground.
		if ( _hitGround == FALSE )
			_hitGround = HasHitGround();

		/*
		** We now do completion in the safe or crash landing stages
		** (by calling HitGround() )
		if (HasHitGround())
		{
			HitGround();
		}
		*/

		// Display some debug data.
#if DEBUG_EJECTION_SEQUENCE
		SpewDebugData();
#endif // DEBUG_EJECTION_SEQUENCE

	return IsLocal();
}
Exemple #24
0
OGRErr OGRSpatialReference::importFromPanorama( long iProjSys, long iDatum,
                                                long iEllips,
                                                double *padfPrjParams )

{
    Clear();

/* -------------------------------------------------------------------- */
/*      Use safe defaults if projection parameters are not supplied.    */
/* -------------------------------------------------------------------- */
    int bProjAllocated = false;

    if( padfPrjParams == NULL )
    {
        int     i;

        padfPrjParams = (double *)CPLMalloc( 8 * sizeof(double) );
        if ( !padfPrjParams )
            return OGRERR_NOT_ENOUGH_MEMORY;
        for ( i = 0; i < 7; i++ )
            padfPrjParams[i] = 0.0;
        bProjAllocated = true;
    }

/* -------------------------------------------------------------------- */
/*      Operate on the basis of the projection code.                    */
/* -------------------------------------------------------------------- */
    switch ( iProjSys )
    {
        case PAN_PROJ_NONE:
            break;

        case PAN_PROJ_UTM:
            {
                int nZone;

                if ( padfPrjParams[7] == 0.0 )
                    nZone = (int) TO_ZONE(padfPrjParams[3]);
                else
                    nZone = (int) padfPrjParams[7];

                // XXX: no way to determine south hemisphere. Always assume
                // northern hemisphere.
                SetUTM( nZone, TRUE );
            }
            break;

        case PAN_PROJ_WAG1:
            SetWagner( 1, 0.0,
                       padfPrjParams[5], padfPrjParams[6] );
            break;

        case PAN_PROJ_MERCAT:
            SetMercator( TO_DEGREES * padfPrjParams[0],
                         TO_DEGREES * padfPrjParams[3],
                         padfPrjParams[4],
                         padfPrjParams[5], padfPrjParams[6] );
            break;

        case PAN_PROJ_PS:
            SetPS( TO_DEGREES * padfPrjParams[2],
                   TO_DEGREES * padfPrjParams[3],
                   padfPrjParams[4],
                   padfPrjParams[5], padfPrjParams[6] );
            break;

        case PAN_PROJ_POLYC:
            SetPolyconic( TO_DEGREES * padfPrjParams[2],
                          TO_DEGREES * padfPrjParams[3],
                          padfPrjParams[5], padfPrjParams[6] );
            break;

        case PAN_PROJ_EC:
            SetEC( TO_DEGREES * padfPrjParams[0],
                   TO_DEGREES * padfPrjParams[1],
                   TO_DEGREES * padfPrjParams[2],
                   TO_DEGREES * padfPrjParams[3],
                   padfPrjParams[5], padfPrjParams[6] );
            break;

        case PAN_PROJ_LCC:
            SetLCC( TO_DEGREES * padfPrjParams[0],
                    TO_DEGREES * padfPrjParams[1],
                    TO_DEGREES * padfPrjParams[2],
                    TO_DEGREES * padfPrjParams[3],
                    padfPrjParams[5], padfPrjParams[6] );
            break;

        case PAN_PROJ_TM:
            {
                // XXX: we need zone number to compute false easting
                // parameter, because usually it is not contained in the
                // "Panorama" projection definition.
                // FIXME: what to do with negative values?
                int    nZone;
                double  dfCenterLong;

                if ( padfPrjParams[7] == 0.0 )
                {
                    nZone = (int)TO_ZONE(padfPrjParams[3]);
                    dfCenterLong = TO_DEGREES * padfPrjParams[3];
                }
                else
                {
                    nZone = (int) padfPrjParams[7];
                    dfCenterLong = 6 * (double)nZone - 3;
                }

                padfPrjParams[5] = nZone * 1000000.0 + 500000.0;
                padfPrjParams[4] = 1.0;
                SetTM( TO_DEGREES * padfPrjParams[2],
                       dfCenterLong,
                       padfPrjParams[4],
                       padfPrjParams[5], padfPrjParams[6] );
            }
            break;

        case PAN_PROJ_STEREO:
            SetStereographic( TO_DEGREES * padfPrjParams[2],
                              TO_DEGREES * padfPrjParams[3],
                              padfPrjParams[4],
                              padfPrjParams[5], padfPrjParams[6] );
            break;

        case PAN_PROJ_AE:
            SetAE( TO_DEGREES * padfPrjParams[0],
                   TO_DEGREES * padfPrjParams[3],
                   padfPrjParams[5], padfPrjParams[6] );
            break;

        case PAN_PROJ_GNOMON:
            SetGnomonic( TO_DEGREES * padfPrjParams[2],
                         TO_DEGREES * padfPrjParams[3],
                         padfPrjParams[5], padfPrjParams[6] );
            break;

        case PAN_PROJ_MOLL:
            SetMollweide( TO_DEGREES * padfPrjParams[3],
                          padfPrjParams[5], padfPrjParams[6] );
            break;

        case PAN_PROJ_LAEA:
            SetLAEA( TO_DEGREES * padfPrjParams[0],
                     TO_DEGREES * padfPrjParams[3],
                     padfPrjParams[5], padfPrjParams[6] );
            break;

        case PAN_PROJ_EQC:
            SetEquirectangular( TO_DEGREES * padfPrjParams[0],
                                TO_DEGREES * padfPrjParams[3],
                                padfPrjParams[5], padfPrjParams[6] );
            break;

        case PAN_PROJ_CEA:
            SetCEA( TO_DEGREES * padfPrjParams[0],
                    TO_DEGREES * padfPrjParams[3],
                    padfPrjParams[5], padfPrjParams[6] );
            break;

        case PAN_PROJ_IMWP:
            SetIWMPolyconic( TO_DEGREES * padfPrjParams[0],
                             TO_DEGREES * padfPrjParams[1],
                             TO_DEGREES * padfPrjParams[3],
                             padfPrjParams[5], padfPrjParams[6] );
            break;

        case PAN_PROJ_MILLER:
            SetMC(TO_DEGREES * padfPrjParams[5],
                TO_DEGREES * padfPrjParams[4],
                padfPrjParams[6], padfPrjParams[7]);
            break;

        default:
            CPLDebug( "OSR_Panorama", "Unsupported projection: %ld", iProjSys );
            SetLocalCS( CPLString().Printf("\"Panorama\" projection number %ld",
                                   iProjSys) );
            break;

    }

/* -------------------------------------------------------------------- */
/*      Try to translate the datum/spheroid.                            */
/* -------------------------------------------------------------------- */

    if ( !IsLocal() )
    {
        if ( iDatum > 0 && iDatum < NUMBER_OF_DATUMS && aoDatums[iDatum] )
        {
            OGRSpatialReference oGCS;
            oGCS.importFromEPSG( aoDatums[iDatum] );
            CopyGeogCSFrom( &oGCS );
        }

        else if ( iEllips > 0
                  && iEllips < NUMBER_OF_ELLIPSOIDS
                  && aoEllips[iEllips] )
        {
            char    *pszName = NULL;
            double  dfSemiMajor, dfInvFlattening;

            if ( OSRGetEllipsoidInfo( aoEllips[iEllips], &pszName,
                            &dfSemiMajor, &dfInvFlattening ) == OGRERR_NONE )
            {
                SetGeogCS( CPLString().Printf(
                            "Unknown datum based upon the %s ellipsoid",
                            pszName ),
                           CPLString().Printf(
                            "Not specified (based on %s spheroid)", pszName ),
                           pszName, dfSemiMajor, dfInvFlattening,
                           NULL, 0.0, NULL, 0.0 );
                SetAuthority( "SPHEROID", "EPSG", aoEllips[iEllips] );
            }
            else
            {
                CPLError( CE_Warning, CPLE_AppDefined,
                          "Failed to lookup ellipsoid code %ld, likely due to"
                          " missing GDAL gcs.csv\n"
                          " file.  Falling back to use Pulkovo 42.", iEllips );
                SetWellKnownGeogCS( "EPSG:4284" );
            }

            if ( pszName )
                CPLFree( pszName );
        }

        else
        {
            CPLError( CE_Warning, CPLE_AppDefined,
                      "Wrong datum code %ld. Supported datums are 1--%ld only.\n"
                      "Falling back to use Pulkovo 42.",
                      iDatum, NUMBER_OF_DATUMS - 1 );
            SetWellKnownGeogCS( "EPSG:4284" );
        }
    }

/* -------------------------------------------------------------------- */
/*      Grid units translation                                          */
/* -------------------------------------------------------------------- */
    if( IsLocal() || IsProjected() )
        SetLinearUnits( SRS_UL_METER, 1.0 );

    FixupOrdering();

    if ( bProjAllocated && padfPrjParams )
        CPLFree( padfPrjParams );

    return OGRERR_NONE;
}
Exemple #25
0
// get canonical identifier of an address' group
// no two connections will be attempted to addresses with the same group
std::vector<unsigned char> CNetAddr::GetGroup() const
{
    std::vector<unsigned char> vchRet;
    int nClass = NET_IPV6;
    int nStartByte = 0;
    int nBits = 16;

    // all local addresses belong to the same group
    if (IsLocal())
    {
        nClass = 255;
        nBits = 0;
    }
    // all internal-usage addresses get their own group
    if (IsInternal())
    {
        nClass = NET_INTERNAL;
        nStartByte = sizeof(g_internal_prefix);
        nBits = (sizeof(ip) - sizeof(g_internal_prefix)) * 8;
    }
    // all other unroutable addresses belong to the same group
    else if (!IsRoutable())
    {
        nClass = NET_UNROUTABLE;
        nBits = 0;
    }
    // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
    // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
    else if (IsIPv4() || IsRFC6145() || IsRFC6052())
    {
        nClass = NET_IPV4;
        nStartByte = 12;
    }
    // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
    else if (IsRFC3964())
    {
        nClass = NET_IPV4;
        nStartByte = 2;
    }
    // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
    else if (IsRFC4380())
    {
        vchRet.push_back(NET_IPV4);
        vchRet.push_back(GetByte(3) ^ 0xFF);
        vchRet.push_back(GetByte(2) ^ 0xFF);
        return vchRet;
    }
    else if (IsTor())
    {
        nClass = NET_TOR;
        nStartByte = 6;
        nBits = 4;
    }
    // for he.net, use /36 groups
    else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
        nBits = 36;
    // for the rest of the IPv6 network, use /32 groups
    else
        nBits = 32;

    vchRet.push_back(nClass);
    while (nBits >= 8)
    {
        vchRet.push_back(GetByte(15 - nStartByte));
        nStartByte++;
        nBits -= 8;
    }
    if (nBits > 0)
        vchRet.push_back(GetByte(15 - nStartByte) | ((1 << (8 - nBits)) - 1));

    return vchRet;
}
Exemple #26
0
OGRErr OGRSpatialReference::importFromERM( const char *pszProj,
        const char *pszDatum,
        const char *pszUnits )

{
    Clear();

    /* -------------------------------------------------------------------- */
    /*      do we have projection and datum?                                */
    /* -------------------------------------------------------------------- */
    if( EQUAL(pszProj,"RAW") )
        return OGRERR_NONE;

    /* -------------------------------------------------------------------- */
    /*      Do we have an EPSG coordinate system?                           */
    /* -------------------------------------------------------------------- */

    if( EQUALN(pszProj,"EPSG:",5) )
        return importFromEPSG( atoi(pszProj+5) );


    if( EQUALN(pszDatum,"EPSG:",5) )
        return importFromEPSG( atoi(pszDatum+5) );

    /* -------------------------------------------------------------------- */
    /*      Set projection if we have it.                                   */
    /* -------------------------------------------------------------------- */
    OGRErr eErr;

    if( EQUAL(pszProj,"GEODETIC") )
    {
    }
    else
    {
        eErr = importFromDict( "ecw_cs.wkt", pszProj );
        if( eErr != OGRERR_NONE )
            return eErr;

        if( EQUAL(pszUnits,"FEET") )
            SetLinearUnits( SRS_UL_US_FOOT, CPLAtof(SRS_UL_US_FOOT_CONV));
        else
            SetLinearUnits( SRS_UL_METER, 1.0 );
    }

    /* -------------------------------------------------------------------- */
    /*      Set the geogcs.                                                 */
    /* -------------------------------------------------------------------- */
    OGRSpatialReference oGeogCS;

    eErr = oGeogCS.importFromDict( "ecw_cs.wkt", pszDatum );
    if( eErr != OGRERR_NONE )
    {
        Clear();
        return eErr;
    }

    if( !IsLocal() )
        CopyGeogCSFrom( &oGeogCS );

    return OGRERR_NONE;
}