Пример #1
0
int main()
{
    srand((unsigned)time(NULL));

    int i, j, k, l, varw, varc1, varc2, vfun=3, vtest, vgen, temp; // iteration vars
    float w, c1, c2, edge, Vmax, goal, gb, res = 0, avggennew=0;  // gb is the global gbest
    float vel[coornum], pbest[coornum], gbest[coornum], results[4*testnum]; // Each bird's got their own gbest
    float absRadius; // Absolute perceptive radius
    float relRadius; // A iteration var for radius
    int radRec; // A var to count the index of the radius
    int adjmat[N][N]; // Adjacent Matrix

    char buffer[19]; // A buffer to write the file, 15 is the estimated char numbers
    char storage[19*relRange];


    /* Storage Section */
//The strategy is: we store the 'sum' into 'aves'.
//When the time comes they got loaded into the file, we'll have them become real 'average'

    float AveOptGen[relRange];  // FuncNumber*RadiusNumber: Every 19[radius] with a func
    float AveOptRate[relRange];  // FuncNumber*RadiusNumber: Every 19[radius] with a func
    float AveDeg[relRange][gennum/aveDegInterval+1];  // [FuncNumber*RadiusNumber][Every 10 gen]
                                            //So the truth is, we're getting the average(a matrix) of average(a test)
    float AveOptFit[relRange][gennum/aveDegInterval+1]; // The average of the gbest fitness in the end of each test (last generation)
    /* End of Storage Section */


    for(i=0;i<relRange;i++){
        AveOptGen[i]=0;
        AveOptRate[i]=0;
        for(j=0;j<gennum/aveDegInterval;j++){
            AveDeg[i][j]=0;
            AveOptFit[i][j]=0;
        }

    }

    for(i=0;i<19*relRange;i++){
        storage[i]=' ';
    }


    radRec=0; // Set the radius index counting number

for(relRadius=0.24;relRadius<1.01;relRadius+=0.02){ // Loop layer 1 (relRadius)

    w = 0.6;
    for(varw = 0; varw < 1; varw++)
    {
        c1 = 1.7;
        for(varc1 = 0; varc1 < 1; varc1++)
        {
            c2 = 1.7;
            for(varc2 = 0; varc2 < 1 ; varc2++)
            {


                        edge = 5.12;
                        Vmax = edge;
                        goal = 100;

                    int ngoal = 0, avggen = 0; // Goal achieving flag & Average generations

                    for(i = 0; i < testnum; i++)
                    {
                        results[4*i] = gennum;
                        results[4*i+1] = 0;
                        results[4*i+2] = gennum;
                        results[4*i+3] = 0;
                    }


                    for(vtest = 0; vtest < testnum; vtest++)  // Run the experiment
                    {
                        double neoDiag=0;
                        double dist=0;
                        int sum = 1;

                        absRadius = relRadius * sqrt(dim * pow(2 * edge , 2));

                        for(i = 0; i < coornum; i++)
                        {
                            pbest[i] = INT_MAX;
                            gbest[i] = INT_MAX;
                        }

                        //Initialization:

                        for(i = 0; i < dim + 1; i++)
                        {
                            for(j = 0; j < N; j++)
                            {
                                if(i < dim)
                                {
                                    coor[(dim+1)*j+i] = (double)rand() / RAND_MAX *  2 * edge - edge;
                                    vel[(dim+1)*j+i] = (double)rand() / RAND_MAX * 2 * Vmax - Vmax;
                                    pbest[(dim+1)*j+i] = coor[(dim+1)*j+i];
                                    gbest[(dim+1)*j+i] = coor[(dim+1)*j+i];

                                }
                                else
                                { // i=dim

                                        Func(j);
                                    // Initializing pbest
                                    pbest[(dim+1)*j+i] = coor[(dim+1)*j+i];
                                    gbest[(dim+1)*j+i] = coor[(dim+1)*j+i];
                                    /*
                                    if(coor[(dim+1)*j+i] < gbest[(dim+1)*j+i])
                                    {
                                        for(l = 0; l < dim + 1; l++)
                                            gbest[(dim+1)*j+l] = coor[(dim+1)*j+l];

                                    }
                                    for(k = 0; k < N; k++)
                                        if( gbest[(dim+1)*j+i] < gbest[(dim+1)*k+i])
                                        {

                                            for(l = 0; l < dim + 1; l++)
                                                gbest[(dim+1)*k+l] = gbest[(dim+1)*j+l];
                                        }
                                    */
                                } // End of the condition i = dim
                            } // for birds



                        } // for dims

                        //neoDiag=0;
                        // Producing the initiating Adjacent Matrix
                        for(j=0;j<N;j++)
                            for(k=0;k<N;k++) // Avoid Relapse
                            {
                                dist=getDistance(j,k);
                                if( dist <= absRadius && j!=k ) // k Can be perceived by j
                                    {
                                        adjmat[j][k]=1;
                                    }
                                else{
                                    adjmat[j][k]=0;
                                }
                               /* if(dist>neoDiag){
                                    printf("%d,%d,%f\n",j,k,dist);
                                    neoDiag=dist;
                                }
                                */

                            }
                        // End of producing the initiating Adjacent Matrix

                        for( j=0; j<N ; j++ )
                                for( k=0; k<N ; k++ )
                                    if( adjmat[j][k] != 0) // k Can be perceived by j
                                        temp+=1;
                        temp/=N;
                        AveDeg[radRec][0]+=temp; // Got it

                        // Updating each bird's gbest:
                        for(j=0;j<N;j++){
                             for(k=0;k<N;k++)
                                if( adjmat[j][k] != 0 ){// k Can be perceived by j
                                        // Updating the gbest of j
                                        //printf("%f\t",getDistance(j,k));
                                        if( coor[(dim+1)*k+dim] < gbest[(dim+1)*j+dim] ){
                                            for(l=0;l<=dim;l++)
                                                gbest[(dim+1)*j+l] = coor[(dim+1)*k+l];
                                    }
                                }
                                //printf("gbest of %d:%f\nfitness of %d:%f\n",j,gbest[(dim+1)*j+dim],j,coor[(dim+1)*j+dim]);
                        }

                        gb = gbest[dim]; // Updating the global gbest
                        for(i = 1; i < N; i++)
                            if(gbest[(dim+1)*i+dim] < gb)
                                gb = gbest[(dim+1)*i+dim];
                        AveOptFit[radRec][0]+=gb;

                        // End of Updating each bird's gbest in initialization


                        for(vgen = 0; vgen < gennum; vgen++)         // Evolution
                        {
                            float aveDegree=0; // Average Degree


                            for(i = 0; i < dim + 1; i++)
                            {
                                for(j = 0; j < N; j++)
                                {
                                    if(i < dim)
                                    {
                                        float r1 = (double)rand() / RAND_MAX * 1;
                                        float r2 = (double)rand() / RAND_MAX * 1;
                                        vel[(dim+1)*j+i] = w * vel[(dim+1)*j+i] + c1 * r1 * (pbest[(dim+1)*j+i] - coor[(dim+1)*j+i])\
                                                           + c2 * r2 * (gbest[(dim+1)*j+i] - coor[(dim+1)*j+i]);

                                        coor[(dim+1)*j+i] += vel[(dim+1)*j+i];

                                    }
                                    else  // i = dim
                                    {

                                            Func(j);
                                        // When i = dim, updating pbest:
                                        if(coor[(dim+1)*j+i] < pbest[(dim+1)*j+i])
                                            for(l = 0; l < dim + 1; l++)
                                                pbest[(dim+1)*j+l] = coor[(dim+1)*j+l];

                                         // Comparing itself with gbest:
                                        if(coor[(dim+1)*j+i] < gbest[(dim+1)*j+i])
                                            for(l = 0; l < dim + 1; l++)
                                                gbest[(dim+1)*j+l] = coor[(dim+1)*j+l];


                                    } // End of else
                                } // for birds
                            } // for dims

                            if( (vgen+1) % (50*aveDegInterval) == 0 && vgen!=0)
                            {
                                //printf("%d,%f\n",vgen,neoDiag);
                                absRadius=relRadius*neoDiag;
                            }

                            neoDiag=0;

                            // Producing the initiating Adjacent Matrix
                            for( j=0; j<N ; j++ )
                                for( k=0; k<N; k++) // Avoid Relapse
                                    {
                                        dist=getDistance(j,k);
                                        if( dist <= absRadius && j!=k ) // k Can be perceived by j
                                        {
                                            adjmat[j][k]=1;
                                        }
                                        else{
                                                adjmat[j][k]=0;
                                        }

                                        if( (vgen+1) % (50*aveDegInterval) == 499 )
                                            neoDiag+=dist;

                                    }
                            neoDiag/=N*(N-1);
                                    //if(neoDiag!=0)
                                    //printf("%d,%f\n",vgen,neoDiag);
                            // End of producing the initiating Adjacent Matrix

                            //Caculating Average Degree of the generation
                            if( (vgen+1) % aveDegInterval == 0 ){
                                for( j=0; j<N ;j++ )
                                    for( k=0; k<N ;k++ )
                                        if( adjmat[j][k] != 0) // k Can be perceived by j
                                            aveDegree+=1;
                                aveDegree/=N; // Got it
                                AveDeg[radRec][(vgen+1) / aveDegInterval] += aveDegree; // Storing Average Degree of this particular generation
                            }


                            // Updating each bird's gbest:
                            for( j=0; j<N ;j++ ){
                                for( k=0; k<N ;k++ )
                                    if( adjmat[j][k] != 0 ) // k Can be perceived by j
                                        // Updating the gbest of j
                                        if( coor[(dim+1)*k+dim] < gbest[(dim+1)*j+dim] )
                                            for(l=0;l<=dim;l++)
                                                gbest[(dim+1)*j+l] = coor[(dim+1)*k+l];
                                //printf("gbest of %d:%f\nfitness of %d:%f\n",j,gbest[(dim+1)*j+dim],j,coor[(dim+1)*j+dim]);
                            }
                            // End of Updating each bird's gbest

                            gb = gbest[dim]; // Updating the global gbest
                            for(i = 1; i < N; i++)
                                if(gbest[(dim+1)*i+dim] < gb)
                                    gb = gbest[(dim+1)*i+dim];

                                if( (vgen+1) % aveDegInterval == 0 ){
                                AveOptFit[radRec][(vgen+1) / aveDegInterval]+=gb;
                            }

                            if(gb < goal && sum != 0)
                            {
                                results[4*vtest] = (double)vgen+1;
                                results[4*vtest+1] = gb;
                                sum = 0;
                                printf("\ngb:%f,%d\t",gb,vgen);
                                //ngoal++;
                                //break;
                            }
                            if(vgen == gennum - 1)
                            {
                                results[4*vtest+2] = gennum;
                                results[4*vtest+3] = gb;
                                 printf("lastgb:%f\n",gb);
                            }


                        } // for vgens


                        printf("\nTest%d for Function%d of relRadius%f is done. The next one's coming at ya.\n\n",vtest,vfun,relRadius);

                    } // for vtest

                    for(i = 0; i < testnum; i++)
                    {
                        if(results[4*i] != gennum)
                        {
                            ngoal++;
                            avggen += results[4*i];
                            res += results[4*i+1];
                        }
                    }
                    printf("%d,%d", avggen, ngoal);
                    if(ngoal == 0)
                        avggennew = (double)gennum;
                    else
                        avggennew = (double)avggen / ngoal;

                    printf("AVGEN:%f\t",avggennew);
                    AveOptGen[radRec]=avggennew;
                    printf("AVRATE:%f",(double)ngoal / testnum * 100);
                    AveOptRate[radRec]=(double)ngoal / testnum * 100;

                    printf("Function%d is tested under this radius.\n", vfun);

                c2 += 0.1;
            }
            c1 += 0.1;
        }
        w += 0.1;
    }
//} // End of Loop layer 2 (population)

    radRec++;

    printf("\n\nRadius %d is tested\n\n",radRec);

} // End of Loop layer 1 (relRadius)
    printf("\n\n Done! You got it, dude!");

    for(i=0;i<relRange;i++)
        for(j=0;j<=(gennum/aveDegInterval);j++){
            AveDeg[i][j]=(double)AveDeg[i][j]/testnum;
            AveOptFit[i][j]=(double)AveOptFit[i][j]/testnum;
        }

// Get da data in da file!
    sprintf(storage,"Gen,");
    for(i=0;i<relRange;i++){
        sprintf(buffer,"AvDeg%d,",i);
        strcat(storage,buffer);
    }


    pso = fopen("vicpsoFunc3-adjmat.txt", "w");
    fprintf(pso, "RelRadius,AveOptGen,AveOptRate,AveDeg\n");
    for(i=0;i<relRange;i++){
        fprintf(pso, "%f,%f,%f\n",0.24+i*0.02,AveOptGen[i],AveOptRate[i]);
    }
    fclose(pso);

    pso = fopen("vicpsoFunc3-adjmat-AveDeg.txt", "w");
    fprintf(pso, "%s\n",storage );
        for(j=0;j<=(gennum/aveDegInterval);j++){
            int inIte;
            fprintf(pso,"%d,",j*10);
            for(inIte=0;inIte<relRange;inIte++){
                fprintf(pso, "%f,",AveDeg[inIte][j]);
            }
            fprintf(pso, "\n");
        }


    fclose(pso);

    pso = fopen("vicpsoFunc3-OptFit.txt", "w");
    fprintf(pso, "%s\n",storage );

        for(j=0;j<=(gennum/aveDegInterval);j++){
            int inIte;
            fprintf(pso,"%d,",j*10);
            for(inIte=0;inIte<relRange;inIte++){
                fprintf(pso, "%f,",AveOptFit[inIte][j]);
            }
            fprintf(pso, "\n");
        }
    fclose(pso);

    return 0;

} // End of main
Пример #2
0
void bimWorld::CameraManipulator::switchMatrixManipulator(ManipulatorType emanip)
{
	auto viewer = m_host->_ViewerData()->ModelViewer();
	auto sceneRoot = m_host->_ViewerData()->getSceneRoot();
	auto modelRoot = m_host->_ViewerData()->getModelRoot();
	if (!viewer || !sceneRoot || !modelRoot)
	{
		return;
	}
	m_host->_RenderingThreads()->setIsExternalRendering(true);
	auto manip = viewer->getCameraManipulator();
	osg::Vec3d eye, center, up;
	auto matrix = manip->getMatrix();
	manip->getHomePosition(eye, center, up);
	switch (emanip)
	{
	case ManipulatorType::Default:
		sceneRoot->getOrCreateStateSet()->setMode(GL_LIGHT0,
			osg::StateAttribute::ON);
		sceneRoot->getOrCreateStateSet()->setMode(GL_LIGHT1,
			osg::StateAttribute::ON);
		sceneRoot->getOrCreateStateSet()->setMode(GL_LIGHT2,
			osg::StateAttribute::OFF);
		sceneRoot->getOrCreateStateSet()->setMode(GL_LIGHT3,
			osg::StateAttribute::OFF);
		sceneRoot->getOrCreateStateSet()->setMode(GL_LIGHT4,
			osg::StateAttribute::OFF);
		((BIMCameraManipulator*)m_d.get())->setPosition(eye, center, up, matrix);

		////                BIMCameraManipulator* mat = (BIMCameraManipulator*)(m_d.get());
		//                 ((BIMCameraManipulator*)m_d.get())->beginSetCameraMatrix();
		//                ((BIMCameraM-anipulator*)m_d.get())->setByMatrix(matrix);
		//               ((BIMCameraManipulator*)m_d.get())->endSetCameraMatrix();
		viewer->setCameraManipulator(((BIMCameraManipulator*)m_d.get()), false);
		break;
	case ManipulatorType::Person:
	{
		auto oldManip = static_cast<BIMCameraManipulator*>(manip);
		if (!oldManip)
			break;
		auto rotation = oldManip->getRotation();
		auto dist = oldManip->getDistance();
		auto personManip = static_cast<PersonManipulator*>(m_p.get());
		if (!personManip)
			break;
		personManip->setScreenRotation(rotation);
		personManip->setScreenDistance(dist);
		personManip->setPosition(eye, center, up, matrix);
		viewer->setCameraManipulator(personManip, false);
		break;
	}
	case ManipulatorType::FirstPerson:
	{
		sceneRoot->getOrCreateStateSet()->setMode(GL_LIGHT0,
			osg::StateAttribute::OFF);
		sceneRoot->getOrCreateStateSet()->setMode(GL_LIGHT1,
			osg::StateAttribute::OFF);
		sceneRoot->getOrCreateStateSet()->setMode(GL_LIGHT2,
			osg::StateAttribute::ON);
		sceneRoot->getOrCreateStateSet()->setMode(GL_LIGHT3,
			osg::StateAttribute::ON);
		sceneRoot->getOrCreateStateSet()->setMode(GL_LIGHT4,
			osg::StateAttribute::ON);

		osgGA::CameraManipulator* first = new BIMFirstPersonManipulator(m_host);
		viewer->setCameraManipulator(first, true);

		first->setHomePosition(modelRoot->getBound().center(), osg::Vec3(0, 0, 0), up);
		viewer->home();
		break;
	}
	}
	m_host->_RenderingThreads()->setIsExternalRendering(false);

	return;

	//		osgGA::KeySwitchMatrixManipulator *switchmanipulator = dynamic_cast<osgGA::KeySwitchMatrixManipulator*>(m_mViewer->getCameraManipulator());
	//
	//		//m_ptrKeySwitchMatrixManipulator=new osgGA::KeySwitchMatrixManipulator;
	//		//m_ptrKeySwitchMatrixManipulator->addMatrixManipulator(1,"deflaut",createCameraManipulator());
	//		//m_ptrKeySwitchMatrixManipulator->addMatrixManipulator(2,"person",createPersonManipulator());
	//		switchmanipulator->selectMatrixManipulator((int)emanip);
	//		if (emanip == deflaut)
	//		{
	//			BIMCameraManipulator* manipulator = dynamic_cast<BIMCameraManipulator*>(switchmanipulator->getCurrentMatrixManipulator());
	//
	//			zoomTo(m_modelRoot);
	//			//if (manipulator)
	//			//{
	//			//	manipulator->setupFrameRateController(m_modelRoot.get());
	//			//	manipulator->setModelRoot(m_modelRoot);
	//			//}
	//		}
	//		else if (emanip == person)
	//		{
	//			PersonManipulator* manipulator = dynamic_cast<PersonManipulator*>(switchmanipulator->getCurrentMatrixManipulator());
	//			zoomTo(m_modelRoot);
	//			//if (manipulator)
	//			//{
	//			//	manipulator->setupFrameRateController(m_modelRoot.get());
	//			//	manipulator->setModelRoot(m_modelRoot);
	//			//}
	//		}

	m_host->_RenderingThreads()->updateSeveralTimes(1);
}
void HelloWorld::setTouchEvent(){
    //touch 控制精灵
    auto *testSprite = this->createTestSpriteWithFormat("player1_%i_%i.png");
    
    testSprite->runAction(RepeatForever::create(Blink::create(0.5, 3)));
    
    Size winSize = Director::getInstance()->getWinSize();
    
    _mapLayer->addChild(testSprite, 200);
    
    Point mapPosition = Point(winSize.width * 0.5f - testSprite->getPosition().x , winSize.height * 0.5f - testSprite->getPosition().y);
    
    _mapLayer->setPosition(mapPosition);//移动到玩家的位置
    this->adjustMapLayer(false);
    
    //触摸
    auto dispatcher = Director::getInstance()->getEventDispatcher();
    auto myListener = EventListenerTouchOneByOne::create();
    
    //如果不加入此句消息依旧会向下传递
    myListener->setSwallowTouches(true);
    
    //-----touch began-----
    myListener->onTouchBegan = [=](Touch* touch,Event* event)
    {
        
        _bIsMove = false;
        return true;
    };
    
    //-----touch moved-----
    myListener->onTouchMoved = [=](Touch* touch,Event* event)
    {
        auto touchPoint = _mapLayer->convertToNodeSpace(touch->getLocation()); ;
        auto firstTouchPoint = _mapLayer->convertToNodeSpace(touch->getStartLocation());
        
        if (touchPoint.getDistance(firstTouchPoint) > 5){
            _bIsMove = true;
            
        }else{
            
        }
        
        if (_bIsMove) {
            auto preTouchPoint = _mapLayer->convertToNodeSpace(touch->getPreviousLocation());
            auto position  = _mapLayer->getPosition();
            _mapLayer->setPosition(Point(position.x + touchPoint.x - preTouchPoint.x, position.y + touchPoint.y - preTouchPoint.y));
        }
    };
    
    //-----touch ended-----
    myListener->onTouchEnded = [=](Touch* touch,Event* event)
    {
        
        auto touchPoint = _mapLayer->convertToNodeSpace(touch->getLocation()); ;
        
        if (!_bIsMove) {
            //根据点击坐标转换成mapId
            auto mapId = this->_mapInfo->convertPointToId(touchPoint);
            
            auto position = testSprite->getPosition();
            auto originId = _mapInfo->convertPointToId(position);
            
            //生成路径
            auto* pMapPath = _mapInfo->getMapPath(originId, mapId);
            
            if (pMapPath != nullptr)
            {
                auto *pointArr1 = pMapPath->getPointArr();
                
                auto duration = 0.2 * pointArr1->count();
                
                auto *easeWalkTo1 = EaseWalkTo::create(duration, pointArr1);
                easeWalkTo1->setTag(99);
                testSprite->stopActionByTag(99);
                testSprite->runAction(easeWalkTo1);
                
            }
        }else{
            
        }
        
        //触摸结束后自动调整地图防止越界
        this->adjustMapLayer(true);
        
    };
    
    //监听事件
    dispatcher->addEventListenerWithSceneGraphPriority(myListener, this);
 
}
Пример #4
0
//----------------------------------------
void ofEasyFingerCam::begin(ofRectangle viewport)
{
    glEnable(GL_DEPTH_TEST);
    viewportRect = viewport;
    ofCamera::begin(viewport);
    ofPushMatrix();
    glGetDoublev(GL_PROJECTION_MATRIX, this->matP);
    glGetDoublev(GL_MODELVIEW_MATRIX, this->matM);
    glGetIntegerv(GL_VIEWPORT, this->viewport);
    bool hasTweens = false;
    if(rTweens.size()>0)
    {
        hasTweens = true;
        setAnglesFromOrientation();
        targetXRot = rTweens[0]->x;
        targetYRot = rTweens[0]->y;
        targetZRot = rTweens[0]->z;
        updateRotation();
        if(targetXRot - rotationX <1 && targetXRot - rotationX >-1 &&
           targetYRot - rotationY <1 && targetYRot - rotationY >-1 &&
           targetZRot - rotationZ <1 && targetZRot - rotationZ >-1)
        {
            rTweens.erase(rTweens.begin());
        }
        setAnglesFromOrientation();
    }
    if(sTweens.size()>0)
    {
        hasTweens = true;
        if(abs(sTweens.at(0)->scale - getDistance()) < 10)
        {
            float newvalue = (getDistance()-sTweens.at(0)->scale)*0.05/100;
            setDistance(getDistance()+newvalue);
        }
    }
    if(pTweens.size()>0)
    {
        hasTweens = true;
        if(target.getPosition().distance(pTweens.at(0)->pan) > 1)
        {
            ofVec3f newTranslation;
            newTranslation = pTweens.at(0)->pan - target.getPosition();
            translation = newTranslation/10;
            target.move(translation);
        }
        else
        {
            pTweens.erase(pTweens.begin());
        }
    }
    if(hasTweens)
    {
        currentState = TWEENING;
    }
    else
    {
        currentState = STABLE;
        if(bMouseInputEnabled||bFingerInputEnabled)
        {
            if(!bDistanceSet)
            {
                setDistance(getImagePlaneDistance(viewport), true);
            }
            if (fingers.size() > 0 )
            {
                // it's important to check whether we've already accounted for the mouse
                // just in case you use the camera multiple times in a single frame
                if (lastFrame != ofGetFrameNum())
                {
                    lastFrame = ofGetFrameNum();
                    currentState = STABLE;
                    if (fingers.size() == 1)
                    {
                        if(selectedPlane->axis == AxisPlane::NOAXIS)
                        {
                            currentState = ROTATING;
                            // if there is some smart way to use dt to scale the values drag, we should do it
                            // you can't simply multiply drag etc because the behavior is unstable at high framerates
                            // float dt = ofGetLastFrameTime();
                            ofVec2f mousePosScreen = ofVec3f(fingers[0]->getX()*ofGetWidth() - viewport.width/2 - viewport.x, viewport.height/2 - (fingers[0]->getY()*ofGetHeight() - viewport.y), 0);
                            ofVec2f mouseVelScreen = (mousePosScreen - mousePosScreenPrev).lengthSquared();
                            ofVec3f targetPos =  target.getGlobalPosition();
                            ofVec3f mousePosXYZ = ofVec3f(mousePosScreen.x, mousePosScreen.y, targetPos.z);
                            float sphereRadius = min(viewport.width, viewport.height)/2;
                            float diffSquared = sphereRadius * sphereRadius - (targetPos - mousePosXYZ).lengthSquared();
                            if(diffSquared <= 0)
                            {
                                mousePosXYZ.z = 0;
                            }
                            else
                            {
                                mousePosXYZ.z = sqrtf(diffSquared);
                            }
                            mousePosXYZ.z += targetPos.z;
                            ofVec3f mousePosView = ofMatrix4x4::getInverseOf(target.getGlobalTransformMatrix()) * mousePosXYZ;
                            //calc new rotation velocity
                            ofQuaternion newRotation;
                            if(fingerPressedPrev[0])
                            {
                                newRotation.makeRotate(mousePosViewPrev, mousePosView);
                            }
                            fingerPressedPrev[0] = true;
                            //apply drag towards new velocities
                            rotation.slerp(drag, rotation, newRotation); // TODO: add dt
                            mousePosViewPrev = ofMatrix4x4::getInverseOf(target.getGlobalTransformMatrix()) * mousePosXYZ;
                            // apply transforms if they're big enough
                            // TODO: these should be scaled by dt
                            if(translation.lengthSquared() > epsilonTransform)
                            {
                                // TODO: this isn't quite right, it needs to move wrt the rotation
                                target.move(translation);
                            }
                            if (rotation.asVec3().lengthSquared() > epsilonTransform)
                            {
                                target.rotate(rotation.conj());
                            }
                            if (abs(distanceScaleVelocity - 1.0f) > epsilonTransform)
                            {
                                setDistance(getDistance() * (1.0f + distanceScaleVelocity), false);
                            }
                            mousePosScreenPrev = mousePosScreen;
                            // targetFut.setPosition(target.getPosition());
                        }
                    }
                    if (fingers.size() == 2)
                    {
                        currentState = SCALING;
                        if(zooming)
                        {
                            ofVec2f pointa = ofVec2f(fingers[0]->getX()*ofGetWidth(),fingers[0]->getY()*ofGetHeight());
                            ofVec2f pointb = ofVec2f(fingers[1]->getX()*ofGetWidth(),fingers[1]->getY()*ofGetHeight());
                            float newDistance = pointa.distance(pointb);
                            float newDistanceScaleVelocity = 0.0f;
                            if(prevDistance == 0)
                            {
                                prevDistance = newDistance;
                            }
                            else
                            {
                                newDistanceScaleVelocity = zoomSpeed * ( prevDistance - newDistance) / ofVec2f(0,0).distance(ofVec2f(ofGetHeight(),ofGetWidth()));
                                distanceScaleVelocity = ofLerp(distanceScaleVelocity, newDistanceScaleVelocity, drag);
                                if (abs(distanceScaleVelocity - 1.0f) > epsilonTransform)
                                {
                                    setDistance(getDistance() * (1.0f + distanceScaleVelocity), false);
                                }
                                prevDistance = newDistance;
                            }
                        }
                    }
                    else
                    {
                        prevDistance = 0;
                    }
                    if (fingers.size() == 3)
                    {
                        currentState = POINTING;
                    }
                    if (fingers.size() == 5)
                    {
                        if(selectedPlane->axis == AxisPlane::NOAXIS)
                        {
                            currentState = PANNING;
                            //DECIDE LATER
                        }
                    }
                    if (fingers.size() == 10)
                    {
                        if(selectedPlane->axis == AxisPlane::NOAXIS)
                        {
                            currentState = RESET;
                            addPanningTween(ofVec3f(0,0,0));
                            addRotationTween(0, 0, 0, 1);
                        }
                    }
                }
            }
            else
            {
                //MOUSE
                fingerPressedPrev[0] = false;
                // it's important to check whether we've already accounted for the mouse
                // just in case you use the camera multiple times in a single frame
                if (lastFrame != ofGetFrameNum())
                {
                    lastFrame = ofGetFrameNum();
                    if(selectedPlane->axis == AxisPlane::NOAXIS)
                    {
                        // if there is some smart way to use dt to scale the values drag, we should do it
                        // you can't simply multiply drag etc because the behavior is unstable at high framerates
                        // float dt = ofGetLastFrameTime();
                        currentState = STABLE;
                        ofVec2f mousePosScreen = ofVec3f(ofGetMouseX() - viewport.width/2 - viewport.x, viewport.height/2 - (ofGetMouseY() - viewport.y), 0);
                        ofVec2f mouseVelScreen = (mousePosScreen - mousePosScreenPrev).lengthSquared();
                        ofVec3f targetPos =  target.getGlobalPosition();
                        ofVec3f mousePosXYZ = ofVec3f(mousePosScreen.x, mousePosScreen.y, targetPos.z);
                        float sphereRadius = min(viewport.width, viewport.height)/2;
                        float diffSquared = sphereRadius * sphereRadius - (targetPos - mousePosXYZ).lengthSquared();
                        if(diffSquared <= 0)
                        {
                            mousePosXYZ.z = 0;
                        }
                        else
                        {
                            mousePosXYZ.z = sqrtf(diffSquared);
                        }
                        mousePosXYZ.z += targetPos.z;
                        ofVec3f mousePosView = ofMatrix4x4::getInverseOf(target.getGlobalTransformMatrix()) * mousePosXYZ;
                        bool mousePressedCur[] = {ofGetMousePressed(0), ofGetMousePressed(2)};
                        //calc new rotation velocity
                        ofQuaternion newRotation;
                        if(mousePressedPrev[0] && mousePressedCur[0])
                        {
                            newRotation.makeRotate(mousePosViewPrev, mousePosView);
                        }
                        //calc new scale velocity
                        float newDistanceScaleVelocity = 0.0f;
                        if(mousePressedPrev[1] && mousePressedCur[1])
                        {
                            newDistanceScaleVelocity = zoomSpeed * (mousePosScreenPrev.y - mousePosScreen.y) / viewport.height;
                        }
                        mousePressedPrev[0] = mousePressedCur[0];
                        mousePressedPrev[1] = mousePressedCur[1];
                        ofVec3f newTranslation;
                        // TODO: this doesn't work at all. why not?
                        if(ofGetMousePressed() && ofGetKeyPressed(OF_KEY_SHIFT))
                        {
                            newTranslation = mousePosScreenPrev - mousePosScreen;
                        }
                        //apply drag towards new velocities
                        distanceScaleVelocity = ofLerp(distanceScaleVelocity, newDistanceScaleVelocity, drag); // TODO: add dt
                        rotation.slerp(drag, rotation, newRotation); // TODO: add dt
                        translation.interpolate(newTranslation, drag);
                        mousePosViewPrev = ofMatrix4x4::getInverseOf(target.getGlobalTransformMatrix()) * mousePosXYZ;
                        // apply transforms if they're big enough
                        // TODO: these should be scaled by dt
                        if(translation.lengthSquared() > epsilonTransform)
                        {
                            // TODO: this isn't quite right, it needs to move wrt the rotation
                            target.move(translation);
                        }
                        if (rotation.asVec3().lengthSquared() > epsilonTransform)
                        {
                            target.rotate(rotation.conj());
                        }
                        if (abs(distanceScaleVelocity - 1.0f) > epsilonTransform)
                        {
                            setDistance(getDistance() * (1.0f + distanceScaleVelocity), false);
                        }
                        mousePosScreenPrev = mousePosScreen;
                        //targetFut.setPosition(target.getPosition());
                    }
                }
            }
        }
        setAnglesFromOrientation();
    }
    ofCamera::begin(viewport);
}
Пример #5
0
int main()
{
    srand((unsigned)time(NULL));

    int i, j, k, l, varw, varc1, varc2, vfun=2, vtest, vgen; // iteration vars
    float w, c1, c2, edge, Vmax, goal, gb, res = 0, avggennew=0;  // gb is the global gbest
    float vel[coornum], pbest[coornum], gbest[coornum], results[4*testnum]; // Each bird's got their own gbest
    double absRadius[N],paramK[N]; // Absolute perceptive radius and the radius parameter matrix K
    double relRadius; // A iteration var for radius
    int radRec; // A var to count the index of the radius
    int adjmat[N][N]; // Adjacent Matrix

    char buffer[19]; // A buffer to write the file, 15 is the estimated char numbers
    char storage[19*relRange];


    /* Storage Section */
//The strategy is: we store the 'sum' into 'aves'.
//When the time comes they got loaded into the file, we'll have them become real 'average'

    float AveOptGen[relRange];  // FuncNumber*RadiusNumber: Every 19[radius] with a func
    float AveOptRate[relRange];  // FuncNumber*RadiusNumber: Every 19[radius] with a func
    float AveOptFit[relRange][gennum/aveDegInterval+1]; // The average of the gbest fitness of the interval generations
    float AveEndFit[relRange];// The average of the gbest fitness in the end of each successful test (last generation)
    /* End of Storage Section */


    for(i=0; i<relRange; i++)
    {
        AveOptGen[i]=0;
        AveOptRate[i]=0;
        AveEndFit[i]=0;
        for(j=0; j<gennum/aveDegInterval; j++)
        {
  //          AveDeg[i][j]=0;
            AveOptFit[i][j]=0;
        }

    }

    for(i=0; i<19*relRange; i++)
    {
        storage[i]=' ';
    }


    radRec=0; // Set the radius index counting number

    for(relRadius=0.2; relRadius<1.01; relRadius+=0.05) // Loop layer 1 (relRadius)
    {

        w = 0.6;
        for(varw = 0; varw < 1; varw++)
        {
            c1 = 1.7;
            for(varc1 = 0; varc1 < 1; varc1++)
            {
                c2 = 1.7;
                for(varc2 = 0; varc2 < 1 ; varc2++)
                {


                    edge = 30;
                    Vmax = edge;
                    goal = 100;

                    int ngoal = 0, avggen = 0; // Goal achieving flag & Average generations

                    for(i = 0; i < testnum; i++)
                    {
                        results[4*i] = gennum;
                        results[4*i+1] = 0;
                        results[4*i+2] = gennum;
                        results[4*i+3] = 0;
                    }


                    for(vtest = 0; vtest < testnum; vtest++)  // Run the experiment
                    {
                        double neoDiag=0;
                        double dist=0;
                        int sum = 1;


                        for(i = 0; i < coornum; i++)
                        {
                            pbest[i] = INT_MAX;
                            gbest[i] = INT_MAX;
                        }

                        //Initialization:

                        for(i = 0; i < dim + 1; i++)
                        {
                            for(j = 0; j < N; j++)
                            {
                                if(i < dim)
                                {
                                    coor[(dim+1)*j+i] = (double)rand() / RAND_MAX *  2 * edge - edge;
                                    vel[(dim+1)*j+i] = (double)rand() / RAND_MAX * 2 * Vmax - Vmax;
                                    pbest[(dim+1)*j+i] = coor[(dim+1)*j+i];
                                    gbest[(dim+1)*j+i] = coor[(dim+1)*j+i];

                                }
                                else
                                {
                                    // i=dim

                                    Func(j);
                                    // Initializing pbest
                                    pbest[(dim+1)*j+i] = coor[(dim+1)*j+i];
                                    gbest[(dim+1)*j+i] = coor[(dim+1)*j+i];

                                } // End of the condition i = dim
                            } // for birds



                        } // for dims


                        absRadius[0] = relRadius * sqrt(dim * pow(2 * edge , 2));
                        for(j=0;j<N;j++){
                            paramK[j]=relRadius;
                            absRadius[j]=absRadius[0];
                        }


                        for(j=0; j<N; j++)
                            for(k=0; k<N; k++) // Avoid Relapse
                            {
                                dist=getDistance(j,k);
                                if( dist <= absRadius[j] && j!=k ) // k Can be perceived by j
                                {
                                    adjmat[j][k]=1;
                                }
                                else
                                {
                                    adjmat[j][k]=0;
                                }


                            }
                        // End of producing the initiating Adjacent Matrix


                        // Updating each bird's gbest:
                        for(j=0; j<N; j++)
                        {
                            for(k=0; k<N; k++)
                                if( adjmat[j][k] != 0 ) // k Can be perceived by j
                                {
                                    // Updating the gbest of j
                                    //printf("%f\t",getDistance(j,k));
                                    if( coor[(dim+1)*k+dim] < gbest[(dim+1)*j+dim] )
                                    {
                                        for(l=0; l<=dim; l++)
                                            gbest[(dim+1)*j+l] = coor[(dim+1)*k+l];
                                    }
                                }
                            //printf("gbest of %d:%f\nfitness of %d:%f\n",j,gbest[(dim+1)*j+dim],j,coor[(dim+1)*j+dim]);
                        }

                        gb = gbest[dim]; // Updating the global gbest
                        for(i = 1; i < N; i++)
                            if(gbest[(dim+1)*i+dim] < gb)
                                gb = gbest[(dim+1)*i+dim];
                        AveOptFit[radRec][0]+=gb;

                        // End of Updating each bird's gbest in initialization


                        for(vgen = 0; vgen < gennum; vgen++)         // Evolution starts
                        {

                            for(i = 0; i < dim + 1; i++)
                            {
                                for(j = 0; j < N; j++)
                                {
                                    if(i < dim)
                                    {
                                        float r1 = (double)rand() / RAND_MAX * 1;
                                        float r2 = (double)rand() / RAND_MAX * 1;
                                        vel[(dim+1)*j+i] = w * vel[(dim+1)*j+i] + c1 * r1 * (pbest[(dim+1)*j+i] - coor[(dim+1)*j+i])\
                                                           + c2 * r2 * (gbest[(dim+1)*j+i] - coor[(dim+1)*j+i]);

                                        coor[(dim+1)*j+i] += vel[(dim+1)*j+i];

                                    }
                                    else  // i = dim
                                    {

                                        Func(j);
                                        // When i = dim, updating pbest:
                                        if(coor[(dim+1)*j+i] < pbest[(dim+1)*j+i])
                                            for(l = 0; l < dim + 1; l++)
                                                pbest[(dim+1)*j+l] = coor[(dim+1)*j+l];

                                        // Comparing itself with gbest:
                                        if(coor[(dim+1)*j+i] < gbest[(dim+1)*j+i])
                                            for(l = 0; l < dim + 1; l++)
                                                gbest[(dim+1)*j+l] = coor[(dim+1)*j+l];


                                    } // End of else
                                } // for birds
                            } // for dims

                            if( (vgen+1) % (changeInte) == 0 && vgen!=0)
                            {
                                double fit[2][N];
                                for(j=0;j<N;j++){
                                     fit[0][j]=coor[(dim+1)*j+dim];  // Fitness
                                     fit[1][j]=j;  // The index of particle
                                }
                                QuickSort(fit,0,N-1);  // Done sorting the fitness while keeping the index
                                // Changing the parameter k
                                // The quicksort gives a small to large sequence!
                                for(j=0;j<N;j++){
                                    if(j<15){
                                        paramK[(int)fit[1][j]]-=kstep;
                                        if( paramK[(int)fit[1][j]] < kLowerLim)
                                             paramK[(int)fit[1][j]] = kLowerLim;
                                    }
                                    if(j>=35){
                                        paramK[(int)fit[1][j]]+=kstep;
                                    }
                                    absRadius[(int)fit[1][j]]=paramK[(int)fit[1][j]]*neoDiag;
                                    //printf("%d,",(int)fit[1][j]);
                                }
                                //printf("\n");
                                //printf("%d,%f\n",vgen,neoDiag);
                            }

                            neoDiag=0;

                            // Producing the initiating Adjacent Matrix
                            for( j=0; j<N ; j++ )
                                for( k=0; k<N; k++) // Avoid Relapse
                                {
                                    dist=getDistance(j,k);
                                    if( dist <= absRadius[j] && j!=k ) // k Can be perceived by j
                                    {
                                        adjmat[j][k]=1;
                                    }
                                    else
                                    {
                                        adjmat[j][k]=0;
                                    }

                                    if( (vgen+1) % changeInte == (changeInte-1) )
                                        if(dist>neoDiag)
                                        {
                                            neoDiag=dist;
                                            //printf("%d,%d,dist:%f\t",j,k,dist);
                                        }

                                }
                            //if(neoDiag!=0)
                            //printf("%d,%f\n",vgen,neoDiag);
                            // End of producing the initiating Adjacent Matrix

                          /*  //Caculating Average Degree of the generation
                            if( (vgen+1) % aveDegInterval == 0 )
                            {
                                for( j=0; j<N ; j++ )
                                    for( k=0; k<N ; k++ )
                                        if( adjmat[j][k] != 0) // k Can be perceived by j
                                            aveDegree+=1;
                                aveDegree/=N; // Got it
                                AveDeg[radRec][(vgen+1) / aveDegInterval] += aveDegree; // Storing Average Degree of this particular generation
                            }
                        */


                            // Updating each bird's gbest:
                            for( j=0; j<N ; j++ )
                            {
                                for( k=0; k<N ; k++ )
                                    if( adjmat[j][k] != 0 ) // k Can be perceived by j
                                        // Updating the gbest of j
                                        if( coor[(dim+1)*k+dim] < gbest[(dim+1)*j+dim] )
                                            for(l=0; l<=dim; l++)
                                                gbest[(dim+1)*j+l] = coor[(dim+1)*k+l];
                                //printf("gbest of %d:%f\nfitness of %d:%f\n",j,gbest[(dim+1)*j+dim],j,coor[(dim+1)*j+dim]);
                            }
                            // End of Updating each bird's gbest

                            gb = gbest[dim]; // Updating the global gbest
                            for(i = 1; i < N; i++)
                                if(gbest[(dim+1)*i+dim] < gb)
                                    gb = gbest[(dim+1)*i+dim];

                            if( (vgen+1) % aveDegInterval == 0 )
                            {
                                AveOptFit[radRec][(vgen+1) / aveDegInterval]+=gb;
                            }

                            if(gb < goal && sum != 0)
                            {
                                results[4*vtest] = (double)vgen+1;
                                results[4*vtest+1] = gb;
                                sum = 0;
                                printf("\ngb:%f,%d\t",gb,vgen);
                                //ngoal++;
                                //break;
                            }
                            if(vgen == gennum - 1)
                            {
                                results[4*vtest+2] = gennum;
                                results[4*vtest+3] = gb;
                                printf("lastgb:%f\n",gb);
                            }


                        } // for vgens


                        printf("\nTest%d for Function%d of relRadius%f is done. The next one's coming at ya.\n\n",vtest,vfun,relRadius);

                    } // for vtest

                    for(i = 0; i < testnum; i++)
                    {
                        if(results[4*i] != gennum)
                        {
                            ngoal++;
                            avggen += results[4*i];
                            res += results[4*i+1];
                            AveEndFit[radRec]+=results[4*i+3];
                        }
                    }
                    printf("%d,%d", avggen, ngoal);
                    if(ngoal == 0)
                    {
                        AveEndFit[radRec]=-1;
                        avggennew = (double)gennum;
                    }
                    else
                    {
                        AveEndFit[radRec] /= ngoal;
                        avggennew = (double)avggen / ngoal;
                    }


                    printf("AVGEN:%f\t",avggennew);
                    AveOptGen[radRec]=avggennew;
                    printf("AVRATE:%f",(double)ngoal / testnum * 100);
                    AveOptRate[radRec]=(double)ngoal / testnum * 100;

                    printf("Function%d is tested under this radius.\n", vfun);

                    c2 += 0.1;
                }
                c1 += 0.1;
            }
            w += 0.1;
        }
//} // End of Loop layer 2 (population)

        radRec++;

        printf("\n\nRadius %d is tested\n\n",radRec);

    } // End of Loop layer 1 (relRadius)
    printf("\n\n Done! You got it, dude!");

    for(i=0; i<relRange; i++)
        for(j=0; j<=(gennum/aveDegInterval); j++)
        {
            AveOptFit[i][j]=(double)AveOptFit[i][j]/(testnum);
        }

// Get da data in da file!
    sprintf(storage,"Gen,");
    for(i=0; i<relRange; i++)
    {
        sprintf(buffer,"ItemRel%f,",0.2+i*0.05);
        strcat(storage,buffer);
    }


    pso = fopen("c:/pso/dynaRadKSort1.4/100/vicpsoFunc2-main.txt", "w");
    fprintf(pso, "RelRadius,AveOptGen,AveOptRate\n");
    for(i=0; i<relRange; i++)
    {
        fprintf(pso, "%f,%f,%f\n",0.2+i*0.05,AveOptGen[i],AveOptRate[i]);
    }
    fclose(pso);


    pso = fopen("c:/pso/dynaRadKSort1.4/100/vicpsoFunc2-OptFit.txt", "w");
    fprintf(pso, "%s\n",storage );

    for(j=0; j<=(gennum/aveDegInterval); j++)
    {
        int inIte;
        fprintf(pso,"%d,",j*10);
        for(inIte=0; inIte<relRange; inIte++)
        {
            fprintf(pso, "%f,",AveOptFit[inIte][j]);
        }
        fprintf(pso, "\n");
    }
    fclose(pso);

    pso = fopen("c:/pso/dynaRadKSort1.4/100/vicpsoFunc2-EndSucFit.txt","w");
    for(i=0; i<relRange;i++){
        fprintf(pso,"%f,%f,\n",0.2+i*0.05,AveEndFit[i]);
    }
    fclose(pso);

    return 0;

} // End of main
boost::optional<IdfObject> ForwardTranslator::translateShadingSurface( model::ShadingSurface & modelObject )
{
  boost::optional<IdfObject> idfObject;

  boost::optional<Schedule> transmittanceSchedule = modelObject.transmittanceSchedule();
  Transformation transformation;
  Point3dVector points;

  boost::optional<ShadingSurfaceGroup> shadingSurfaceGroup = modelObject.shadingSurfaceGroup();
  if (shadingSurfaceGroup){

    transformation = shadingSurfaceGroup->transformation();
    points = transformation * modelObject.vertices();

    if (istringEqual("Space", shadingSurfaceGroup->shadingSurfaceType())){

      idfObject = IdfObject(openstudio::IddObjectType::Shading_Zone_Detailed);
      idfObject->setString(Shading_Zone_DetailedFields::Name, modelObject.name().get());

      boost::optional<Space> space = shadingSurfaceGroup->space();
      if (space){
        
        boost::optional<Surface> baseSurface;
        double minDistance = std::numeric_limits<double>::max();

        // at this point zone has one space and internal surfaces have already been combined
        for (const Surface& surface : space->surfaces()){
          if (istringEqual(surface.outsideBoundaryCondition(), "Outdoors")){
            Point3dVector surfaceVertices = surface.vertices();
            for (const Point3d& point : points){
              for (const Point3d& surfaceVertex : surfaceVertices){
                double distance = getDistance(point, surfaceVertex);
                if (distance < minDistance){
                  baseSurface = surface;
                  minDistance = distance;
                }
              }
            }
          }
        }

        if (!baseSurface){
          LOG(Error, "Cannot find appropriate base surface for shading surface '" << modelObject.name().get() << 
                     "', the shading surface will not be translated");
          return boost::none;
        }

        idfObject->setString(Shading_Zone_DetailedFields::BaseSurfaceName, baseSurface->name().get());
      }

      if (transmittanceSchedule){
        idfObject->setString(Shading_Zone_DetailedFields::TransmittanceScheduleName, transmittanceSchedule->name().get());
      }

    }else if (istringEqual("Site", shadingSurfaceGroup->shadingSurfaceType())){

      idfObject = IdfObject(openstudio::IddObjectType::Shading_Site_Detailed);
      idfObject->setString(Shading_Site_DetailedFields::Name, modelObject.name().get());
      
      if (transmittanceSchedule){
        idfObject->setString(Shading_Site_DetailedFields::TransmittanceScheduleName, transmittanceSchedule->name().get());
      }

    }else{
      boost::optional<Building> building = modelObject.model().getUniqueModelObject<Building>();
      if (building){
        transformation = building->transformation().inverse()*transformation;
      }

      idfObject = IdfObject(openstudio::IddObjectType::Shading_Building_Detailed);
      idfObject->setString(Shading_Building_DetailedFields::Name, modelObject.name().get());
      
      if (transmittanceSchedule){
        idfObject->setString(Shading_Building_DetailedFields::TransmittanceScheduleName, transmittanceSchedule->name().get());
      }
    }

  }else{
    idfObject = IdfObject(openstudio::IddObjectType::Shading_Building_Detailed);
    idfObject->setString(Shading_Building_DetailedFields::Name, modelObject.name().get());
    
    if (transmittanceSchedule){
      idfObject->setString(Shading_Building_DetailedFields::TransmittanceScheduleName, transmittanceSchedule->name().get());
    }
  }

  m_idfObjects.push_back(*idfObject);

  idfObject->clearExtensibleGroups();

  for (const Point3d& point : points){
    IdfExtensibleGroup group = idfObject->pushExtensibleGroup();
    OS_ASSERT(group.numFields() == 3);
    group.setDouble(0, point.x());
    group.setDouble(1, point.y());
    group.setDouble(2, point.z());
  }

  // get reflectance properties from construction if possible
  bool addShadingPropertyObject = false;

  IdfObject shadingPropertyObject = IdfObject(openstudio::IddObjectType::ShadingProperty_Reflectance);
  shadingPropertyObject.setString(ShadingProperty_ReflectanceFields::ShadingSurfaceName, modelObject.name().get());

  boost::optional<model::ConstructionBase> constructionBase = modelObject.construction();
  if (constructionBase){
    if (constructionBase->isFenestration()){

      shadingPropertyObject.setDouble(ShadingProperty_ReflectanceFields::FractionofShadingSurfaceThatIsGlazed, 1.0);
      shadingPropertyObject.setString(ShadingProperty_ReflectanceFields::GlazingConstructionName, constructionBase->name().get());
      addShadingPropertyObject = true;

    }else{

      shadingPropertyObject.setDouble(ShadingProperty_ReflectanceFields::FractionofShadingSurfaceThatIsGlazed, 0.0);

      boost::optional<model::Construction> construction = constructionBase->optionalCast<model::Construction>();
      if (construction){

        std::vector<model::Material> layers = construction->layers();

        // we want the outer layer
        if (!layers.empty()){

          if (layers[0].optionalCast<model::StandardOpaqueMaterial>()){
            model::StandardOpaqueMaterial outerMaterial = layers[0].cast<model::StandardOpaqueMaterial>();

            boost::optional<double> solRefl = outerMaterial.solarReflectance();
            if (solRefl){
              shadingPropertyObject.setDouble(ShadingProperty_ReflectanceFields::DiffuseSolarReflectanceofUnglazedPartofShadingSurface, *solRefl);
              addShadingPropertyObject = true;
            }

            boost::optional<double> visRefl = outerMaterial.visibleReflectance();
            if (visRefl){
              shadingPropertyObject.setDouble(ShadingProperty_ReflectanceFields::DiffuseVisibleReflectanceofUnglazedPartofShadingSurface, *visRefl);
              addShadingPropertyObject = true;
            }
          }

          
          if (layers[0].optionalCast<model::MasslessOpaqueMaterial>()){
            model::MasslessOpaqueMaterial outerMaterial = layers[0].cast<model::MasslessOpaqueMaterial>();

            boost::optional<double> solRefl = outerMaterial.solarReflectance();
            if (solRefl){
              shadingPropertyObject.setDouble(ShadingProperty_ReflectanceFields::DiffuseSolarReflectanceofUnglazedPartofShadingSurface, *solRefl);
              addShadingPropertyObject = true;
            }

            boost::optional<double> visRefl = outerMaterial.visibleReflectance();
            if (visRefl){
              shadingPropertyObject.setDouble(ShadingProperty_ReflectanceFields::DiffuseVisibleReflectanceofUnglazedPartofShadingSurface, *visRefl);
              addShadingPropertyObject = true;
            }
          }

        }
      }
    }
  }

  if (addShadingPropertyObject){
    m_idfObjects.push_back(shadingPropertyObject);
  }

  return idfObject;
}
Пример #7
0
boolean isCollission(Sphere &sphere1,Sphere &sphere2){
	if(getDistance(sphere1.Centre,sphere2.Centre)<sphere1.radius+sphere2.radius)
		return true;
	return false;
}
Пример #8
0
//----------------------------------------
void ofEasyCam::updateMouse(){
    mouse = ofVec2f(ofGetMouseX(), ofGetMouseY());
    if(viewport.inside(mouse.x, mouse.y) && !bValidClick && ofGetMousePressed()){
        unsigned long curTap = ofGetElapsedTimeMillis();
        if(lastTap != 0 && curTap - lastTap < doubleclickTime){
            reset();
        }
 
        if ((bEnableMouseMiddleButton && ofGetMousePressed(OF_MOUSE_BUTTON_MIDDLE)) || ofGetKeyPressed(doTranslationKey)  || ofGetMousePressed(OF_MOUSE_BUTTON_RIGHT) || ofGetMousePressed(OF_MOUSE_BUTTON_LEFT)){ // <>< # Added left mouse button for dragging
            bDoTranslate = true;
            bDoRotate = false;
            bApplyInertia = false;
        }/*else if (ofGetMousePressed(OF_MOUSE_BUTTON_LEFT)) {
            bDoTranslate = false;
            bDoRotate = true;
            bApplyInertia = false;
            if(ofVec2f(mouse.x - viewport.x - (viewport.width/2), mouse.y - viewport.y - (viewport.height/2)).length() < min(viewport.width/2, viewport.height/2)){
                bInsideArcball = true;
            }else {
                bInsideArcball = false;
            }
        }*/
        lastTap = curTap;
        //lastMouse = ofVec2f(ofGetPreviousMouseX(),ofGetPreviousMouseY()); //this was causing the camera to have a tiny "random" rotation when clicked.
        lastMouse = mouse;
        bValidClick = true;
        bApplyInertia = false;
    }
 
    if (bValidClick) {
        if (!ofGetMousePressed()) {
            bApplyInertia = true;
            bValidClick = false;
        }else {
            int vFlip;
            if(isVFlipped()){
                vFlip = -1;
            }else{
                vFlip =  1;
            }
 
            mouseVel = mouse  - lastMouse;
 
            if (bDoTranslate) {
                moveX = 0;
                moveY = 0;
                moveZ = 0;
                if (ofGetMousePressed(OF_MOUSE_BUTTON_RIGHT)) {
                    moveZ = mouseVel.y * sensitivityZ * (getDistance() + FLT_EPSILON)/ viewport.height;
                }else {
                    moveX = -mouseVel.x * sensitivityXY * (getDistance() + FLT_EPSILON)/viewport.width;
                    moveY = vFlip * mouseVel.y * sensitivityXY * (getDistance() + FLT_EPSILON)/viewport.height;
                }
            }else {
                xRot = 0;
                yRot = 0;
                zRot = 0;
                if (bInsideArcball) {
                    xRot = vFlip * -mouseVel.y * rotationFactor;
                    yRot = -mouseVel.x * rotationFactor;
                }else {
                    ofVec2f center(viewport.width/2, viewport.height/2);
                    zRot = - vFlip * ofVec2f(mouse.x - viewport.x - center.x, mouse.y - viewport.y - center.y).angle(lastMouse - ofVec2f(viewport.x, viewport.y) - center);
                }
            }
            lastMouse = mouse;
        }
    }
}
Пример #9
0
void main(void)\n\
{  \n\
   float fTime0_X = parameters[0][0];\n\
   vec4 coreSeed = parameters[1];\n\
\n\
   vec3 rayDir = normalize(objectPosition * vec3(1.0, 0.6, 1.0));\n\
   vec3 camPos = vec3(0.0, 0.0, -parameters[0][1]);\n\
   \n\
   // rotate camera around y axis\n\
   float alpha = parameters[0][2] * 4.5f;\n\
   camPos.xz = vec2(cos(alpha)*camPos.x - sin(alpha)*camPos.z,\n\
                    sin(alpha)*camPos.x + cos(alpha)*camPos.z);\n\
   rayDir.xz = vec2(cos(alpha)*rayDir.x - sin(alpha)*rayDir.z,\n\
                    sin(alpha)*rayDir.x + cos(alpha)*rayDir.z);\n\
   \n\
   vec3 rayPos = camPos;\n\
   float sceneSize = 8.0;\n\
   vec3 totalColor = vec3(0.);\n\
   float stepSize;\n\
   float totalDensity = 0.0;\n\
   float stepDepth = 0.0; // how far I went already.\n\
   \n\
   for(int step = 0; length(rayPos)<sceneSize && totalDensity < 0.9 && step < 50; step++)\n\
   {      \n\
      float implicitVal;\n\
      \n\
      // This stuff is the transformation information from previous stuff\n\
	  float transer = parameters[0][3];\n\
      vec4 prevQuaternion = vec4(cos(transer), sin(transer), sin(transer * 1.3), sin(transer * 2.7));\n\
      prevQuaternion = normalize(prevQuaternion);\n\
      float prevLength = 1.0;\n\
      vec3 prevMover = vec3(0.0);\n\
      vec3 prevColor = vec3(1.0, 0.4, 0.2);\n\
      \n\
      // Multiple boxes\n\
      implicitVal = 1.0e10;\n\
      \n\
      for (int loop = 0; loop < 12; loop++)\n\
      {\n\
         vec4 newQuaternion;\n\
         float newLength;\n\
         vec3 newMover;\n\
         vec3 newColor;\n\
         \n\
         mat3 prevRotationMatrix = quaternionToMatrix(prevQuaternion);\n\
\n\
         // Loop for solid stuff\n\
         vec4 seed = coreSeed;\n\
         for (int k = 0; k < 4; k++)\n\
         {\n\
            seed = randomIteration(seed);\n\
            vec4 quaternion = normalize(seed - vec4(0.5));\n\
            mat3 rotationMatrix = quaternionToMatrix(quatMult(quaternion, prevQuaternion));\n\
            vec3 lengthes = seed.xyz * seed.xyz * seed.xyz * seed.xyz * vec3(0.2) + vec3(0.05);\n\
            lengthes *= prevLength;\n\
            vec3 mover = 0.5*seed.wzx - vec3(0.25);\n\
            mover = (mover * prevRotationMatrix * prevLength) + prevMover;\n\
            float curImplicitVal = getDistance(rotationMatrix, lengthes, mover, rayPos);\n\
            implicitVal = min(implicitVal, curImplicitVal);\n\
         }\n\
         \n\
         // Non-solid:\n\
         float nonSolidDist = 1.0e10;\n\
         for (int k = 0; k < 2; k++)\n\
         {\n\
            seed = randomIteration(seed);\n\
            vec4 quaternion = normalize(seed - vec4(0.5));\n\
            quaternion = quatMult(quaternion, prevQuaternion);\n\
            vec3 lengthes = seed.xyz * vec3(0.3) + vec3(0.25);\n\
            lengthes *= prevLength;\n\
            vec3 mover = 0.5*seed.wzx - vec3(0.25);\n\
            mover = (mover * prevRotationMatrix * prevLength) + prevMover;\n\
            float curImplicitVal = getSphereDistance(lengthes.x, mover, rayPos);\n\
            if (curImplicitVal < nonSolidDist)\n\
            {\n\
               nonSolidDist = curImplicitVal;\n\
               newQuaternion = quaternion;\n\
               newLength = lengthes.x;\n\
               newMover = mover;\n\
               newColor = seed.xyz;\n\
            }\n\
         }\n\
         \n\
         if (nonSolidDist > implicitVal)\n\
         {\n\
            // I will not get closer than where I am now.\n\
            break;\n\
         }\n\
         else\n\
         {\n\
            prevQuaternion = newQuaternion;\n\
            prevLength = newLength;\n\
            prevMover = newMover;\n\
            prevColor = 0.5 * prevColor + 0.5 * newColor;      \n\
         }\n\
      }\n\
      \n\
      // I need to do this distance related to for the DOF!      \n\
      totalColor += vec3(1./50., 1./70., 1./90.) *\n\
                    1.7 / exp(abs(implicitVal*5.) + 0.0) * 1.8;\n\
      totalDensity += 1./ 15. / exp(abs(implicitVal*10.0) + 0.5);\n\
                      // *(1.0 - cos(fTime0_X*3.)*0.5);\n\
      //if (implicitVal < 0.0)\n\
      stepDepth += abs(implicitVal) * 0.95;      \n\
      {\n\
         // TODO: I could make this distance-related, with offset to get the size right?\n\
         float localDensity = implicitVal < 0.0 ? 1.0 : 0.0;\n\
         totalColor = totalColor + (1.-totalDensity) * prevColor * localDensity;\n\
         totalDensity = totalDensity + (1.05-totalDensity) * localDensity;\n\
      }\n\
      \n\
      stepSize = abs(implicitVal) * 0.99;\n\
      stepSize = max(0.005 * stepDepth, stepSize);\n\
      rayPos += rayDir * stepSize;\n\
   }\n\
   \n\
   float grad = normalize(rayDir).y;\n\
   totalColor += (1.-totalDensity) * (grad * vec3(0.0,-0.4,-0.3) + (1.-grad)*vec3(0.0,0.4,0.6));\n\
   \n\
   gl_FragColor = vec4(totalColor-vec3(0.0), 1.0);\n\
}\n\
Пример #10
0
/*
*	Calcul du sous arbre recouvrant minimal
*
*	@param g, graphe
*	@return un graphe avec les liaisons du sous arbre recouvrant minimal
*/
struct Graph* minSpanningTree(struct Graph g)
{
	int l, c, i=0, nbEdges=0, cityA=-1, cityB=-1;
	int isConnexe;
	struct Edge edge;
	struct Graph* newGraph=NULL;
	struct Edge* matrixEdges=NULL;
	int* connexeComp=NULL;
	float** matrix;
	int aux, j, k;
 
	newGraph =(struct Graph*) malloc(sizeof(struct Graph));
	newGraph->nbCities = g.nbCities;

	connexeComp = malloc(g.nbCities * sizeof(int));
	matrixEdges = malloc((g.nbCities*g.nbCities) * sizeof(struct Edge));

	newGraph->matrixCities = malloc(g.nbCities * sizeof(struct City));

	for(j = 0; j < g.nbCities; j++)
	{
		newGraph->matrixCities[j] = g.matrixCities[j];
	}

	matrix = initMatrix(g.nbCities);

	for(j = 0; j < g.nbCities; j++)
	{
		for(k = 0; k < g.nbCities; k++)
		{
			matrix[j][k] = -1.0;
		}
	}

	for (l = 0; l < g.nbCities-1; l++)
	{
		for (c = l+1; c < g.nbCities; c++)
		{
			if(g.matrix[l][c] != -1)
			{
				edge.cityA = l;
				edge.cityB = c;
				edge.distance = g.matrix[l][c];
				matrixEdges[i] = edge;
				i++;
			}
		}
	}

	nbEdges = i;
	quickSortDistance(matrixEdges, nbEdges);

	for (i = 0; i < g.nbCities; i++)
	{
		connexeComp[i] = i;
	}

	k = 0;
	j = 0;
    
	while (k < (g.nbCities-1) && j<nbEdges)
	{
		cityA= matrixEdges[j].cityA;
		cityB= matrixEdges[j].cityB;
		if (connexeComp[cityA] != connexeComp[cityB])
		{
			k++;
			matrix[cityA][cityB] = getDistance(g, cityA, cityB);
			aux = connexeComp[cityB];

			for (i = 0; i < g.nbCities; i++)
			{
				if (connexeComp[i] == aux)
				{
					connexeComp[i] = connexeComp[cityA];
         			}
			}
		}
		j++;
	}

	i = 0;
	isConnexe = 1;

	while (i < g.nbCities-1 && isConnexe)
	{
		if (connexeComp[i] != connexeComp[i+1])
		{
			isConnexe = 0;
		}
		i++;
	}

	newGraph->matrix = matrix;

	if (isConnexe == 0)
	{
		free(connexeComp);
		free(matrixEdges);
		deleteGraph(*newGraph);
		free(newGraph);
		printf("The graph is not connected : there is no minimum spanning tree between these cities.\n");
		return NULL;
	}
	

	free(connexeComp);
	free(matrixEdges);

	return newGraph;
}
Пример #11
0
void LegsDetector::update(const std::vector< laser_t >& laserBuffer)
{
   // first remove high peaks due to absorving materials
   laser_t laser[BUFFERLENGTH];
   for (int i = 0; i < _bufferLength; i++)
   {
      laser[i].range = DBL_MAX;
      double angle = laser[i].angle = laserBuffer[i].angle;
	  for (int k = max(0, i-_delta); k <= min( _bufferLength-1, i+_delta); k++)
      {
         double range;
         if (laserBuffer[k].range < laser[i].range)
         {
            range = laser[i].range = laserBuffer[k].range;
            laser[i].x = range * cos(angle);
            laser[i].y = range * sin(angle);
         }
      }
   }
   //                       (0)
   //                        |
   //                        |
   //                        |
   // (+90)------------------|-------------------(-90)
   // reading from right to left i.e. from -90 to +90
   //
   // start extracting all the vertical edges of interest
   // remembering the scan goes from right (-PI/2) to left (+PI/2)
   // left and right edges correspond to the robot's point of view
   //
   //                 -(p1)             (p1)-
   //                   |    (p1)-(p1)   |
   //                   |     |    |     |
   //                   |     |   l|     |r
   //                   |     |    |     |
   //                  L|     |R  (p2)--(p2)
   //                   |     |
   //                   |     |
   //                  (p2)--(p2)
   //
   vector< edge_t<point_t> > vEdge;
   double prevRange = laser[0].range;
   for (int id = 1; id < _bufferLength; id++)
   {
      double range = laser[id].range;

      //if ( range == MAXIMUM_RANGE  || prevRange == MAXIMUM_RANGE ) ;
	  if ((prevRange - range) > MIN_LONG_EDGE)      // possible left long edge
      {
		  edge_t<point_t> e = {Point(laser[id-1].x, laser[id-1].y, laser[id-1].range, laser[id-1].angle),
                              Point(laser[id].x, laser[id].y, laser[id].range, laser[id].angle), 'R'};
         vEdge.push_back(e);
      }
      else if ((range - prevRange) > MIN_LONG_EDGE) // possible right long edge
      {
         edge_t<point_t> e = {Point(laser[id].x, laser[id].y, laser[id].range, laser[id].angle),
                              Point(laser[id-1].x, laser[id-1].y, laser[id-1].range, laser[id-1].angle), 'L'};
         vEdge.push_back(e);
      }
      else if ((prevRange - range) > MIN_SHORT_EDGE) // possible left short edge
      {
         edge_t<point_t> e = {Point(laser[id-1].x, laser[id-1].y, laser[id-1].range, laser[id-1].angle),
                              Point(laser[id].x, laser[id].y, laser[id].range, laser[id].angle), 'r'};
         vEdge.push_back(e);
      }
      else if ((range - prevRange) > MIN_SHORT_EDGE) // possible right short edge
      {
         edge_t<point_t> e = {Point(laser[id].x, laser[id].y, laser[id].range, laser[id].angle),
                              Point(laser[id-1].x, laser[id-1].y, laser[id-1].range, laser[id-1].angle), 'l'};
         vEdge.push_back(e);
      }

      prevRange = range;
   }
   // remove edges too close to each other
   if ( vEdge.empty() ) return;
   vector<edge_t<point_t> >::iterator first = vEdge.begin();
   vector<edge_t<point_t> >::iterator second = first + 1;
   double d1, d2;
   char t1, t2;
   while (second < vEdge.end())
   {
	   t1 = toupper(first->type);
       t2 = toupper(second->type);
	   d1 = getDistance(second->p1, first->p2);
	   d2 = getDistance(first->p1, second->p2);
       if ( t1 == 'R' && t2 == 'R' && d1 < MIN_EDGE_DIST )
       {
		   first->p2 = second->p2;
           first->type = 'R';
           second = vEdge.erase(second);
        }
        else if ( t1 == 'L' && t2 == 'L' && d2 < MIN_EDGE_DIST )
        {
			first->p1 = second->p1;
            first->type = 'L';
            second = vEdge.erase(second);
	   }
       else
       {
		   first++;
           second++;
       }
   }
   if ( vEdge.empty() ) return;
   // draw some stuff for debugging... (must be done now, before vEdge is modified)
   if (_debug)
   {
      CvPoint start;
	  cvSet(_tmpImg, cvScalar(255,255,255));

	  start = cvPoint(DEBUG_WINDOW_WIDTH/2, 0);
	  cvCircle(_tmpImg, start, 1*DEBUG_WINDOW_WIDTH/80, cvScalar(255,0,0));
	  cvCircle(_tmpImg, start, 1*DEBUG_WINDOW_WIDTH/16, cvScalar(255,0,0));
	  cvCircle(_tmpImg, start, 2*DEBUG_WINDOW_WIDTH/16, cvScalar(255,0,0));
	  cvCircle(_tmpImg, start, 3*DEBUG_WINDOW_WIDTH/16, cvScalar(255,0,0));
	  cvCircle(_tmpImg, start, 4*DEBUG_WINDOW_WIDTH/16, cvScalar(255,0,0));
	  cvCircle(_tmpImg, start, 5*DEBUG_WINDOW_WIDTH/16, cvScalar(255,0,0));
	  cvCircle(_tmpImg, start, 6*DEBUG_WINDOW_WIDTH/16, cvScalar(255,0,0));
	  cvCircle(_tmpImg, start, 7*DEBUG_WINDOW_WIDTH/16, cvScalar(255,0,0));
	  cvCircle(_tmpImg, start, 8*DEBUG_WINDOW_WIDTH/16, cvScalar(255,0,0));

      start = cvPoint(METER2PIXEL(laser[0].y) + DEBUG_WINDOW_WIDTH/2,
                              METER2PIXEL(laser[0].x));
      // draw the laser data
      for (int i = 1; i < _bufferLength; i++)
      {
         CvPoint end = cvPoint(METER2PIXEL(laser[i].y) + DEBUG_WINDOW_WIDTH/2,
                               METER2PIXEL(laser[i].x));

		 if (laser[i].range == MAXIMUM_RANGE && laser[i-1].range == MAXIMUM_RANGE)
			 cvLine(_tmpImg, start, end, cvScalar(0,0,0));
		 if (laser[i].range <  MAXIMUM_RANGE && laser[i-1].range <  MAXIMUM_RANGE)
			 cvLine(_tmpImg, start, end, cvScalar(0,0,0));

		 start = end;
      }
      // draw the extremes
      for (unsigned int i = 0; i < vEdge.size(); i++)
      {
         CvScalar color;
		 switch (vEdge[i].type)
         {
            case 'R':
               color = cvScalar(0,0,255); // red
               break;
            case 'L':
               color = cvScalar(255,0,0); // blue
               break;
            case 'r':
               color = cvScalar(0,196,255);  // yellow
               break;
            case 'l':
               color = cvScalar(64,255,0);  // green
               break;
         }
		 // draw min extremes
		 CvPoint center = cvPoint(METER2PIXEL(vEdge[i].p1.y) + DEBUG_WINDOW_WIDTH/2,
                                  METER2PIXEL(vEdge[i].p1.x));
         cvCircle(_tmpImg, center, 2, color);
         // draw max extremes
         CvPoint c1 = cvPoint(METER2PIXEL(vEdge[i].p2.y) - 3 + DEBUG_WINDOW_WIDTH/2,
                              METER2PIXEL(vEdge[i].p2.x) - 3);
         CvPoint c2 = cvPoint(METER2PIXEL(vEdge[i].p2.y) + 3 + DEBUG_WINDOW_WIDTH/2,
                              METER2PIXEL(vEdge[i].p2.x) + 3);
         cvRectangle(_tmpImg, c1, c2, color);
      }
   }

   // extract the horizontal lines of interest
   vector< edge_t<point_t> > hEdge;
   int temp = 1;
   while ( temp > 0 ) { temp = getUpattern(vEdge, hEdge); }
   temp = 1;
   while ( _selectivity < 2 && temp > 0 ) { temp = getPpattern(vEdge, hEdge);}
   temp = 1;
   while ( _selectivity < 1 && temp > 0 ) { temp = getOpattern(vEdge, hEdge);}

   // finally calculate distance and direction of each horizontal line
   _target.clear();
   vector< edge_t<point_t> >::iterator itend = hEdge.end();
   for (vector< edge_t<point_t> >::iterator it = hEdge.begin(); it < itend; it++)
   {
      target_t t;
      // the distance is an average between the two points
      double xm = ((it->p1).x + (it->p2).x) / 2;
      double ym = ((it->p1).y + (it->p2).y) / 2;
      t.distance = sqrt(sqr(xm) + sqr(ym));
      // left PI/2, right -PI/2
      t.bearing = atan2(ym, xm);
      // no height information of course...
      t.pattern = it->type;
      _target.push_back(t);
   }
   // final number of detected people
   _howMany = _target.size();
   // draw the last things for debugging
   if (_debug)
   {
      // draw horizontal edges
      for (unsigned int i = 0; i < hEdge.size(); i++)
      {
         CvPoint p1 = cvPoint(METER2PIXEL(hEdge[i].p1.y) + DEBUG_WINDOW_WIDTH/2,
                              METER2PIXEL(hEdge[i].p1.x));
         CvPoint p2 = cvPoint(METER2PIXEL(hEdge[i].p2.y) + DEBUG_WINDOW_WIDTH/2,
                              METER2PIXEL(hEdge[i].p2.x));
//          cvLine(_tmpImg, p1, p2, cvScalar(0,128,255), 2);
         CvPoint pm = cvPoint((p1.x + p2.x) / 2, (p1.y + p2.y) / 2);
         int thick;
         if (hEdge[i].type == 'U')
            thick = 3;
         else if (hEdge[i].type == 'P')
            thick = 2;
         else
            thick = 1;
         cvLine(_tmpImg, cvPoint(DEBUG_WINDOW_WIDTH/2, 0), pm, cvScalar(0,128,255), thick);
      }

      cvFlip(_tmpImg, NULL, -1);
      cvResize(_tmpImg, _debugImage, CV_INTER_NN);
      cvShowImage("Legs detector", _debugImage);
	cvWaitKey(20);
 	  //if (_delay)
        //cvWaitKey(_delay);  // handles event processing of HIGHGUI library
   }
   return;
}
Пример #12
0
/*
*	Calcul le chemin le plus court entre 2 villes en utilisant l'algorithme de Dijkstra
*
*	@param g, est une matrice de n entier par n entier (représentant la distance entre 2 villes) où n représente le nombre de ville.
*	@param cityA, ville représentée par un entier (indice de la matrice du graphe g).
*	@param cityB, ville représentée par un entier (indice de la matrice du graphe g).
*	@return un tableau d'entiers, le chemin le plus court entre les paramètres cityA et cityB où chaque case représente
*		l'indice de la ville dans le tableau de ville.
*/
int shortestPath(struct Graph g, int cityA, int cityB, int* path)
{
	int i, j, newCity = 0;
	float min, dist;
	int city = cityA;
	int newCityFound = 1;
	int* father = (int*) malloc(g.nbCities * sizeof(int));
	float* length = (float*) malloc(g.nbCities * sizeof(float));
	int* visited = (int*) malloc(g.nbCities * sizeof(int));

	for(i = 0; i < g.nbCities; i++)
	{
		path[i] = -1;
	}

	for(i = 0; i < g.nbCities; i++)
	{
		father[i] = -1;
		length[i] = -1.0;
		visited[i] = -1;
	}
	
	length[city] = 0;
	while(city != cityB && newCityFound)
	{
		for(i = 0; i < g.nbCities; i++)
		{
			dist = getDistance(g, i, city);
			
			if((dist > 0.0) && (visited[i] == -1))
			{
				if((length[i] == -1.0) || (dist + length[city] < length[i]))
				{
					length[i] = dist + length[city];
					
					father[i] = city;
				}					
			}
		}
		
		min = 10000000;
		newCityFound = 0;
		
		for(i = 0; i < g.nbCities; i++)
		{
			if((length[i] < min) && (visited[i] == -1) && (length[i] > 0))
			{
				min = length[i];
				newCity = i;
				newCityFound = 1;
			}
		}

		visited[newCity] = 0;
		city = newCity;
		
	}
	
	if (!newCityFound)
	{
		free(father);
		free(visited);
		free(length);
		return 0;
	}
	else
	{
		i = cityB;
		path[0] = cityB;
		j = 0;
	
		while(path[j] != cityA)
		{
			j++;
			path[j] = father[i];
			i = father[i];
		}

		free(father);
		free(visited);
		free(length);

		return 1;
	}
}
Пример #13
0
void CMobEntity::OnMobSkillFinished(CMobSkillState& state, action_t& action)
{

    auto PSkill = state.GetSkill();
    auto PTarget = static_cast<CBattleEntity*>(state.GetTarget());

    static_cast<CMobController*>(PAI->GetController())->TapDeaggroTime();

    // store the skill used
    m_UsedSkillIds[PSkill->getID()] = GetMLevel();

    PAI->TargetFind->reset();

    float distance = PSkill->getDistance();
    uint8 findFlags = 0;
    if (PSkill->getFlag() & SKILLFLAG_HIT_ALL)
    {
        findFlags |= FINDFLAGS_HIT_ALL;
    }

    // Mob buff abilities also hit monster's pets
    if (PSkill->getValidTargets() == TARGET_SELF)
    {
        findFlags |= FINDFLAGS_PET;
    }

    action.id = id;
    if (objtype == TYPE_PET && static_cast<CPetEntity*>(this)->getPetType() == PETTYPE_JUG_PET &&
        static_cast<CPetEntity*>(this)->getPetType() == PETTYPE_AUTOMATON)
        action.actiontype = ACTION_PET_MOBABILITY_FINISH;
    else if (PSkill->getID() < 256)
        action.actiontype = ACTION_WEAPONSKILL_FINISH;
    else
        action.actiontype = ACTION_MOBABILITY_FINISH;
    action.actionid = PSkill->getID();

    if (PTarget && PAI->TargetFind->isWithinRange(&PTarget->loc.p, distance))
    {
        if (PSkill->isAoE())
        {
            PAI->TargetFind->findWithinArea(PTarget, (AOERADIUS)PSkill->getAoe(), PSkill->getRadius(), findFlags);
        }
        else if (PSkill->isConal())
        {
            float angle = 45.0f;
            PAI->TargetFind->findWithinCone(PTarget, distance, angle, findFlags);
        }
        else
        {
            PAI->TargetFind->findSingleTarget(PTarget, findFlags);
        }
    }
    else
    {
        action.actiontype = ACTION_MOBABILITY_INTERRUPT;
        actionList_t& actionList = action.getNewActionList();
        actionList.ActionTargetID = id;

        actionTarget_t& actionTarget = actionList.getNewActionTarget();
        actionTarget.animation = PSkill->getID();
        return;
    }

    uint16 actionsLength = PAI->TargetFind->m_targets.size();

    PSkill->setTotalTargets(actionsLength);
    PSkill->setTP(state.GetSpentTP());
    PSkill->setHPP(GetHPP());

    uint16 msg = 0;
    uint16 defaultMessage = PSkill->getMsg();

    bool first {true};
    for (auto&& PTarget : PAI->TargetFind->m_targets)
    {
        actionList_t& list = action.getNewActionList();

        list.ActionTargetID = PTarget->id;

        actionTarget_t& target = list.getNewActionTarget();

        list.ActionTargetID = PTarget->id;
        target.reaction = REACTION_HIT;
        target.speceffect = SPECEFFECT_HIT;
        target.animation = PSkill->getAnimationID();
        target.messageID = PSkill->getMsg();


        // reset the skill's message back to default
        PSkill->setMsg(defaultMessage);

        if (objtype == TYPE_PET && static_cast<CPetEntity*>(this)->getPetType() != PETTYPE_JUG_PET)
        {
            target.animation = PSkill->getPetAnimationID();
            target.param = luautils::OnPetAbility(PTarget, this, PSkill, PMaster, &action);
        }
        else
        {
            target.param = luautils::OnMobWeaponSkill(PTarget, this, PSkill);
        }

        if (msg == 0)
        {
            msg = PSkill->getMsg();
        }
        else
        {
            msg = PSkill->getAoEMsg();
        }

        target.messageID = msg;

        if (PSkill->hasMissMsg())
        {
            target.reaction = REACTION_MISS;
            target.speceffect = SPECEFFECT_NONE;
            if (msg = PSkill->getAoEMsg())
                msg = 282;
        }
        else
        {
            target.reaction = REACTION_HIT;
        }

        if (target.speceffect & SPECEFFECT_HIT)
        {
            target.speceffect = SPECEFFECT_RECOIL;
            target.knockback = PSkill->getKnockback();
            if (first && (PSkill->getSkillchain() != 0))
            {
                CWeaponSkill* PWeaponSkill = battleutils::GetWeaponSkill(PSkill->getSkillchain());
                if (PWeaponSkill)
                {
                    SUBEFFECT effect = battleutils::GetSkillChainEffect(PTarget, PWeaponSkill);
                    if (effect != SUBEFFECT_NONE)
                    {
                        int32 skillChainDamage = battleutils::TakeSkillchainDamage(this, PTarget, target.param);
                        if (skillChainDamage < 0)
                        {
                            target.addEffectParam = -skillChainDamage;
                            target.addEffectMessage = 384 + effect;
                        }
                        else
                        {
                            target.addEffectParam = skillChainDamage;
                            target.addEffectMessage = 287 + effect;
                        }
                        target.additionalEffect = effect;
                    }
                }
                first = false;
            }
        }
        PTarget->StatusEffectContainer->DelStatusEffectsByFlag(EFFECTFLAG_DETECTABLE);
    }
}
Пример #14
0
float GestureRecognizer::getPathLength(vector<CCPoint> points) {
	float dist = 0;
	for(int i=1; i < points.size(); i++) 
		dist += getDistance(points[i], points[i-1]);
	return dist;
}
Пример #15
0
float GestureRecognizer::getPathDist(vector<CCPoint> pointsA, vector<CCPoint> pointsB) {
	float dist = 0;
	for(int i=0; i<pointsA.size(); i++) 
		dist += getDistance(pointsA[i], pointsB[i]);
	return dist / pointsA.size();
}
QString PageItem_OSGFrame::getPDFMatrix(QString viewName)
{
    struct viewDefinition defaultView;
    defaultView = viewMap[viewName];
    osg::Vec3d trackerCenter = defaultView.trackerCenter;
    osg::Vec3d cameraPosition = defaultView.cameraPosition;
    osg::Vec3d cameraUp = defaultView.cameraUp;
    double viewx, viewy, viewz;
    double leftx, lefty, leftz;
    double upx, upy, upz;
    double transx, transy, transz;
    double roll = 0.0;
    double roo = getDistance(cameraPosition, trackerCenter);
    cameraPosition.normalize();
    cameraUp.normalize();
    viewx = -cameraPosition[0];
    viewy = -cameraPosition[1];
    viewz = -cameraPosition[2];
    if (viewx == 0.0 && viewy == 0.0 && viewz == 0.0)
    {
        viewy = 1.0;
    }
    leftx = -1.0f;
    lefty =  0.0f;
    leftz =  0.0f;
    if (viewz < 0.0) /* top view*/
    {
        upx = 0.0f;
        upy = 1.0f;
        upz = 0.0f;
    }
    else /* bottom view*/
    {
        upx = 0.0f;
        upy =-1.0f;
        upz = 0.0f;
    }
    if ( fabs(viewx) + fabs(viewy) != 0.0f) /* other views than top and bottom*/
    {
        cameraUp.normalize();
        upx = cameraUp[0];
        upy = cameraUp[1];
        upz = cameraUp[2];
        leftx = viewz*upy - viewy*upz;
        lefty = viewx*upz - viewz*upx;
        leftz = viewy*upx - viewx*upy;
        normalized(leftx, lefty, leftz);
    }
    /* apply camera roll*/
    {
        double leftxprime, leftyprime, leftzprime;
        double upxprime, upyprime, upzprime;
        double sinroll, cosroll;
        sinroll =  sin((roll/180.0f)*M_PI);
        cosroll =  cos((roll/180.0f)*M_PI);
        leftxprime = leftx*cosroll + upx*sinroll;
        leftyprime = lefty*cosroll + upy*sinroll;
        leftzprime = leftz*cosroll + upz*sinroll;
        upxprime = upx*cosroll + leftx*sinroll;
        upyprime = upy*cosroll + lefty*sinroll;
        upzprime = upz*cosroll + leftz*sinroll;
        leftx = leftxprime;
        lefty = leftyprime;
        leftz = leftzprime;
        upx = upxprime;
        upy = upyprime;
        upz = upzprime;
    }
    /* translation vector*/
    roo = fabs(roo);
    if (roo == 0.0)
    {
        roo = 0.000000000000000001;
    }
    transx = trackerCenter[0] - roo*viewx;
    transy = trackerCenter[1] - roo*viewy;
    transz = trackerCenter[2] - roo*viewz;
    if (fabs(leftx) < 0.0000001)
        leftx = 0.0;
    if (fabs(lefty) < 0.0000001)
        lefty = 0.0;
    if (fabs(leftz) < 0.0000001)
        leftz = 0.0;
    if (fabs(upx) < 0.0000001)
        upx = 0.0;
    if (fabs(upy) < 0.0000001)
        upy = 0.0;
    if (fabs(upz) < 0.0000001)
        upz = 0.0;
    if (fabs(transx) < 0.0000001)
        transx = 0.0;
    if (fabs(transy) < 0.0000001)
        transy = 0.0;
    if (fabs(transz) < 0.0000001)
        transz = 0.0;
    QString ret = "";
    QString desc4 = "%1 %2 %3 ";
    ret += desc4.arg(leftx).arg(lefty).arg(leftz);
    ret += desc4.arg(upx).arg(upy).arg(upz);
    ret += desc4.arg(viewx).arg(viewy).arg(viewz);
    ret += desc4.arg(transx).arg(transy).arg(transz);
    distanceToObj = roo;
    return ret;
}