Example #1
0
int MainWindow::createKmlFile( const QString &s_FilenameIn,
                               int &i_IconColor, int &i_IconSize,
                               int &i_TracklineColor, int &i_TracklineWidth,
                               QString &s_FilenameGoogleEarthProgram, bool &b_startGoogleEarth,
                               QString &s_FilenameOut, const int i_NumOfFiles )
{
    int         i               = 0;
    int         n               = 0;

    int			stopProgress	= 0;

    int         i_ID            = 0;
    int         i_StartID       = 0;
    int         i_EndID         = 0;

    double      d_Distance      = 0.0;
    double      d_Speed         = 0.0;
    double      d_Latitude      = 0.0;
    double      d_Longitude     = 0.0;
    double      d_Latitude_old  = 0.0;
    double      d_Longitude_old = 0.0;
    double      d_Seconds_old   = 0.0;
    double      d_PlotDistance  = 100.0;

    QString     s_Date          = "";
    QString     s_Time          = "";
    QString     s_Latitude      = "";
    QString     s_Longitude     = "";
    QString     s_TrackName     = "";

    QStringList sl_Input;

    QFileInfo fi( s_FilenameIn );

// **********************************************************************************************
// read file

    QFile fin( s_FilenameIn );

    if ( fin.open( QIODevice::ReadOnly | QIODevice::Text ) == false )
        return( -10 );

    QTextStream tin( &fin );

    while ( tin.atEnd() == false )
        sl_Input.append( tin.readLine().replace( QChar( 0x00 ), "" ) );

    fin.close();

    n = sl_Input.count();

// **********************************************************************************************

    if ( ( n<2 ) || ( sl_Input.at( i++ ) != "INDEX,TAG,DATE,TIME,LATITUDE N/S,LONGITUDE E/W,HEIGHT,SPEED,HEADING,VOX" ) )
        return( _APPBREAK_ );

    i_StartID   = sl_Input.at( 1 ).section( ",", 0, 0 ).toInt();
    i_EndID     = sl_Input.at( sl_Input.count() - 1 ).section( ",", 0, 0 ).toInt();
    s_TrackName = fi.baseName();

    if ( doGPStoKmlOptionsDialog( i_StartID, i_EndID, i_IconColor, i_IconSize, i_TracklineColor, i_TracklineWidth, s_TrackName, s_FilenameGoogleEarthProgram, b_startGoogleEarth ) == QDialog::Rejected )
        return( _APPBREAK_ );

// **********************************************************************************************
// open output file

    s_FilenameOut = fi.absolutePath() + "/" + s_TrackName + ".kml";

    QFile fout( s_FilenameOut );

    if ( fout.open( QIODevice::WriteOnly | QIODevice::Text) == false )
    {
        s_FilenameOut = "";
        return( -20 );
    }

// **********************************************************************************************

    initProgress( i_NumOfFiles, s_FilenameIn, tr( "Creating KML file..." ), 2*sl_Input.count() );

// **********************************************************************************************

    QTextStream tout( &fout );
    tout.setCodec( "UTF-8" );

    tout << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl;
    tout << "<kml xmlns=\"http://earth.google.com/kml/2.1\">" << endl;
    tout << "<Document>" << endl;
/*
    tout << "  <ScreenOverlay>" << endl;
    tout << "    <name>Pan2Applic logo</name>" << endl;
    tout << "    <Icon><href>http://epic.awi.de/40953/121/Pan2Applic_logo.png</href></Icon>" << endl;
    tout << "    <overlayXY x=\"0\" y=\"1\" xunits=\"fraction\" yunits=\"fraction\"/>" << endl;
    tout << "    <screenXY x=\"5\" y=\"5\" xunits=\"pixels\" yunits=\"insetPixels\"/>" << endl;
    tout << "    <size x=\"200\" y=\"88\" xunits=\"pixel\" yunits=\"pixel\"/>" << endl;
    tout << "  </ScreenOverlay>" << endl;
*/
    tout << "  <Style id=\"circle-blue\"><IconStyle><Icon><href>http://epic.awi.de/40953/1/circle-blue.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"circle-green\"><IconStyle><Icon><href>http://epic.awi.de/40953/2/circle-green.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"circle-orange\"><IconStyle><Icon><href>http://epic.awi.de/40953/3/circle-orange.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"circle-red\"><IconStyle><Icon><href>http://epic.awi.de/40953/4/circle-red.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"circle-white\"><IconStyle><Icon><href>http://epic.awi.de/40953/5/circle-white.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"circle-yellow\"><IconStyle><Icon><href>http://epic.awi.de/40953/6/circle-yellow.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"square-blue\"><IconStyle><Icon><href>http://epic.awi.de/40953/7/square-blue.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"square-green\"><IconStyle><Icon><href>http://epic.awi.de/40953/8/square-green.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"square-orange\"><IconStyle><Icon><href>http://epic.awi.de/40953/9/square-orange.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"square-red\"><IconStyle><Icon><href>http://epic.awi.de/40953/10/square-red.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"square-white\"><IconStyle><Icon><href>http://epic.awi.de/40953/11/square-white.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"square-yellow\"><IconStyle><Icon><href>http://epic.awi.de/40953/12/square-yellow.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"star-blue\"><IconStyle><Icon><href>http://epic.awi.de/40953/13/star-blue.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"star-green\"><IconStyle><Icon><href>http://epic.awi.de/40953/14/star-green.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"star-orange\"><IconStyle><Icon><href>http://epic.awi.de/40953/15/star-orange.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"star-red\"><IconStyle><Icon><href>http://epic.awi.de/40953/16/star-red.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"star-white\"><IconStyle><Icon><href>http://epic.awi.de/40953/17/star-white.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"star-yellow\"><IconStyle><Icon><href>http://epic.awi.de/40953/18/star-yellow.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"triangle-blue\"><IconStyle><Icon><href>http://epic.awi.de/40953/19/triangle-blue.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"triangle-green\"><IconStyle><Icon><href>http://epic.awi.de/40953/20/triangle-green.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"triangle-orange\"><IconStyle><Icon><href>http://epic.awi.de/40953/21/triangle-orange.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"triangle-red\"><IconStyle><Icon><href>http://epic.awi.de/40953/22/triangle-red.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"triangle-white\"><IconStyle><Icon><href>http://epic.awi.de/40953/23/triangle-white.png</href></Icon></IconStyle></Style>" << endl;
    tout << "  <Style id=\"triangle-yellow\"><IconStyle><Icon><href>http://epic.awi.de/40953/24/triangle-yellow.png</href></Icon></IconStyle></Style>" << endl;

// **********************************************************************************************
// Way points

    tout << "<Folder>" << endl;
    tout << "<name>Point Set</name>" << endl;
    tout << "<open>0</open>" << endl;

    while ( ( i<n ) && ( stopProgress != _APPBREAK_ ) )
    {
        if ( sl_Input.at( i ).section( ",", 1, 1 ) == "T" )
        {
            i_ID = sl_Input.at( i ).section( ",", 0, 0 ).toInt();

            if ( ( i_StartID <= i_ID ) && ( i_ID <= i_EndID ) )
            {
                s_Time      = sl_Input.at( i ).section( ",", 3, 3 ).left( 2 ) + ":" + sl_Input.at( i ).section( ",", 3, 3 ).mid( 2, 2 ) + ":" + sl_Input.at( i ).section( ",", 3, 3 ).mid( 4, 2 );
                s_Date      = "20" + sl_Input.at( i ).section( ",", 2, 2 ).left( 2 ) + "-" + sl_Input.at( i ).section( ",", 2, 2 ).mid( 2, 2 ) + "-" + sl_Input.at( i ).section( ",", 2, 2 ).mid( 4, 2 );

                s_Latitude  = extractLatitude( sl_Input.at(i) );
                s_Longitude = extractLongitude( sl_Input.at(i) );

                d_Latitude  = s_Latitude.toDouble();
                d_Longitude = s_Longitude.toDouble();

                d_Distance  = calculateDistance( d_Latitude, d_Longitude, d_Latitude_old, d_Longitude_old ); // [m]

                if ( ( i_ID == i_StartID ) || ( i_ID == i_EndID ) || ( d_Distance > d_PlotDistance ) )
                {
                    d_Speed = 3.6 * d_Distance/( (double) i - d_Seconds_old ); // [m/s] -> [km/h]

                    tout << "<Placemark>";
//                  tout << "<name>" << s_Time << "</name>";

                    switch ( i_IconColor )
                    {
                        case _RED_:
                            tout << "<styleUrl>#red</styleUrl>";
                            break;
                        case _GREEN_:
                            tout << "<styleUrl>#green</styleUrl>";
                            break;
                        case _BLUE_:
                            tout << "<styleUrl>#blue</styleUrl>";
                            break;
                        case _ORANGE_:
                            tout << "<styleUrl>#orange</styleUrl>";
                            break;
                        case _YELLOW_:
                            tout << "<styleUrl>#yellow</styleUrl>";
                            break;
                        default:
                            tout << "<styleUrl>#red</styleUrl>";
                            break;
                    }

                    tout << "<Style><IconStyle>" << QString( "<scale>%1</scale>" ).arg( (float) i_IconSize/100. ) << "</IconStyle></Style>";
                    tout << "<Point><coordinates>" << s_Longitude << "," << s_Latitude << "</coordinates></Point>";
                    tout << "<description>" << endl;
                    tout << "<![CDATA[Time: " << s_Time << "<br />Date: " << s_Date << "<br />Latitude: " << d_Latitude << "° N<br />Longitude: " << d_Longitude << "° E<br />Altitude: " << sl_Input.at( i ).section( ",", 6, 6 ).simplified() << " m<br />Speed: " << d_Speed << " km/h<br />ID: " << i_ID << "<br />]]>" << endl;
                    tout << "</description>" << endl;
                    tout << "</Placemark>" << endl;

                    d_Latitude_old  = d_Latitude;
                    d_Longitude_old = d_Longitude;
                    d_Seconds_old   = (double) i;

                    if ( d_Speed < 50. )
                        d_PlotDistance = 100;
                    else
                        d_PlotDistance = 1000;
                }
            }
        }

        stopProgress = incProgress( i_NumOfFiles, ++i );
    }

    tout << "</Folder>" << endl;

// **********************************************************************************************
// Track line

    tout << "<Placemark><name>Trackline</name>" << endl;

    switch ( i_TracklineColor )
    {
        case _RED_:
            tout << "<Style><LineStyle><color>ff0000ff</color>";
            break;
        case _GREEN_:
            tout << "<Style><LineStyle><color>ff00ff00</color>";
            break;
        case _BLUE_:
            tout << "<Style><LineStyle><color>ffff0000</color>";
            break;
        case _ORANGE_:
            tout << "<Style><LineStyle><color>ff0099ff</color>";
            break;
        case _YELLOW_:
            tout << "<Style><LineStyle><color>ff33ffff</color>";
            break;
        default:
            tout << "<Style><LineStyle><color>ff0099ff</color>";
            break;
    }

    tout << "<width>" << (float) i_TracklineWidth/10. << "</width></LineStyle></Style>" << endl;

    tout << "<LineString>" << endl;
    tout << "<tessellate>1</tessellate>" << endl;
    tout << "<coordinates>" << endl;

    i = 1;

    while ( ( i<n ) && ( stopProgress != _APPBREAK_ ) )
    {
        if ( sl_Input.at( i ).section( ",", 1, 1 ) == "T" )
        {
            i_ID = sl_Input.at( i ).section( ",", 0, 0 ).toInt();

            if ( ( i_StartID <= i_ID ) && ( i_ID <= i_EndID ) )
            {
                s_Latitude  = extractLatitude( sl_Input.at(i) );
                s_Longitude = extractLongitude( sl_Input.at(i) );

                tout << s_Longitude << "," << s_Latitude << "," << sl_Input.at( i ).section( ",", 6, 6 ).simplified() << endl;
            }
        }

        stopProgress = incProgress( i_NumOfFiles, ++i+n );
    }

    tout << "</coordinates>" << endl;
    tout << "</LineString>" << endl;
    tout << "</Placemark>" << endl;
    tout << "</Document>" << endl;
    tout << "</kml>" << endl;

    fout.close();

    resetProgress( i_NumOfFiles );

    if ( stopProgress == _APPBREAK_ )
        return( _APPBREAK_ );

    return( _NOERROR_ );
}
Example #2
0
double ClsTopologyRect::DistMax(){
    double fWidth = pclsWidth->getValue();
    double fHeight = pclsHeight->getValue();
    return calculateDistance(1., 1., fWidth, fHeight);
}
Example #3
0
CubeSide::CubeSide(Cube &parent, int n) : _parent(&parent), _n(n) {
	calculateDistance();

	show();
}
Example #4
0
void RulerLabel::draw(int sel) 
{
	if (drawMode == DRAW_HIDDEN) return;

	
	if (vertex1.isSet())
	{
		vec2d startPnt = vertex1.pos2d();
		vec2d endPnt = cursor;
		if (vertex2.isSet())
		{
			vec3d start3d(0,0,0);
			vec3d end3d(0,0,0);
			getVertexPoints(&start3d, &end3d);
			startPnt = vertex1.viewProject( start3d );
			endPnt = vertex2.viewProject( end3d );
		}
		//==== Calculate Distance ====//
		calculateDistance();
		Stringc label;
		if (vertex2.isSet())
		{
			char str[255];
			char fmt[255];
			sprintf(fmt, "%%0.%df %%s", precision);
			sprintf(str, fmt, rulerDistance, unitString.get_char_star());
			label = str;
		}
		else
		{
			label = getName();
		}

		if (sel)
			glColor3ub(255, 0, 0);
		else
			glColor3ub((int)color.x(), (int)color.y(), (int)color.z());
		//==== Draw Points ====//
		if (drawMode == DRAW_HIGHLIGHT)
		{
			glPointSize(sel ? 7.0f : 6.0f);
			glBegin(GL_POINTS);
			glVertex2d(startPnt.x(), startPnt.y());
			glVertex2d(endPnt.x(), endPnt.y());
			glEnd();
		}

		//==== Calculate Offset ====//
		if (attachState == VERTEX2_SET)
			calculateOffset();
		vec2d deltavec = startPnt - endPnt;
		vec2d offset(deltavec.y(), -deltavec.x());
		offset.normalize();
		vec2d startOff = startPnt + offset * rulerOffset * viewScale;
		vec2d endOff = endPnt   + offset * rulerOffset * viewScale;

		//==== Draw Lines ====//
		glLineWidth(sel ? 2.0f : 1.0f);
		glBegin(GL_LINE_STRIP);
			glVertex2d(startPnt.x(), startPnt.y());
			glVertex2d(startOff.x(), startOff.y());
			glVertex2d(endOff.x(), endOff.y());
			glVertex2d(endPnt.x(), endPnt.y());
		glEnd();

		//==== Draw Text ====//
		vec2d vc = (startOff + endOff) * 0.5;
		double ang = PI/2.0;
		if (deltavec.x() > 0.0001 || deltavec.x() < -0.0001) // ~!= 0
			ang = atan( (deltavec.y()) / (deltavec.x()) );

		glColor3ub((int)color.x(), (int)color.y(), (int)color.z());
		glPushMatrix();
		{
			glTranslated(vc.x(), vc.y(), 0);
			glRotatef((float)RAD2DEG(ang), 0,0,1);
			glEnable(GL_TEXTURE_2D);
			if ( font )
				drawString(font, textSize * (float)sqrt(viewScale), label, 0,0, (float)textOffset, 0.7f);
			glDisable(GL_TEXTURE_2D);
		}
		glPopMatrix();
	}

}
void TargetDisplayWindowUpdator::updateUpdatables()
{
	{
		LinkedList* list = game->items->getAllItems();
		
		itemsToBeUpdated.clear();

		float updateDistance = updateItemsInsideDistance * updateItemsInsideDistance;

		SafeLinkedListIterator i( list );

		while( i.iterateAvailable() )
		{
			Item* item = (Item*)i.iterateNext();
			VC3 pos = item->getPosition();
		

			if( item->getHighlightStyle() >= 0 && calculateDistance( pos, game ) < updateDistance )
			{
				itemsToBeUpdated.push_back( item );
			}
		}
	}

#ifdef PROJECT_SURVIVOR
	bool any_player_has_intelligence = false;
	int value = 0;
	if(util::Script::getGlobalIntVariableValue("enemyintelligence_in_use", &value) && value == 1)
	{
		for(int i = 0; i < MAX_PLAYERS_PER_CLIENT; i++)
		{
			if(util::Script::getGlobalArrayVariableValue("upgraded_enemyintelligence", i, &value) && value == 1
				&& game->gameUI->getFirstPerson(i)
				&& strcmp(game->gameUI->getFirstPerson(i)->getUnitType()->getName(), "Surv_Sniper") == 0)
			{
				any_player_has_intelligence = true;
				break;
			}
		}
	}
#endif

	{
		VC3 cam_pos;
		if( game->gameUI->getFirstPerson( 0 ) )
			cam_pos = game->gameUI->getFirstPerson( 0 )->getPosition();
		else
			cam_pos = game->gameUI->getGameCamera()->getPosition();

		float updateDistance = unitDistance * unitDistance;

		unitsToBeUpdated.clear();

		IUnitListIterator *iter = game->units->getNearbyAllUnits(cam_pos, updateDistance);
		while (iter->iterateAvailable())
		{
			Unit *unit = (Unit *)iter->iterateNext();
			VC3 pos = unit->getPosition();


#ifdef PROJECT_SURVIVOR
			// this is an enemy
			if(unit->getOwner() == 1 || unit->getOwner() == 3)
			{
				// has intelligence on living enemy
				if(any_player_has_intelligence && unit->getHP() > 0)
				{
					// highlight if not already
					if(unit->getHighlightStyle() == -1)
						unit->setHighlightStyle(3);
				}
				// otherwise, if still highlighted by intelligence
				else if(unit->getHighlightStyle() == 3)
				{
					// unhighlight
					unit->setHighlightStyle(-1);
				}
			}
#endif

			// also include target locked enemies
			if( unit->getHighlightStyle() >= 0 || unit->getTargetLockCounter() > 0)
			{
				unitsToBeUpdated.push_back( unit );
			}
		}
		delete iter;
	}
}
Example #6
0
vector<Grid> Planner::aStarPlanning(Map &map)
{
    // implemtation of the a star algorithm
    
    // initialize the way point list
    vector<Grid> wayPoint;
    
    // return an empty list if map is invalid
    if(map.start.x==-1||map.start.y==-1||map.goal.x==-1||map.goal.y==-1)
        return wayPoint;
    
    
    // type of the A star priority list element
    typedef struct {Grid pos; float f;} AStarUnit;
    
    
    list<AStarUnit> openlist; // open list
    vector<vector<float> > h(map._rows, vector<float>(map._cols, -1.0));  // heuristic value
    vector<vector<float> > g(map._rows, vector<float>(map._cols, -1.0));  // optimized value of the grid
    vector<vector<float> > f(map._rows, vector<float>(map._cols, -1.0));  // the key value of the A star algorithm (search priority)
    vector<vector<Grid> > b(map._rows, vector<Grid>(map._cols, Grid(-1,-1)));  // back pointer to pred node
    vector<vector<bool> > closelist(map._rows, vector<bool>(map._cols, false));  // close list

    
    
    // value initialization
    h[map.start.y][map.start.x] = calculateDistance(map.start,map.goal);
    g[map.start.y][map.start.x] = 0;
    f[map.start.y][map.start.x] = h[map.start.y][map.start.x];
    
    AStarUnit startP={map.start,calculateDistance(map.start,map.goal)};
    openlist.push_back(startP);
    
    while (openlist.size()>0)
    {
        // iterate when the open list is not empty
        // pop the first item in the open list to expand
        Grid currentP  = openlist.front().pos;
        closelist[currentP.y][currentP.x] = true;
        openlist.pop_front();
        
        // if already reach the goal, stop iterating
        if (currentP==map.goal) break;
        
        // find its direct neigbour
        vector<Grid> neighbourList = findNeighbour(map,currentP,4);
        
        for(Grid neighbour:neighbourList)
        {
            
            // update the shorest distance of the cells neighbour if a shorter path is finded
            if (((g[neighbour.y][neighbour.x]==-1.0)||(g[neighbour.y][neighbour.x]>g[currentP.y][currentP.x]+calculateDistance(neighbour,currentP)))&&(!closelist[neighbour.y][neighbour.x]))
            {
                
                h[neighbour.y][neighbour.x] = calculateDistance(neighbour,map.goal);
                g[neighbour.y][neighbour.x] = g[currentP.y][currentP.x]+calculateDistance(neighbour,currentP);
                f[neighbour.y][neighbour.x] = h[map.start.y][map.start.x]+g[map.start.y][map.start.x];
                b[neighbour.y][neighbour.x] = currentP;
                float _f =f[map.start.y][map.start.x];
                
                // find the correct position to insert the cell into the priority list, according to f value
                auto insert_pos = find_if(openlist.begin(),openlist.end(),[_f](AStarUnit list_elem){return _f<list_elem.f;});
                openlist.insert(insert_pos,{neighbour,_f});
            }
            
        }
        
        
    }
    
    // form the waypoint list from the goal cell in the map
    deque<Grid> tempWayPoint;
    Grid trace = map.goal;
    while (trace!=Grid(-1.0,-1.0))
    {
        tempWayPoint.push_front(trace);
        
        trace = b[trace.y][trace.x];
    }
    
    wayPoint.assign(tempWayPoint.cbegin(),tempWayPoint.cend());
    
    
    return wayPoint;
}
Example #7
0
void CProximity::GetProximity(CbleDevice *pdevice)
{
#if __INTERNAL_DEBUG_
    DBG("Enter.");
#endif
//#if __INTERNAL_DEBUG_
    DBG("thing ea = %d", map_rssi.size() );
    DBG("RSSI ea = %d", RSSI_EA );

    for (int num = 0; num < map_rssi.size(); num++ )
    {
        std::string addr = pdevice->getNext(num)->remote_address;
        DBG("Addr -> %s", addr.c_str() );
        for (int i = 0; i < RSSI_EA ; i++)
            DBG(" %d th. rssi = %d", i, map_rssi[addr].rssi[i] );
    }
//#endif

    reference_ea = map_rssi.size();
    float *avg = new float[reference_ea];

    if ( is_first )
        prox_first_setting( reference_ea );

    for (int i = 0; i < reference_ea; i++)
    {
        std::string addr = pdevice->getNext(i)->remote_address;

        if ( rssicnt[i] > arraysize - 1)
            rssicnt[i] = rssicnt[i] % arraysize;

        for (int j = 0; j < RSSI_EA; j++)
        {
            rssi[i][rssicnt[i]] = map_rssi[addr].rssi[j];
            rssicnt[i]++;
        }

        avg[i] = CalculateExponentialAverage(RSSI_EA, rssi[i], startindex[i], flag[i]);
        m_distance[i] = calculateDistance(avg[i], -58);

        if ( m_distance[i] <= 1.0 )
        {
            m_proximity[i] = 1;
        }
        else if (m_distance[i] <= 2)
        {
            m_proximity[i] = 2;
        }
        else
        {
            m_proximity[i] = 3;
        }

        DBG("distance = %f", m_distance[i]);
        DBG("proximity = %d", m_proximity[i]);
        //Serial.println(calculateDistance(avg[i], -58));
        startindex[i] += RSSI_EA;

        if (startindex[i] >= arraysize)
        {
            startindex[i] = 0;
        }

        if (flag[i] < (arraysize / RSSI_EA))
        {
            flag[i]++;
        }
    } // for

    delete avg;
}
Example #8
0
Coordinate City::getAdjecantStreet(CityObjects* building, Coordinate truckLoc) {
	REQUIRE(properlyInitialized(), "Object 'City' was not properly properlyInitializedialized when calling getAdjecantStreet()");

	Structures* ptr = dynamic_cast<Structures*>(building);
	std::vector<Coordinate> coordinates;
	Coordinate location;

	for (int x = 0; x < ptr->getWidth(); x++){
		for (int y = 0; y < ptr->getLength(); y++){
			location = ptr->getLocation();
			location.setX(location.getX()+x);
			location.setY(location.getY()-y);

			if (location.getY() < matrix.getRows()-1) {
				if (matrix.getObject(location.getX(), location.getY()+1) == NULL) {
					continue;
				}
				else if(matrix.getObject(location.getX(), location.getY()+1)->getType() == street){
					coordinates.push_back(Coordinate(location.getX(), location.getY()+1));
				}
			}

			if (location.getY() > 0){
				if (matrix.getObject(location.getX(), location.getY()-1) == NULL) {
					continue;
				}
				else if(matrix.getObject(location.getX(), location.getY()-1)->getType() == street){
					coordinates.push_back(Coordinate(location.getX(), location.getY()-1));
				}
			}

			if (location.getX() < matrix.getColumns()-1){
				if (matrix.getObject(location.getX()+1, location.getY()) == NULL) {
					continue;
				}
				else if (matrix.getObject(location.getX()+1, location.getY())->getType() == street){
					coordinates.push_back(Coordinate(location.getX()+1, location.getY()));
				}
			}
			if (location.getX() > 0){
				if (matrix.getObject(location.getX()-1, location.getY()) == NULL) {
					continue;
				}
				else if(matrix.getObject(location.getX()-1, location.getY())->getType() == street){
					coordinates.push_back(Coordinate(location.getX()-1, location.getY()));
				}
			}
		}
	}

	if (coordinates.size() == 0){
		return Coordinate(-1, -1);
	}

	std::pair<double, Coordinate> closest(calculateDistance(*coordinates.begin(), truckLoc), *coordinates.begin());

	for(std::vector<Coordinate>::iterator it = coordinates.begin(); it != coordinates.end(); it++){
		if (calculateDistance(*it, truckLoc) < closest.first) {
			closest.first = calculateDistance(*it, truckLoc);
			closest.second = *it;
		}
	}

	return closest.second;
}
void fantasma::mover_fantasma(){
	borrar_fantasma();
	choque_pacman();
	float nearerDistance = calculateDistance(Point2D(_x*1.0, _y*1.0), Point2D(x*1.0, y*1.0));
	float newDistance = nearerDistance;
	float fuzzyRate = fuzzyReaction(nearerDistance);
	//printf("%f", fuzzyRate);
	int bolx = _x, boly = _y;

	if (mapa[_y][_x] == '|'){
		fdir = rand() % 4;
	}
	if (mapa[_y][_x] == '*'){
		fdir = 0;
	}
	// fuzzy Bonus
	if ((fuzzyRate > .50 && fuzzyRate <= 1.0) || (fuzzyRate > .25 && rand() % 10 == 3)){
		for (int i = 0; i < 4; i++){
			if (i == 2){
				newDistance = calculateDistance(Point2D((_x+1)*1.0, _y*1.0), Point2D(x*1.0, y*1.0));
				if(mapa[_y][_x + 1] != 'X' && mapa[_y][_x + 1] != 'A' && mapa[_y][_x + 1] != 'Y' &&
					mapa[_y][_x + 1] != 'B' && mapa[_y][_x + 1] != 'C' && mapa[_y][_x + 1] != 'D'){
					if (pillTimer < 0 && newDistance < nearerDistance){
						fdir = i;
					}
					else if (pillTimer >= 0 && newDistance > nearerDistance){
						fdir = i;
					}
				}
			}
			if (i == 3){
				newDistance = calculateDistance(Point2D((_x - 1)*1.0, _y*1.0), Point2D(x*1.0, y*1.0));
				if (mapa[_y][_x - 1] != 'X' && mapa[_y][_x - 1] != 'A' && mapa[_y][_x - 1] != 'Y' &&
					mapa[_y][_x - 1] != 'B' && mapa[_y][_x - 1] != 'C' && mapa[_y][_x - 1] != 'D'){
					if (pillTimer < 0 && newDistance < nearerDistance){
						fdir = i;
					}
					else if (pillTimer >= 0 && newDistance > nearerDistance){
						fdir = i;
					}
				}
			}
			if (i == 0){
				newDistance = calculateDistance(Point2D(_x*1.0, (_y-1)*1.0), Point2D(x*1.0, y*1.0));
				if (mapa[_y - 1][_x] != 'X' && mapa[_y - 1][_x] != 'A' && mapa[_y - 1][_x] != 'Y' &&
					mapa[_y - 1][_x] != 'B' && mapa[_y - 1][_x] != 'C' && mapa[_y - 1][_x] != 'D'){
					if (pillTimer < 0 && newDistance < nearerDistance){
						fdir = i;
					}
					else if (pillTimer >= 0 && newDistance > nearerDistance){
						fdir = i;
					}
				}
			}
			if (i == 1){
				newDistance = calculateDistance(Point2D(_x*1.0, (_y + 1)*1.0), Point2D(x*1.0, y*1.0));
				if (mapa[_y + 1][_x] != 'X' && mapa[_y + 1][_x] != 'A' && mapa[_y + 1][_x] != 'Y' &&
					mapa[_y + 1][_x] != 'B' && mapa[_y + 1][_x] != 'C' && mapa[_y + 1][_x] != 'D'){
					if (pillTimer < 0 && newDistance < nearerDistance){
						fdir = i;
					}
					else if (pillTimer >= 0 && newDistance > nearerDistance){
						fdir = i;
					}
				}
			}
		}
	}
		if (fdir == 2){
			if (mapa[_y][_x + 1] != 'X' && mapa[_y][_x + 1] != 'A' && mapa[_y][_x + 1] != 'Y' &&
				mapa[_y][_x + 1] != 'B' && mapa[_y][_x + 1] != 'C' && mapa[_y][_x + 1] != 'D')         
				_x++;
			else fdir = rand() % 4;
		}
		if (fdir == 3){
			newDistance = calculateDistance(Point2D((_x - 1)*1.0, _y*1.0), Point2D(x*1.0, y*1.0));
			if (mapa[_y][_x - 1] != 'X' && mapa[_y][_x - 1] != 'A' && mapa[_y][_x - 1] != 'Y' &&
				mapa[_y][_x - 1] != 'B' && mapa[_y][_x - 1] != 'C' && mapa[_y][_x - 1] != 'D')          
				_x--;
			else fdir = rand() % 4;
		}
		if (fdir == 0){
			if (mapa[_y - 1][_x] != 'X' && mapa[_y - 1][_x] != 'A' && mapa[_y - 1][_x] != 'Y' &&
				mapa[_y - 1][_x] != 'B' && mapa[_y - 1][_x] != 'C' && mapa[_y - 1][_x] != 'D')           
				_y--;
			else fdir = rand() % 4;
		}
		if (fdir == 1){
			if (mapa[_y + 1][_x] != 'X' && mapa[_y + 1][_x] != 'A' && mapa[_y + 1][_x] != 'Y' &&
				mapa[_y + 1][_x] != 'B' && mapa[_y + 1][_x] != 'C' && mapa[_y + 1][_x] != 'D')                
				_y++;
			else fdir = rand() % 4;
		}
		if (fuzzyRate < .50 || (rand() % 10 == 3 && fuzzyRate <= .75)){
			if (fuzzyRate >.50 || (fuzzyRate > .25 && rand() % 10 == 3)){
				for (int i = 0; i < 4; i++){
					if (i == 2){
						newDistance = calculateDistance(Point2D((_x + 1)*1.0, _y*1.0), Point2D(x*1.0, y*1.0));
						if (mapa[_y][_x + 1] != 'X' && mapa[_y][_x + 1] != 'A' && mapa[_y][_x + 1] != 'Y' &&
							mapa[_y][_x + 1] != 'B' && mapa[_y][_x + 1] != 'C' && mapa[_y][_x + 1] != 'D'){
							if (pillTimer < 0 && newDistance < nearerDistance){
								fdir = i;
							}
							else if (pillTimer > 0 && newDistance > nearerDistance){
								fdir = i;
							}
						}
						else{
							fdir = rand() % 4;
						}
					}
					if (i == 3){
						newDistance = calculateDistance(Point2D((_x - 1)*1.0, _y*1.0), Point2D(x*1.0, y*1.0));
						if (mapa[_y][_x - 1] != 'X' && mapa[_y][_x - 1] != 'A' && mapa[_y][_x - 1] != 'Y' &&
							mapa[_y][_x - 1] != 'B' && mapa[_y][_x - 1] != 'C' && mapa[_y][_x - 1] != 'D'){
							if (pillTimer < 0 && newDistance < nearerDistance){
								fdir = i;
							}
							else if (pillTimer >= 0 && newDistance > nearerDistance){
								fdir = i;
							}
						}
						else{
							fdir = rand() % 4;
						}
					}
					if (i == 0){
						newDistance = calculateDistance(Point2D(_x*1.0, (_y - 1)*1.0), Point2D(x*1.0, y*1.0));
						if (mapa[_y - 1][_x] != 'X' && mapa[_y - 1][_x] != 'A' && mapa[_y - 1][_x] != 'Y' &&
							mapa[_y - 1][_x] != 'B' && mapa[_y - 1][_x] != 'C' && mapa[_y - 1][_x] != 'D'){
							if (pillTimer < 0 && newDistance < nearerDistance){
								fdir = i;
							}
							else if (pillTimer >= 0 && newDistance > nearerDistance){
								fdir = i;
							}
						}
						else{
							fdir = rand() % 4;
						}
					}
					if (i == 1){
						newDistance = calculateDistance(Point2D(_x*1.0, (_y + 1)*1.0), Point2D(x*1.0, y*1.0));
						if (mapa[_y + 1][_x] != 'X' && mapa[_y + 1][_x] != 'A' && mapa[_y + 1][_x] != 'Y' &&
							mapa[_y + 1][_x] != 'B' && mapa[_y + 1][_x] != 'C' && mapa[_y + 1][_x] != 'D') {
							if (pillTimer < 0 && newDistance < nearerDistance){
								fdir = i;
							}
							else if (pillTimer >= 0 && newDistance > nearerDistance){
								fdir = i;
							}
						}
					}
				}
				if (fdir == 2){
					if (mapa[_y][_x + 1] != 'X' && mapa[_y][_x + 1] != 'A' && mapa[_y][_x + 1] != 'Y' &&
						mapa[_y][_x + 1] != 'B' && mapa[_y][_x + 1] != 'C' && mapa[_y][_x + 1] != 'D')         _x++;
					else fdir = rand() % 4;
				}
				if (fdir == 3){
					if (mapa[_y][_x - 1] != 'X' && mapa[_y][_x - 1] != 'A' && mapa[_y][_x - 1] != 'Y' &&
						mapa[_y][_x - 1] != 'B' && mapa[_y][_x - 1] != 'C' && mapa[_y][_x - 1] != 'D')          _x--;
					else fdir = rand() % 4;
				}
				if (fdir == 0){
					if (mapa[_y - 1][_x] != 'X' && mapa[_y - 1][_x] != 'A' && mapa[_y - 1][_x] != 'Y' &&
						mapa[_y - 1][_x] != 'B' && mapa[_y - 1][_x] != 'C' && mapa[_y - 1][_x] != 'D')           _y--;
					else fdir = rand() % 4;
				}
				if (fdir == 1){
					if (mapa[_y + 1][_x] != 'X' && mapa[_y + 1][_x] != 'A' && mapa[_y + 1][_x] != 'Y' &&
						mapa[_y + 1][_x] != 'B' && mapa[_y + 1][_x] != 'C' && mapa[_y + 1][_x] != 'D')                _y++;
					else fdir = rand() % 4;
				}
			}
		}
	if (mapa[boly][bolx] == '_') { setCColor(color[1]); gotoxy(bolx, boly); printf("%c", 250); }

	// rutina atajo
	if (_x <= 17) _x = 61;
	else if (_x >= 62) _x = 18;
	dibujar_fantasma();
}
Example #10
0
float World::calculateDistance(std::vector<float> pos1, std::vector<float> pos2)
{
    return calculateDistance(pos1.at(0), pos1.at(1), pos2.at(0), pos2.at(1));
}
Example #11
0
float World::calculateDistance(float x1, float y1, std::vector<float> pos2)
{
    return calculateDistance(x1,y1, pos2.at(0), pos2.at(1));
}
Example #12
0
// Constructor
World::World(sf::Clock* clock, float worldLength, float worldHeight) : simulationClock(clock), maxWaveDistance(0.0f), optimiseWaveTravelDistance(true), waveAplitudeLoss(0.0f), useWaveAttenuation(true), waveSpeed(5)
{
    this->receptors.clear();
    this->maxWorldDistance = calculateDistance(0,0, worldLength, worldHeight);
}
void ProcessingRuleContainer::parseFrameRangeByGPS(std::string gpsFilePath, double fps){

	std::cout << "PARSE RANGE BY GPS" << std::endl;

	PROCESSING_RULE rule;
	int index = 0;//index of filterInFrameList[]
	int lineCount = 0;
	std::ifstream inputFile;
	inputFile.open(gpsFilePath.c_str());
	double radius, lat1, lon1, dist;
	std::string currentTime;
	std::string line;
	double start, current, hour, min, sec;
	std::vector<struct point> pointList;
	struct point newPoint;

	int frameCount;


	if (!inputFile.is_open())
		return;


	//load gps file
	while( std::getline(inputFile, line) ) {

			 std::cout << line << std::endl;

			 currentTime = line.substr(line.find_first_of("T")+1, line.find_last_of("-", line.find_first_of(";"))-line.find("T")-1);

			// std::cout << currentTime << std::endl;

			 hour = boost::lexical_cast<double>(currentTime.substr(0, 2).c_str());
			 min = boost::lexical_cast<double>(currentTime.substr(currentTime.find(":", 0)+1, 2).c_str());
			 sec = boost::lexical_cast<double>(currentTime.substr( currentTime.find_last_of(":")+1, currentTime.size()-currentTime.find_last_of(":")-1).c_str());

			 current = hour*3600+min*60+sec;


			 if (lineCount == 0){
				 start = current;
		     }

		     lineCount++;

		     newPoint.lat = boost::lexical_cast<double>(line.substr(line.find_first_of(";")+1, (line.find_last_of(";")-line.find_first_of(";")-1)).c_str());
			 newPoint.lon = boost::lexical_cast<double>(line.substr(line.find_last_of(";")+1, (line.size()-line.find_last_of(";")-1)).c_str());

			 newPoint.time = current - start;


			 std::cout << "new point " << newPoint.time << ":" << newPoint.lat << ": " << newPoint.lon << std::endl;
			 pointList.push_back(newPoint);
	}



	for (std::list<PROCESSING_RULE>::iterator i= ruleList.begin(); i != ruleList.end(); i++){

		rule = (*i);

		if (rule.locationFilterList.empty()){
			std::cout << "Locationfilter list is empty" << std::endl;
			continue;
		}

		std::list<LOCATION_FILTER>::iterator it;
		std::list<double>::iterator j;


		//currently the size of filteredInFrameList is set to 32
		index = rule.index;


		for (it = rule.locationFilterList.begin(); it != rule.locationFilterList.end(); it++){

			if ((*it).getParamList().size() == 3){

				j = (*it).getParamList().begin();
				radius = *j;
				j++;
				lat1 = *j;
				j++;
				lon1 = *j;

				std::cout << "rule set radius: " << radius << "lat: " << lat1 << "lon: " << lon1 << std::endl;


				bool bInside = false;

				for (std::vector<struct point>::iterator m = pointList.begin(); m!= pointList.end(); m++){


					 dist = calculateDistance(lat1, lon1, (*m).lat, (*m).lon);

					 std::cout << "distance " << dist << std::endl;


					 if (dist <= radius){


						 //included in the range
						 frameCount = (*m).time * fps;

						 std::cout << (*m).time << ", " << (*i).filteredInFrameList[index].second <<  std::endl;

						 if (!bInside){
							 	 if (index >0 )
							 		 index++;

								(*i).filteredInFrameList[index].first = frameCount;
								(*i).filteredInFrameList[index].second = frameCount;

								bInside = true;
						 } else {

								 (*i).filteredInFrameList[index].second = frameCount;
						 }
					  }//if radius
					 else{
						 bInside = false;
					 }
				}//for vector

				std::cout << "location scoped from " << (*i).filteredInFrameList[index].first << " to " << (*i).filteredInFrameList[index].second << std::endl;
				//check if the location is included. try to jump instead of reading each one

		}//if paramList.size() == 3
		else {
			j = (*it).getParamList().begin();

			double minLat = radius = *j;
			j++;
			double minLong = *j;
			j++;
			double maxLat = *j;
			j++;
			double maxLong = *j;

			std::cout << "rule set leftdown, rightup(lat,lon)" << minLat << "," << minLong << " " << maxLat << ","<< maxLong << std::endl;


			bool bInside = false;

			for (std::vector<struct point>::iterator m = pointList.begin(); m!= pointList.end(); m++){


					if (((*m).lat >= minLat) && ((*m).lat <= maxLat) && ((*m).lon >= minLong) && ((*m).lon <= maxLong)) {

						 //included in the range
						 frameCount = (*m).time*fps;

						 if (!bInside){
						 	 if (index >0 )
						 		 index++;

						 	 (*i).filteredInFrameList[index].first = frameCount;
						 	 (*i).filteredInFrameList[index].second = frameCount;

						 	 bInside = true;
						 } else
						 	 (*i).filteredInFrameList[index].second = frameCount;
					}
					else
						bInside = false;

					std::cout << "location scoped from " << (*i).filteredInFrameList[index].first << " to " << (*i).filteredInFrameList[index].second << std::endl;
				}//for vector

							//check if the location is included. try to jump instead of reading each one
			}//for filterList

		}//else


		if ((*i).filteredInFrameList[0].second > 0)
			(*i).index = index+1;

	}//for ruleList


}
Position Monster::calculateToPosition (const Game& game, const Position& player_position) const {
	// Examine the four possible locations for the monster to move,
	// one to each of north, south, east, and west, to see which
	// is closest to the target
	Position new_position = position;
	double new_distance = calculateDistance(position, player_position);

	Position temp_position;
	double temp_distance;

	if (position.row > 0)
	{
		temp_position = 
			toPosition(position.row - 1, position.column);
		temp_distance = calculateDistance(temp_position, player_position);
		if (!game.isBlockedForMonster(temp_position)) { //Check for wall
			if (temp_distance < new_distance)
			{
				new_position = temp_position;
				new_distance = temp_distance;
			}
		}
	}
	if (position.row  < (ROWS - 1))
	{
		temp_position = 
			toPosition(position.row + 1, position.column);
		temp_distance = calculateDistance(temp_position, player_position);
		if (!game.isBlockedForMonster(temp_position)) {
			if (temp_distance < new_distance)
			{
				new_position = temp_position;
				new_distance = temp_distance;
			}
		}
	}
	if (position.column > 0)
	{
		temp_position = 
			toPosition(position.row, position.column - 1);
		temp_distance = calculateDistance(temp_position, player_position);
		if (!game.isBlockedForMonster(temp_position)) {
			if (temp_distance < new_distance)
			{
				new_position = temp_position;
				new_distance = temp_distance;
			}
		}
	}
	if (position.column < (COLUMNS - 1))
	{
		temp_position = 
			toPosition(position.row, position.column + 1);
		temp_distance = calculateDistance(temp_position, player_position);
		if (!game.isBlockedForMonster(temp_position)) {
			if (temp_distance < new_distance)
			{
				new_position = temp_position;
				new_distance = temp_distance;
			}
		}
	}
	return new_position;
}
Example #15
0
void PanelRadar::updateRadarInfo()
{
	if (!getVisible())
	{
		return;
	}

	// find what avatars we can know about
	std::vector<LLUUID> avatar_ids;
	std::vector<LLVector3d> positions;
	LLWorld::getInstance()->getAvatars(&avatar_ids, &positions);

	if (!avatar_ids.empty())
	{
		for (U32 i=0; i<avatar_ids.size(); i++)
		{
			// This actually happens sometimes O.o
			if (avatar_ids[i] == gAgent.getID() || avatar_ids[i].isNull())
			{
				continue;
			}

			// Determine if they're in the list already--getEntry checks for null keys
			PanelRadarEntry* entry = getEntry(avatar_ids[i]);

			// If they aren't, create a new entry
			// If they are, see if we need to update any values
			// List them as "(Unknown)" if we can't get their name
			if (!entry)
			{
				mAvatars.insert(std::pair<LLUUID, PanelRadarEntry>(avatar_ids[i], PanelRadarEntry(avatar_ids[i], 
																	getSelectedName(avatar_ids[i]),
																	calculateDistance(avatar_ids[i], positions[i]),
																	positions[i],
																	RADAR_STATUS_NONE,
																	RADAR_NOTIFIED_NONE)
																	));
			}
			else
			{
				if (entry->getName() == getString("unknown_avatar"))
				{
					// Try to find the name again
					entry->setName(getSelectedName(avatar_ids[i]));
				}
				if (entry->getPosition() != positions[i])
				{
					entry->setPosition(positions[i]);
				}
				if (entry->getStatusTimer().hasExpired())
				{
					entry->setStatus(RADAR_STATUS_NONE);
				}
				entry->setDistance(calculateDistance(avatar_ids[i], positions[i]));
			}
		}
		removeDeadEntries(avatar_ids);
	}
	else // avatar_ids empty
	{
		mRadarList->deleteAllItems();
		mRadarList->addCommentText(getString("no_one_near"), ADD_TOP);
		LLUIString av_count_string = getString("avatars_in_plural");
		av_count_string.setArg("[COUNT]", "0");
		childSetText("avatar_count", av_count_string.getString());
		return;
	}

	updateRadarDisplay();
}
Example #16
0
int SkeletonState::update(Skeleton skeleton)
{
    // copy the skeleton joints to member
    skeleton_ = skeleton;

    // are we confident in joint positions?
    bool confidentLeft  = false;
    bool confidentRight = false;

    if(skeleton_.leftHand.confidence > 0.5 && skeleton_.leftElbow.confidence > 0.5 && skeleton_.leftShoulder.confidence > 0.5)
        confidentLeft = true;

    if(skeleton_.rightHand.confidence > 0.5 && skeleton_.rightElbow.confidence > 0.5 && skeleton_.rightShoulder.confidence > 0.5)
        confidentRight = true;

    // if we are not a controlling user, check for the signal and return
    if(control_ == false)
    {
        // make sure hands are marked inactive
        leftHandActive_ = rightHandActive_ = false;

        // the raising of left hand above head
        if(confidentLeft && skeleton_.leftHand.y > skeleton_.head.y)
        {
            control_ = true;

            controlTimeOut_.restart();

            return 1;
        }
        else
            return 0;
    }

    // depth threshold - factor length of elbow to shoulder
    float depthThreshold = 1.2 * calculateDistance(skeleton_.rightShoulder, skeleton_.rightElbow);

    // magnitude of arm length
    float armLength = calculateDistance(skeleton_.rightHand, skeleton_.rightElbow) +
                      calculateDistance(skeleton_.rightElbow, skeleton_.rightShoulder);

    // the maximum distance that can be reached by arm while crossing depth plane
    float maxReach = sqrtf(armLength*armLength - depthThreshold*depthThreshold);

    // marker position (normalized)
    float normX = ((skeleton_.rightHand.x - skeleton_.rightShoulder.x) + maxReach)/(2.*maxReach);
    float normY = 1. - ((skeleton_.rightHand.y - skeleton_.rightShoulder.y) + maxReach)/(2.*maxReach);

    // determine if hands are active
    if(confidentLeft && (skeleton_.leftShoulder.z - skeleton_.leftHand.z) > depthThreshold)
        leftHandActive_ = true;
    else
        leftHandActive_ = false;

    if(confidentRight && (skeleton_.rightShoulder.z - skeleton_.rightHand.z) > depthThreshold)
        rightHandActive_ = true;
    else
        rightHandActive_ = false;

    // update marker if right hand is active
    if(rightHandActive_)
    {
        // restart marker timer
        markerTimeOut_.restart();

        // keep track of old position
        float oldX, oldY;
        displayGroup_->getMarker()->getPosition(oldX, oldY);

        // set new position
        displayGroup_->getMarker()->setPosition(normX, normY);

        // if we do not have an active window
        if(activeWindow_ == false)
        {
            // see if we have a window under the marker
            boost::shared_ptr<ContentWindowInterface> cwi = displayGroup_->getContentWindowInterfaceUnderMarker();

            // no window under marker
            if(cwi != NULL)
            {
                // first time marker is over window, or the window under marker has changed
                if(hoverWindow_ == NULL || hoverWindow_ != cwi)
                {
                    hoverTime_.restart();
                    hoverWindow_ = cwi;
                }

                // we have hovered long enough to make the window active and move it to front
                if(hoverTime_.elapsed() > HOVER_TIME)
                {
                    activeWindow_ = true;
                    hoverWindow_->moveToFront();

                    // highlight the window
                    hoverWindow_->highlight();
                }
            }
        }
        else
        {
            // we have an active window

            // look for mode change pose: hand over head
            if(confidentLeft && skeleton_.leftHand.y > skeleton_.head.y && modeChangeTimeOut_.elapsed() > MODE_CHANGE_TIME && controlTimeOut_.elapsed() > MODE_CHANGE_TIME)
            {
                // change mode and reset timer
                focusInteraction_ = !focusInteraction_;
                modeChangeTimeOut_.restart();
            }

            // neutral distance for zooming, scaling
            float neutralDistance = 2. * calculateDistance(skeleton_.rightHand, skeleton_.rightElbow);

            if(focusInteraction_ == true)
            {
                // left hand is active, zoom in window
                if(leftHandActive_)
                {
                    float zoomFactor = calculateDistance(skeleton_.leftHand, skeleton_.rightHand) / neutralDistance;

                    zoomFactor = 1. + (zoomFactor - 1.)*WINDOW_ZOOM_FACTOR;

                    hoverWindow_->setZoom(zoomFactor * hoverWindow_->getZoom());
                }
                else
                {
                    // left hand not present (but we do have right hand), pan in window
                    double oldCenterX, oldCenterY;
                    hoverWindow_->getCenter(oldCenterX, oldCenterY);

                    hoverWindow_->setCenter(oldCenterX + (normX-0.5)*WINDOW_PAN_FACTOR/hoverWindow_->getZoom(), oldCenterY + (normY-0.5)*WINDOW_PAN_FACTOR/hoverWindow_->getZoom());
                }
            }
            else
            {
                // left hand is active, scale window
                if(leftHandActive_)
                {
                    float scaleFactor = calculateDistance(skeleton_.leftHand, skeleton_.rightHand) / neutralDistance;

                    scaleFactor = 1. + (scaleFactor - 1.)*WINDOW_SCALE_FACTOR;

                    hoverWindow_->scaleSize(scaleFactor);
                }
                else
                {
                    // left hand not present (but we do have right hand), move window under marker
                    double dx = normX - oldX;
                    double dy = normY - oldY;

                    double oldPositionX, oldPositionY;
                    hoverWindow_->getPosition(oldPositionX, oldPositionY);

                    hoverWindow_->setPosition(oldPositionX + dx, oldPositionY + dy);
                }
            }
        }
    }
    else
    {
        // right hand not active

        // sometimes the confidence is lost for a brief moment, so use timeout before making changes
        if(markerTimeOut_.elapsed() > DEAD_MARKER_TIME)
        {
            // no longer have an active window; set hover window to NULL
            activeWindow_ = false;
            hoverWindow_ = boost::shared_ptr<ContentWindowInterface>();

            // the first mode should always be focus interaction
            focusInteraction_ = true;
        }
    }

    return 0;
}
Example #17
0
Result *TSPSimulatedAnnealing::solve()
{
	/**
	 * 1). losujesz rozwiazanie
	 * 2). losujesz sąsiada żeby do niego przejść
	 * 3). przechodzisz jak jest lepszy a jak nie to sprawdzasz prawdopodobieństwo przejścia
	 * 4). koniec algorytmu, gdy:
	 * 		- osiągnie daną liczbę kroków
	 * 		- jeżeli nie ma poprawy po określonej liczbie kroków
	 * 		- przy przejśiu sprawdzamy czy temperatuda nie opadła poniżej minimum
	 */
	Result *cur;
	Result *next;
	Result *best = NULL;
	u_int32_t bestDistance = 0, noBadMovesCounter = 0;
	u_int32_t loopCounter = 0;
	u_int32_t neighorsVisited = 0, betterSolutionsCount = 0;
	u_int32_t nextDistance, curDistance, worseSolutions = 0;

	//printf("%f %f %f %d\n", _startTemperature, _endTemperature, _alpha, _maxBadMoves);

	_temperature = _startTemperature;


	cur = generateRandomResult();

//	TSPGreedySolver2 *greedySolver2;
//	greedySolver2 = new TSPGreedySolver2(_instance, "");
//	cur = greedySolver2->solve();
//	delete greedySolver2;

	best = new Result(*cur);
	bestDistance = calculateDistance(cur);

	while ((_temperature > _endTemperature) &&
			(loopCounter < getNumberOfSteps()) && (noBadMovesCounter < _maxBadMoves))
	{
		next = new Result(*cur);
		next->swapRandomly();

		nextDistance = calculateDistance(next);
		next->setCalculatedDistance(nextDistance);
		neighorsVisited++;

		float lotery = ((float) (rand() % RAND_MAX) / (float) RAND_MAX);
		float accProb = acceptanceProbability(curDistance, nextDistance);

		//kiedy przechodzimy do nowego rozwiazania
		if ((nextDistance < curDistance) || (lotery > accProb))
		{
			delete cur;
			cur = next;
			noBadMovesCounter = 0;

			if (nextDistance >= curDistance)
			{
				//printf("worse %f %f %f\n", lotery, accProb, _temperature);
				worseSolutions++;
			}

			if (nextDistance < bestDistance)
			{
				if (best != NULL)
					delete best;
				betterSolutionsCount++;
				best = new Result(*next);
				bestDistance = nextDistance;
				best->setCalculatedDistance(bestDistance);
			}

			curDistance = calculateDistance(cur);
			cur->setCalculatedDistance(curDistance);
		}
		else
		{
			noBadMovesCounter++;
			delete next;
		}
		loopCounter++;
		_temperature *= _alpha;
	}

//	printf("worse: %d\n", worseSolutions);
//	printf("temperature: %f\n", _temperature);
//	printf("loopCounter: %d\n", loopCounter);
//	printf("bad moves: %d\n", noBadMovesCounter);

	best->setNeighborsVisited(neighorsVisited);
	best->setStepsCount(loopCounter);
	best->setBetterSolutionsCount(betterSolutionsCount);

	return best;
}
Example #18
0
uint16_t contentAccessModuleServer::searchPOIRequest(uint16_t categoryIndex, std::string search_string, DBus_geoCoordinate3D::geoCoordinate3D_t left_bottom_location,DBus_geoCoordinate3D::geoCoordinate3D_t right_top_location)
    {
        std::string sqlQuery; //SQL request on database
        vector<vector<string> > sqlQueryResult; //result of the query on database
        vector<string>  sqlQueryLine;
        std::ostringstream  strStream; //temporary stream used for transformation into string
        size_t index,sub_index,attribute_index;
        DBus_poiCAMDetails poiCAMDet;
        DBus_poiCAMDetails::poiCAMDetails_t poi; //source_id, name, category, location, distance, attributes
        DBus_poiAttribute::poiAttribute_t  poiAttrib;
        DBus_searchResultDetails poiDet;
        DBus_searchResultDetails::searchResultDetails_t poiDetails; //details(unique id, name, lat, lon, alt), categories, attributes(name, type, value)
        std::string name;

        name = m_availableCategoryTable[categoryIndex].name;

        sqlQuery = "SELECT name,segment,latitude,longitude,altitude";
        for (attribute_index=0;attribute_index<m_availableCategoryTable[categoryIndex].attributeList.size();attribute_index++)
        {
            if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).isSearched == true)
            {
                sqlQuery += ",";
                sqlQuery += (m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).name;
            }

        }

        sqlQuery += " FROM poi WHERE (Id IN (SELECT poi_Id FROM belongsto,poicategory WHERE (belongsto.poicategory_Id = poicategory.Id) AND (poicategory.name = '";
        sqlQuery += name;
        sqlQuery += "'))) AND ((latitude > ";
        strStream.str(""); //to clean before !
        strStream << left_bottom_location.latitude;
        sqlQuery += strStream.str();
        sqlQuery += ") AND (latitude < ";
        strStream.str(""); //to clean before !
        strStream << right_top_location.latitude;
        sqlQuery += strStream.str();
        sqlQuery += ")) AND ((longitude > ";
        strStream.str(""); //to clean before !
        strStream << left_bottom_location.longitude;
        sqlQuery += strStream.str();
        sqlQuery += ") AND (longitude < ";
        strStream.str(""); //to clean before !
        strStream << right_top_location.longitude;
        sqlQuery += strStream.str();
        sqlQuery += ")) AND (name LIKE '%";
        sqlQuery += search_string;
        sqlQuery += "%');";
        sqlQueryResult = mp_database->query(sqlQuery.c_str());

        //populate the tables of poi
        poi.category = categoryIndex; //category
        poiDetails.categories.push_back(m_availableCategoryTable[categoryIndex].alias_id); //categories for the table of details

        for (index=0;index<sqlQueryResult.size();index++)
        {
            sqlQueryLine = sqlQueryResult.at(index);
            fromString<poiId_t>(poi.source_id,sqlQueryLine[1], std::dec); //source_id
            fromString<poiId_t>(poiDetails.details.id,sqlQueryLine[1], std::dec); //source_id for the table of details
            poi.name = sqlQueryLine[0]; //name
            poiDetails.details.name = sqlQueryLine[0]; //name for the table of details
            fromString<double>(poi.location.latitude,sqlQueryLine[2], std::dec); //location lat
            fromString<double>(poi.location.longitude,sqlQueryLine[3], std::dec); //location lon
            fromString<double>(poi.location.altitude,sqlQueryLine[4], std::dec); //location alt

            fromString<double>(poiDetails.details.location.latitude,sqlQueryLine[2], std::dec); //location lat for the table of details
            fromString<double>(poiDetails.details.location.longitude,sqlQueryLine[3], std::dec); //location lon for the table of details
            fromString<double>(poiDetails.details.location.altitude,sqlQueryLine[4], std::dec); //location alt for the table of details

            sub_index = 5; //next index to scan into the query line
            for (attribute_index=0;attribute_index<m_availableCategoryTable[categoryIndex].attributeList.size();attribute_index++)
            {
                if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).isSearched == true)
                {
                    if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_SOURCE)
                    {
                        poiAttrib.id = (m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id;
                        poiAttrib.type = GENIVI_POISERVICE_STRING;
                        poiAttrib.value = sqlQueryLine[sub_index];
                        poi.attributes.push_back(poiAttrib);
                        poiDetails.attributes.push_back(poiAttrib); //for the table of details
                    }
                    else
                        if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_WEBSITE)
                        {
                            poiAttrib.id = (m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id;
                            poiAttrib.type = GENIVI_POISERVICE_STRING;
                            poiAttrib.value = sqlQueryLine[sub_index];
                            poi.attributes.push_back(poiAttrib);
                            poiDetails.attributes.push_back(poiAttrib); //for the table of details
                        }
                        else
                            if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_PHONE)
                            {
                                poiAttrib.id = (m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id;
                                poiAttrib.type = GENIVI_POISERVICE_STRING;
                                poiAttrib.value = sqlQueryLine[sub_index];
                                poi.attributes.push_back(poiAttrib);
                                poiDetails.attributes.push_back(poiAttrib); //for the table of details
                            }
                            else
                                if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_STARS)
                                {
                                    poiAttrib.id = (m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id;
                                    poiAttrib.type = GENIVI_POISERVICE_INTEGER;
                                    poiAttrib.value = sqlQueryLine[sub_index];
                                    poi.attributes.push_back(poiAttrib);
                                    poiDetails.attributes.push_back(poiAttrib); //for the table of details
                                }
                                else
                                    if ((m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id == ATTRIBUTE_OPENINGHOURS)
                                    {
                                        poiAttrib.id = (m_availableCategoryTable[categoryIndex].attributeList.at(attribute_index)).id;
                                        poiAttrib.type = GENIVI_POISERVICE_STRING;
                                        poiAttrib.value = sqlQueryLine[sub_index];
                                        poi.attributes.push_back(poiAttrib);
                                        poiDetails.attributes.push_back(poiAttrib); //for the table of details
                                    }
                    sub_index++;
                }

            }

            //calculate distance from the center location
            poi.distance = calculateDistance(m_centerLocation,poi.location);
            poiCAMDet.set(poi);
            m_poiTable.push_back(poiCAMDet.getDBus());
            poiDet.set(poiDetails);
            m_poiDetailsTable.push_back(poiDet.getDBus());
        }

        return(sqlQueryResult.size());
    }
Example #19
0
void Planner::updateVertex(list<Uelem> &U, Grid &u, vector<vector<int> > &g, vector<vector<int> > &rhs, Map &map,int km)
{
    // update the vertex value and update the priority queue
    if(u!=map.goal)
    {
        vector<Grid> neighbour = findNeighbour(map, u, 8);
        vector<float> dist;
        
        for_each(neighbour.begin(),neighbour.end(),[&](Grid &it){dist.push_back((float)g[it.y][it.x]+calculateDistance(it,u));});
        
        rhs[u.y][u.x]=*min_element(dist.begin(),dist.end());
    }
    
    auto pt =find_if(U.begin(),U.end(),[u](Uelem &pt){return pt.point==u;});
    if (pt!=U.end()) U.erase(pt);
    if (g[u.y][u.x]!=rhs[u.y][u.x])
    {
        Key knew = calculateKey(u,g,rhs,map.start,0);
        auto pt = find_if(U.begin(),U.end(),[&](Uelem &a){return a.key<knew;});
        U.insert(pt,{u,knew});
    }
}
Example #20
0
int main() {
  int playAgain = 1;
  
  Uint32 waitTime = 1000.0f/30;
  Uint32 frameStartTime = 0;
  Sint32 delayTime;
  Uint32 idleTime = 0;

  Mix_Chunk* welcome   = NULL;
  Mix_Chunk* spinNoise = NULL;

  bool running = true;

  if (Mix_OpenAudio(44100, AUDIO_S16SYS, 2, 4096)) {
    cerr << "Unable to open audio" << endl;
    return false;
  }

  string temp;
  temp      = string(ROULETTE_DIR)+
    string("/sounds/welcome.wav");
  welcome   = Mix_LoadWAV(temp.c_str());
  temp      = string(ROULETTE_DIR)+
    string("/sounds/roulette_spin.wav");
  spinNoise = Mix_LoadWAV(temp.c_str());

  Mix_PlayChannel(-1, welcome, 0);

  while (playAgain == 1 && running == true) {

    SDL_Surface *screen = startupInit();

    int goodSpin = 0;
    int last_spin = -1;
    int spinningWheel = 0;

    int userInput[3] = {1,0,0};
    float dragDistance = 0;
    int startPress[2] = {0,0};

    int betSelection = -1;
    int numSelection = -1;
    int padNumber = 0;
    int playerCash = 2000;

    displayDigits(playerCash, screen, 0);

    int exit = 0;

    while (userExit(userInput) && playerCash > 0 && running == true) {

      delayTime = waitTime - (SDL_GetTicks() - frameStartTime);

      if (isRouletteWheel(userInput) == 1) {
	if (padNumber == 0) {
	  displayBetMoney(screen);
	}
	else if (betSelection == -1) {
	  displayChooseNumber(screen);
	}
	else if (numSelection != 11) {
	  displayPressEnter(screen);
	}
	else if (padNumber > playerCash) {
	  displayDontHaveCash(screen);
	}
	else {
	  clearText(screen);
	  spinningWheel = 1;
	  goodSpin = 1;
	  copyCoordinates(startPress, userInput);
	}
      }
      else if (spinningWheel && !isRouletteWheel(userInput) 
	       && userInput[0] ==3) {
	goodSpin = 0;
      }
      else if (spinningWheel && userInput[0] == 2 &&
	       (!goodSpin ||
		!calculateDistance(startPress[0], startPress[1],
				   userInput[1],userInput[2]))) {
	userInput[0] = 3;
	spinningWheel = 0;
      }
      else if (spinningWheel && goodSpin && isRouletteWheel(userInput) == 2) {
	Mix_PlayChannel(-1, spinNoise, 0);
	last_spin = spinRouletteWheel(calculateDistance(startPress[0], startPress[1], userInput[1], userInput[2]), screen, last_spin);
	playerCash = playerCash + (isWinningBet(last_spin, betSelection) * padNumber);
	clearMoneyBar(screen);
	clearRouletteWheel(screen);
	displayDigits(playerCash, screen, 0);

	spinningWheel = 0;
      }
      if (!spinningWheel) {
	betSelection = displayBetTable(userInput, screen,betSelection);
				
	numSelection = numberPadDown(userInput, screen, numSelection, padNumber);
	padNumber = numberPadUp(userInput, screen, numSelection, padNumber);
	userInput[0] = 3;
      }

      if (getUserInput(userInput) == false) {
	running  = false;
      }
      if (running == false) {
	break;
      }
      if(delayTime > 0) {
	SDL_Delay((Uint32)delayTime);
      }
      frameStartTime = SDL_GetTicks();
    }

    playAgain = -1;

    if (playerCash <= 0) {
      displayPlayAgainSplash(screen);
      while (playAgain == -1) {
	delayTime = waitTime - (SDL_GetTicks() - frameStartTime);

	getUserInput(userInput);
	playAgain = playAgainYesNo(userInput[1],userInput[2]);
	
	if(delayTime > 0) {
	  SDL_Delay((Uint32)delayTime);
	}
	frameStartTime = SDL_GetTicks();
      }
    }

    if (playAgain < 1) {
      displayCloseSplash(screen);
    } 

  }

  Mix_FreeChunk(welcome);
  Mix_FreeChunk(spinNoise);

  SDL_Quit();

  return 0;
}
Example #21
0
Result *TSPGreedySolver::solve()
{
	Timer timer;
	bool foundBetter = false;
	numberOfSteps = 0;
	u_int32_t bestDistance, changedDistance, frequency;
	u_int32_t neighorsVisited = 0, betterSolutionsCount = 0;
	Result *best, changed;

	best = generateRandomResult();
	bestDistance = calculateDistance(best);
	best->setCalculatedDistance(bestDistance);
	//best->print();
	changed = *best;

//	frequency = _stepsCount / 100;
//	if (frequency < FREQUENCY_SAVER)
	frequency = FREQUENCY_SAVER;

	timer.start();
	for (u_int32_t i = 0; i < _stepsCount; i++)
	{
		foundBetter = false;
		for (u_int32_t j = 0; j < changed.size(); j++)
		{
			for (u_int32_t k = 0; k < changed.size(); k++)
			{
				if (j == k)
					continue;

				std::swap(changed[j], changed[k]);
				neighorsVisited++;
				changedDistance = calculateDistance(&changed);
				if (changedDistance <= bestDistance)
				{
					betterSolutionsCount++;
					bestDistance = changedDistance;
					*best = changed;
					best->setCalculatedDistance(bestDistance);
					//best->print(true);
					foundBetter = true;
					break;
				}

				std::swap(changed[j], changed[k]);
			}
			numberOfSteps++;
			if (foundBetter)
				break;
		}

		//Nie ma sensu szukac dalej - w sasiedztwie nie ma lepszych rozwiazan
		if (!foundBetter)
		{
			break;
		}
//		printf("lepsze rozwiazanie: %d\n", best->getCalculatedDistance());
		u_int32_t a = i % frequency;
		//cout << a << endl;
		if(a == 0)
		{
			std::stringstream out;
			out << i;
			out << " ";
			out << best->getCalculatedDistance();
			out << " " << timer.getRunTime();
			saver->saveLine(out.str());
		}
	}

	best->setNeighborsVisited(neighorsVisited);
	best->setStepsCount(numberOfSteps);
	best->setBetterSolutionsCount(betterSolutionsCount);

	return best;
}
//    Mark C. Miller, Wed Aug 22 19:57:54 PDT 2012
//    Removed superfolous code allocating and initializing local variables,
//    score_mins and score_maxs. Nothing in the function was using these
//    variables.  
void
avtModelFitFilter::PostExecute()
{  
    intVector numTups = atts.GetNumTups();
    intVector numVars = atts.GetNumVars();
    stringVector Vars = atts.GetVars();
    doubleVector Tuples = atts.GetTuples();
    doubleVector thold  = atts.GetThold();
    unsignedCharVector StatTuples = atts.GetStatTuples();
    intVector tup_match;
    doubleVector mins;
    doubleVector point;

    int tup_index, var_index;
    vtkDataArray *darray;
    char secVarName[1024];
    int numValues;
    size_t varFinder;

    double distance;
    float *scalars;
    bool good_match;

    int relat_index;

    double opt_distance;

    intVector selectionType = atts.GetSelectionType();
    intVector distanceType  = atts.GetDistanceType();
    intVector inputSpace    = atts.GetInputSpace(); 


    //Since there may be overlap between models in variables specified,
    //create a set of all unique variables
    for(size_t i = 0; i < Vars.size(); i++)
    {
        sprintf(secVarName, "%s", Vars[i].c_str());
        createVS(secVarName);
    }
    
    //determine for each variable whether or not statistics or 
    //histograms need to be calculated
    for(int i = 0, currentVar = 0, num_to_remove = 0; i < num_relats; i++)
    {
        if(selectionType[i] == 1 || inputSpace[i] == 1)
            for(int j = 0; j < numVars[i]; j++, currentVar++, num_to_remove++)
            {
                for(varFinder = 0; varFinder < VS.size(); varFinder++)
                    if(!strcmp(VS[varFinder]->name, Vars[currentVar].c_str()))
                        break;
                VS[varFinder]->calculate_stats = true;
            }
        currentVar -= num_to_remove;
        num_to_remove = 0;

        if(selectionType[i] == 3 || inputSpace[i] == 3)
            for(int j = 0; j < numVars[i]; j++, currentVar++, num_to_remove++)
            {
                for(varFinder = 0; varFinder < VS.size(); varFinder++)
                    if(!strcmp(VS[varFinder]->name, Vars[currentVar].c_str()))
                        break;
                VS[varFinder]->calculate_hists = true;
            }
        currentVar -= num_to_remove;
        num_to_remove = 0;

        currentVar += numVars[i];
    }
    
    //also force stats calculation if stat shortcuts specified
    for(int i = 0; i < num_relats; i++)
    {
        tup_index = 0;
        var_index = 0;
        for(int j = 0; j < i; j++)
        {
            tup_index += numTups[j]*numVars[j];
            var_index += numVars[j];
        }
        for(int j = 0; j < numTups[i]*numVars[i]; j++)
            if(StatTuples[tup_index+j] == 'a' || StatTuples[tup_index+j] == 'M' || 
                    StatTuples[tup_index+j] == 'm')
            {
                for(varFinder = 0; varFinder < VS.size(); varFinder++)
                    if(!strcmp(VS[varFinder]->name, Vars[var_index + (j%numVars[i])].c_str()))
                        break;

                VS[varFinder]->calculate_stats = true;
            }
    }
    
    //Go through all variables specified and calculate
    //statistics for each.
    calculateVariableStats();
    
#ifdef PARALLEL
    int numProcs = 1;
    int myRank   = 0;
    
    MPI_Comm_rank(VISIT_MPI_COMM, &myRank);
    MPI_Comm_size(VISIT_MPI_COMM, &numProcs);

    double     *sum;
    double     *max;
    double     *min;
    double     *non_zero_min;
    int *num_points;
    int totVars  = VS.size();
    int number_on = 0;

    double *temp_hist;
    double *merged_ranges;
    
    num_points = (int    *)malloc(sizeof(int)   *totVars);
    sum        = (double *)malloc(sizeof(double)*totVars);
    max        = (double *)malloc(sizeof(double)*totVars);
    min        = (double *)malloc(sizeof(double)*totVars);
    non_zero_min = (double *)malloc(sizeof(double)*totVars);

    merged_ranges = (double *)malloc(sizeof(double)*(BINS*numProcs));
    temp_hist = (double *)malloc(sizeof(double)*BINS);

    for(int i = 0; i < totVars; i++)
    {
        if(VS[i]->calculate_stats)
        {
            num_points[i] = VS[i]->num_points;
            sum[i]        = VS[i]->sum;
            max[i]        = VS[i]->max;
            min[i]        = VS[i]->min;
            non_zero_min[i] = VS[i]->non_zero_min; 
    
            MPI_Allreduce(&num_points[i], &(VS[i]->num_points), 1, MPI_INT, MPI_SUM, VISIT_MPI_COMM);
            MPI_Allreduce(&sum[i], &(VS[i]->sum), 1, MPI_DOUBLE, MPI_SUM, VISIT_MPI_COMM);
            MPI_Allreduce(&max[i], &(VS[i]->max), 1, MPI_DOUBLE, MPI_MAX, VISIT_MPI_COMM);
            MPI_Allreduce(&min[i], &(VS[i]->min), 1, MPI_DOUBLE, MPI_MIN, VISIT_MPI_COMM);
            MPI_Allreduce(&non_zero_min[i], &(VS[i]->non_zero_min), 1, MPI_DOUBLE, MPI_MIN, VISIT_MPI_COMM);
        }

        if(VS[i]->calculate_hists)
        {
            for(int np = 0; np < numProcs; np++)
            {
                if(np == myRank)
                    memcpy(temp_hist, VS[i]->hist.range_ends, BINS*sizeof(double));
            
                MPI_Bcast(temp_hist, BINS, MPI_DOUBLE, i, VISIT_MPI_COMM);
           
                for(int j = 0; j < BINS; j++)
                    merged_ranges[number_on++] = temp_hist[j];
            }
            
            VS[i]->hist.count      = VS[i]->num_points / BINS;
            VS[i]->hist.mod_number = VS[i]->num_points % BINS;
        
            qsort(merged_ranges, BINS*numProcs, sizeof(double), compare_doubles);
        
            for(int j = 0, k = 0; j < numProcs*BINS; j += numProcs, k++)
                VS[i]->hist.range_ends[k] = merged_ranges[j];
            number_on = 0;
        }
    }

    delete num_points;
    delete sum;
    delete max;
    delete min;
    delete non_zero_min;
    delete(temp_hist);
    delete(merged_ranges);
    
#endif

    for(size_t i = 0; i < VS.size(); i++)
        if(VS[i]->num_points)
            VS[i]->average = VS[i]->sum/VS[i]->num_points;

    /*
    puts("-------before------");
    for(int i = 0; i < Tuples.size(); i++)
        printf("Tuples[%d]: %lf\n", i, Tuples[i]);
        */

    //do space converts on thresholds and tuples
    //for tuples, stick stats in if needed
    for(int i = 0; i < num_relats; i++)
    {
        tup_index = 0;
        var_index = 0;
        for(int j = 0; j < i; j++)
        {
            tup_index += numTups[j]*numVars[j];
            var_index += numVars[j];
        }
        
        for(int j = 0; j < numTups[i]*numVars[i]; j++)
        {
            sprintf(secVarName, "%s", Vars[var_index+(j%numVars[i])].c_str());
            for(varFinder = 0; varFinder < VS.size(); varFinder++)
                if(!strcmp(VS[varFinder]->name, secVarName))
                    break;
 
            //we have a thold specified
            if(thold[tup_index+j] > 0)
                if(inputSpace[i] != selectionType[i])
                {
                    thold[tup_index+j] = convertToVariableSpace(thold[tup_index+j], varFinder, inputSpace[i]);
                    thold[tup_index+j] = spaceConvert(thold[tup_index+j], varFinder, selectionType[i]);
                }

            //replace Tuples with stats
            if(StatTuples[tup_index+j] == 'a' || StatTuples[tup_index+j] == 'M' || 
                    StatTuples[tup_index+j] == 'm')
            {
                if(StatTuples[tup_index+j] == 'a')
                    Tuples[tup_index+j] = VS[varFinder]->average;
                else if (StatTuples[tup_index+j] == 'M')
                    Tuples[tup_index+j] = VS[varFinder]->max;
                else if (StatTuples[tup_index+j] == 'm')
                    Tuples[tup_index+j] = VS[varFinder]->min;

                //printf("Tuples[%d] before: %lf\n", tup_index+j, Tuples[tup_index+j]);
                Tuples[tup_index+j] = spaceConvert(Tuples[tup_index+j], varFinder, selectionType[i]);
                //printf("Tuples[%d] after: %lf\n", tup_index+j, Tuples[tup_index+j]);
            }
            else if(inputSpace[i] != selectionType[i])
            {
                //printf("Tuples[%d] before: %lf\n", tup_index+j, Tuples[tup_index+j]);
                Tuples[tup_index+j] = convertToVariableSpace(Tuples[tup_index+j], varFinder, inputSpace[i]);
                //printf("Tuples[%d] after cTVS: %lf\n", tup_index+j, Tuples[tup_index+j]);
                Tuples[tup_index+j] = spaceConvert(Tuples[tup_index+j], varFinder, selectionType[i]);
                //printf("Tuples[%d] after SC: %lf\n", tup_index+j, Tuples[tup_index+j]);
                //printf("Used %lf for min, %lf for max\n", VS[varFinder]->min, VS[varFinder]->max);
            }
        }
    }
    /*
    puts("-------after------");
    for(int i = 0; i < Tuples.size(); i++)
        printf("Tuples[%d]: %lf\n", i, Tuples[i]);
        */
    atts.SetTuples(Tuples);
    atts.SetThold(thold);

    //
    for(size_t ds = 0; ds < out_ds.size(); ds++){
        numValues = 0;
       
        if(Centering == AVT_NODECENT)
            numValues = out_ds[ds]->GetNumberOfPoints();
        else
            numValues = out_ds[ds]->GetNumberOfCells();
    
        for(int p = 0; p < numValues; p++)
        {
            opt_distance = -1; //added for
            relat_index  = -1; //distance use
        
            for(int i = 0; i < num_relats; i++)
            { //added for distances
                if(numTups[i] < 1)
                    continue;
        
                tup_index = 0;
                var_index = 0;
        
                for(int j = 0; j < i; j++)
                {
                    tup_index += numTups[j]*numVars[j];
                    var_index += numVars[j];
                }
        
                grabOnePoint(&point, numVars[i], var_index, selectionType[i], p, out_ds[ds]->GetPointData(), 
                        out_ds[ds]->GetCellData());

                findMatches(&mins, &tup_match, point, numVars[i], numTups[i], tup_index, var_index);
        
                //Find winning relationship
                if(tup_match.size() > 0)
                {
                    distance = calculateDistance(mins, distanceType[i]);
    
                    good_match = true;
                    for(size_t j = 0; j < mins.size(); j++)
                        if(mins[j] < 0)
                            good_match = false;
            
                    if(good_match)
                        if(distance < opt_distance || opt_distance < 0)
                        {
                            opt_distance = distance;
                            relat_index = i;
                        }
                }
            }
        
            if(num_relats && out_ds.size() && p < numValues){
                if(Centering == AVT_NODECENT)
                    darray = out_ds[ds]->GetPointData()->GetScalars("operators/ModelFit/model");
                else
                    darray = out_ds[ds]->GetCellData()->GetScalars("operators/ModelFit/model");
        
                scalars = (float *)darray->GetVoidPointer(0);
                scalars[p] = relat_index+1;
    
                if(Centering == AVT_NODECENT)
                    darray = out_ds[ds]->GetPointData()->GetScalars("operators/ModelFit/distance");
                else
                    darray = out_ds[ds]->GetCellData()->GetScalars("operators/ModelFit/distance");
        
                scalars = (float *)darray->GetVoidPointer(0);
                if(opt_distance > 0)
                    scalars[p] = opt_distance;
                else
                    scalars[p] = -1;
            }
        }
    }
}
void TargetDisplayWindowUpdator::update()
{
	TargetDisplayButtonManager *manager = window->getManager();
	// rect tmp = getTargetScreenRect( game );
	// window->setRect( 0, tmp.x, tmp.y, tmp.w, tmp.h );
	
	{
		float updateDistance = itemDistance * itemDistance;

		std::list< Item* >::iterator it;
		for( it = itemsToBeUpdated.begin(); it != itemsToBeUpdated.end(); ++it )
		{
			//Point tmp = convertVC3toScreen( (*it)->getPosition(), game );
			Item *item = *it;

			float distance = calculateDistance( item->getPosition(), game );
			if( distance < updateDistance )
			{

				if(item && item->getVisualObject() && item->getVisualObject()->getStormModel())
				{
					IStorm3D_Model *m = item->getVisualObject()->getStormModel();
					Rect rect = getScreenArea(m->GetBoundingBox(), game);

					if(window->setRect(item, rect.x, rect.y, rect.w, rect.h, ( distance / updateDistance ), item->getHighlightStyle()))
					{
						if(item->hasHighlightText())
							window->setText(item, item->getHighlightText());
					}

					if( false ) // items cant have health thus they cant have the health bar
						window->setSliderValue( item, 1.0f, 1.0f );
				}

				/*
				if( window->setRect( (*it), tmp.x - 12, tmp.y - 8, 35, 35, (int)( ( distance / updateDistance ) * 100.0f ), (*it)->getStyle() ) )
				{
					if( (*it)->hasStyleText() )
						window->setText( (*it), (*it)->getStyleText() );	
				}
				*/
			}
		}
	}

	{
		float updateDistance = unitDistance * unitDistance;

		std::list< Unit* >::iterator it;
		for( it = unitsToBeUpdated.begin(); it != unitsToBeUpdated.end(); ++it )
		{
			//point tmp = convertVC3toScreen( (*it)->getPosition(), game );
			float distance = calculateDistance( (*it)->getPosition(), game );
			if( distance < updateDistance )
			{
				Unit *unit = *it;
				if(unit && unit->getVisualObject() && unit->getVisualObject()->getStormModel())
				{				
					UnitType *ut = unit->getUnitType();

					IStorm3D_Model *m = unit->getVisualObject()->getStormModel();
					Rect rect;

					// two rects, one for highlight and another for target lock rect
					for(int i = 0; i < 2; i++)
					{
						void *p = unit;
						int style = unit->getHighlightStyle();
						float rect_scale = 1.0f;
						const char *text = NULL;
						
						// target lock rect
						if(i == 1)
						{
							int max = unit->getTargetLockCounterMax();
							if(unit->getTargetLockCounter() <= 0)
							{
								// no target lock
								continue;
							}
							else if(unit->getTargetLockCounter() < max)
							{
								style = 5;
								rect_scale = 2.0f - 1.0f * (unit->getTargetLockCounter() / (float) max);
								text = NULL;
							}
							else
							{
								style = 6;
								rect_scale = 1.0f;
								text = "gui_target_locked";
							}

							p = ((char *)unit) + 2;
						}

						const TargetDisplayButtonManager::ButtonCreator &bc = window->getManager()->getButtonStyle( style );
						if(bc.rect_style == 0)
						{
							rect = getScreenArea(m->GetBoundingBox(), game);
						}
						else if(bc.rect_style == 1)
						{
							// unit size based rect
							//
							IStorm3D_Scene *scene = game->getGameScene()->getStormScene();
							IStorm3D_Camera *cam = scene->GetCamera();

							VC3 pos = m->GetPosition() + VC3(0, ut->getSize() * ut->getTargetRectHeightScale(), 0);
							VC3 pos_screen = VC3(0,0,0);
							VC3 pos_screen2 = VC3(0,0,0);
							float rhw = 0;
							float real_z = 0;
							bool visible = cam->GetTransformedToScreen(pos, pos_screen, rhw, real_z); 
							if(!visible)
								continue;

							pos += cam->GetUpVecReal() * ut->getSize() * 0.5f;
							visible = cam->GetTransformedToScreen(pos, pos_screen2, rhw, real_z); 
							if(!visible)
								continue;

							VC3 diff = pos_screen - pos_screen2;
							float radius = rect_scale * ut->getTargetRectScale() * sqrtf(diff.x * diff.x + diff.y * diff.y);

							pos_screen.x *= 1024.0f;
							pos_screen.y *= 768.0f;

							rect.x = (int)(pos_screen.x - radius * 1024.0f);
							rect.y = (int)(pos_screen.y - radius * 768.0f);
							rect.w = (int)(radius * 1024.0f * 2.0f);
							rect.h = (int)(radius * 768.0f * 2.0f);
						}

						if(window->setRect(p, rect.x, rect.y, rect.w, rect.h, ( distance / updateDistance ), style ))
						{
							if(unit->hasHighlightText() )
								window->setText(p, unit->getHighlightText() );	
							if(text)
								window->setText(p, text );	

						}

						window->setSliderValue(p, ( (float)unit->getHP() / (float)unit->getMaxHP() ), unit->getUnitType()->getHealthSliderScale() );
					}

				}
			}
		}
	}
	
	{
		float updateDistance = itemDistance * itemDistance;

		std::list< Unit* >::iterator it;
		for( it = risingMessages.begin(); it != risingMessages.end(); )
		{
			Unit *unit = *it;
			float distance = calculateDistance( unit->getPosition(), game );
			if(unit && unit->getVisualObject() && unit->getVisualObject()->getStormModel()
				&& distance < updateDistance)
			{
				IStorm3D_Model *m = unit->getVisualObject()->getStormModel();
				Rect rect = getScreenArea(m->GetBoundingBox(), game);

				// hack: allow rising messages on units with highlight
				void *p = ((char *)unit) + 1;
				if(window->setRect(p, rect.x, rect.y, rect.w, rect.h, ( distance / updateDistance ), risingMessageStyle ))
				{
					/*if(unit->hasHighlightText() )
						window->setText(p, unit->getHighlightText() );	
						*/
				}
			}
			else
			{
				// keep rising message visible even if unit was blown up
				// hack: allow rising messages on units with highlight
				void *p = ((char *)unit) + 1;
				window->updateRect(p);
			}

			// hack: allow rising messages on units with highlight
			void *p = ((char *)(*it)) + 1;
			if( window->hasEnded( p ) == false )
			{
				++it;
			}
			else
			{
				std::list< Unit* >::iterator remove = it;
				++it;
				risingMessages.erase( remove );
			}
		}
		
	}

	
	currentFrame++;

	if( currentFrame >= removeUnnessary )
	{
		currentFrame = 0;
		window->removeRest();
	}
	else
	{
		window->hideRest();
	}

	if( currentFrame%updateTargets == 0 )
		updateUpdatables();



}
Example #24
0
void Data::setLocalCoordinateSystem(Polygon* polygon, double delta)
{
    std::cout << "Polygon added, starting creation of local coordinate system, and initializes the polygon" << std::endl;

    //polygon.get..
    //calculate max min lat long
    minLat = std::numeric_limits<double>::max();
    maxLat = std::numeric_limits<double>::min();
    dLat = 1;

    minLon = std::numeric_limits<double>::max();
    maxLon = std::numeric_limits<double>::min();
    dLon = 1;


    std::vector<double> *latitude = polygon->getLatBoundaries();
    for(int i=0; i < latitude->size();i++)
    {
      double d = (*latitude)[i];
      if(d<minLat)
	       minLat = d;
      if(d>maxLat)
	       maxLat = d;
    }
    dLat = maxLat-minLat;

    std::vector<double> *longitude = polygon->getLonBoundaries();
    for(int i=0; i < longitude->size();i++)
    {
      double d = (*longitude)[i];
      if(d<minLon)
	       minLon = d;
      if(d>maxLon)
	       maxLon = d;
    }
    dLon = maxLon-minLon;

    dx = calculateDistance(minLat,minLon,minLat,maxLon);

    dy = calculateDistance(minLat,minLon,maxLat,minLon);

    std::cout << "minLat : " << minLat << std::endl;
    std::cout << "maxLat : " << maxLat << std::endl;
    std::cout << "dLat : " << dLat << std::endl;
    std::cout << "minLon : " << minLon << std::endl;
    std::cout << "maxLon : " << maxLon << std::endl;
    std::cout << "dLon : " << dLon << std::endl;
    std::cout << "dx: " << dx << std::endl;
    std::cout << "dy: " << dy << std::endl;


    localEnabled = true;

    boat_xpos = lonTOx(boat_longitude);
    boat_ypos = latTOy(boat_latitude);

    //calculate the polygon points in local coordinates
    std::vector<double>* localX = new std::vector<double>(); //TODO delete
    std::vector<double>* localY = new std::vector<double>();

    for(int i=0;i<latitude->size();i++)
    {
      localX->push_back(lonTOx((*longitude)[i]));
      localY->push_back(latTOy((*latitude)[i]));
    }


    std::cout << "Polygon in local coordinates" << std::endl;

    for(int i=0;i<localX->size();i++)
    {
      std::cout << "(" << (*localX)[i] << "," << (*localY)[i] << ")" << std::endl;
    }

    polygon->setLocalBoundaries(localX,localY);
    polygon->setGridSize(delta);
    polygon->initialize();


}
Example #25
0
int main(int argc, char *argv[]) {
  char row, tmp;
  int col, knight = 0, i;

  FILE *fin = fopen("camelot.in", "r");
  FILE *fout = fopen("camelot.out", "w");
  assert(fin); assert(fout);

  /* 初始化 */
  initBoard(board, -1);
  initBoard(currentBoard, 31*27);
  initBoard(takeKingBoard, -1);
  initBoard(currentTakeKingBoard, 31*27);
  head = tail = 0;

  /* 输入 */
  fscanf(fin, "%d %d\n", &cols, &rows);
  fscanf(fin, "%c %d%c", &kRow, &kCol, &tmp);
#ifdef debug
  printf("read King: %c %d\n", kRow, kCol);
#endif
  // tmp 可能获取的值为空格或换行,这里只是为了不影响之后的数据而存在的
  while(fscanf(fin, "%c %d%c", &row, &col, &tmp) != EOF) {
    knight += 1;
#ifdef debug
    printf("read: %c %d\n", row, col);
#endif
    // 根据当前输入的“马”初始化
    currentBoard[row - 'A'][col-1] = 0;
    currentTakeKingBoard[row - 'A'][col - 1] = max(abs(kRow - row), abs(kCol - col));

    // 更新 currentBoard 和 currentTakeKingBoard 数组
    calculateDistance(row - 'A', col - 1, currentTakeKingBoard[row-'A'][col-1]);
    updateBoard();
#ifdef debug
    printf("currentTakeKingBoard:\n");
    printBoard(currentTakeKingBoard);
    printf("currentBoard:\n");
    printBoard(currentBoard);
    printf("after updating, takeKingBoard:\n");
    printBoard(takeKingBoard);
    printf("board:\n");
    printBoard(board);
#endif

    initBoard(currentBoard,31*27);
    initBoard(currentTakeKingBoard,31*27);
  }

  /* 计算输出 */
  if (knight == 0) {
    printf("0\n");
    fprintf(fout, "0\n");
  } else {
    fprintf(fout, "%d\n", result());
    printf("%d\n", result());
  }

  fclose(fin); fclose(fout);
  return 0;
}
Example #26
0
void moveZombie(Entity z){
	int r = rand()%4;
	Position p = z->position;

	Entity target = NULL;
	for(signed int x = ( (signed int) p.x ) - 5; x <= ( (signed int) p.x ) + 5; x++) {
		if(x < 0 || x >= GRID_WIDTH) {
			continue;
		}
		for(signed int y = ( (signed int) p.y ) - 5; y <= ( (signed int) p.y ) + 5; y++) {
			if(y < 0 || y >=  GRID_HEIGHT) {
				continue;
			}

			Entity e = getEntityAt((Position) { (unsigned int) x, (unsigned int) y });
			if(e && e->type == ET_SURVIVOR) {
				if(target) {
					Position o = getPosition(target);
					Position u = getPosition(e);

					if(calculateDistance(p, u) < calculateDistance(p, o)) {
						target = e;
					}
				}
				else {
					target = e;
				}
			}
		}
	}
	if(target) {
		Position o = getPosition(target);
		if(calculateDistance(p, o) == 1) {
			// Attack
			target->remainingHealth--;
			if(target->remainingHealth == 0) {
				// Convert the heretics
				NumSurvivors--;
				score -= 3;
				target->type = ET_ZOMBIE;
			}
		}
		else if(o.y < p.y) {
			p.y--;
		}
		else if(o.y > p.y) {
			p.y++;
		}
		else if(o.x < p.x) {
			p.x--;
		}
		else if(o.x > p.x) {
			p.x++;
		}
	}
	else {
		if(r == 0){
			p.x--;
		}
		else if(r==1){
			p.y++;
		}
		else if(r==2){
			p.x++;
		}
		else{
			p.y--;
		}


		if(p.x >= GRID_WIDTH){
			p.x = z->position.x;;
		}

		if(p.y >= GRID_HEIGHT){
			p.y = z->position.y;
		}
	}

	if(z->position.x != p.x || z->position.y != p.y) {
		move(z,p);
	}
}
Example #27
0
int main(void)
{
	setup();
	
	// Play the three beep tones at the beginning to memorize them.
	beep(1, OC_BEEP_FIVE, BEEP_LENGTH, 0);
	beep(1, OC_BEEP_ONE, BEEP_LENGTH, 0);
	beep(1, OC_BEEP_TENTHS, BEEP_LENGTH, 0);
	
	// Wait until the button is not pressed
	while(!(PINB & _BV(BTN)))
	{ }
	
	while(1)
	{
		// Enable INT0 interrupt at low level (ISC00 & ISC01 @ MCUCR = 0) to wake up after
		// we have entered sleep mode.
		GIMSK |= _BV(INT0);
		set_sleep_mode(SLEEP_MODE_PWR_DOWN);
		sleep_mode();

		// Start the logic as soon as the button pin goes low
		if (!(PINB & _BV(BTN)))
		{
			start_timer();
			
			// Do nothing while the button is pressed...
			while(!(PINB & _BV(BTN)))
			{ }
			
			// Wait until 0.2 seconds have passed since button release (poor man's debouncing)
			_delay_ms(200);
			
			// Wait until the button is pressed again
			while(PINB & _BV(BTN))
			{ }
			
			stop_timer();
			
			// Wait until the button is not pressed
			while(!(PINB & _BV(BTN)))
			{ }
			
			uint16_t fiveKilometers = 0;
			uint8_t kilometers = 0;
			uint8_t tenthKilometers = 0;
			
			calculateDistance(&fiveKilometers, &kilometers, &tenthKilometers);
			
			if (fiveKilometers > 0)
			{
				beep(fiveKilometers, OC_BEEP_FIVE, BEEP_LENGTH, BEEP_DELAY);
				_delay_ms(BEEP_MAG_DELAY);
			}
			
			if (kilometers > 0)
			{
				beep(kilometers, OC_BEEP_ONE, BEEP_LENGTH, BEEP_DELAY);
				_delay_ms(BEEP_MAG_DELAY);
			}
			
			if (tenthKilometers > 0)
				beep(tenthKilometers, OC_BEEP_TENTHS, BEEP_LENGTH, BEEP_DELAY);
		}
	}
	
	return 0;
}
Example #28
0
/**
 * Calculate the distance from point1 to point2 by using the Pythagorean theorem.
 * @param point1 The first point.
 * @param point2 The second point.
 * @return The calculated distance.
 */
float math::calculateDistance(Point point1, Point point2)
{
    return calculateDistance(point1.getX(), point1.getY(), point2.getX(), point2.getY());
}