Пример #1
0
void TattooMap::showCloseUp(int closeUpNum) {
	Events &events = *_vm->_events;
	Screen &screen = *_vm->_screen;

	// Reset scroll position
	screen._currentScroll = Common::Point(0, 0);

	// Get the closeup images
	Common::String fname = Common::String::format("res%02d.vgs", closeUpNum + 1);
	ImageFile pic(fname);

	Point32 closeUp(_data[closeUpNum].x * 100, _data[closeUpNum].y * 100);
	Point32 delta((SHERLOCK_SCREEN_WIDTH / 2 - closeUp.x / 100) * 100 / CLOSEUP_STEPS,
		(SHERLOCK_SCREEN_HEIGHT / 2 - closeUp.y / 100) * 100 / CLOSEUP_STEPS);
	Common::Rect oldBounds(closeUp.x / 100, closeUp.y / 100, closeUp.x / 100 + 1, closeUp.y / 100 + 1);
	int size = 64;
	int n = 256;
	int deltaVal = 512;
	bool minimize = false;
	int scaleVal, newSize;

	do {
		scaleVal = n;
		newSize = pic[0].sDrawXSize(n);

		if (newSize > size) {
			if (minimize)
				deltaVal /= 2;
			n += deltaVal;
		} else {
			minimize = true;
			deltaVal /= 2;
			n -= deltaVal;
			if (n < 1)
				n = 1;
		}
	} while (deltaVal && size != newSize);

	int deltaScale = (SCALE_THRESHOLD - scaleVal) / CLOSEUP_STEPS;

	for (int step = 0; step < CLOSEUP_STEPS; ++step) {
		Common::Point picSize(pic[0].sDrawXSize(scaleVal), pic[0].sDrawYSize(scaleVal));
		Common::Point pt(closeUp.x / 100 - picSize.x / 2, closeUp.y / 100 - picSize.y / 2);

		restoreArea(oldBounds);
		screen._backBuffer1.transBlitFrom(pic[0], pt, false, 0, scaleVal);

		screen.slamRect(oldBounds);
		screen.slamArea(pt.x, pt.y, picSize.x, picSize.y);

		oldBounds = Common::Rect(pt.x, pt.y, pt.x + picSize.x + 1, pt.y + picSize.y + 1);
		closeUp += delta;
		scaleVal += deltaScale;

		events.wait(1);
	}

	// Handle final drawing of closeup
	// TODO: Handle scrolling
	Common::Rect r(SHERLOCK_SCREEN_WIDTH / 2 - pic[0]._width / 2, SHERLOCK_SCREEN_HEIGHT / 2 - pic[0]._height / 2,
		SHERLOCK_SCREEN_WIDTH / 2 - pic[0]._width / 2 + pic[0]._width,
		SHERLOCK_SCREEN_HEIGHT / 2 - pic[0]._height / 2 + pic[0]._height);

	restoreArea(oldBounds);
	screen._backBuffer1.transBlitFrom(pic[0], Common::Point(r.left, r.top));
	screen.slamRect(oldBounds);
	screen.slamRect(r);
	events.wait(2);
}
Пример #2
0
void ZViewpoint::zviewpointHandleMsgTrackball( ZMsg *msg ) {
	static float viewpointMouseLast[2];
	static int dragging = 0;

	float newzviewpointScale = 0.f;
	int scaleChange = 0;

	if( (zmsgIs(type,ZUIMouseClickOn) || zmsgIs(type,MouseClick)) && zmsgIs(dir,D) && (zmsgIs(which,R) || zmsgIs(which,M)) && zmsgI(shift) && zmsgI(ctrl) && zmsgI(alt) ) {
		// RESET
		memset( &zviewpointTrans, 0, sizeof(zviewpointTrans) );
		zviewpointRotQuat.fromAxisAngle( FVec3::XAxis, 0.f );
		zviewpointScale = 1.f;
	}

	char button = msg->getS( "which", "X" ) [0]; 

//	if( (zmsgIs(type,ZUIMouseClickOn) || zmsgIs(type,MouseClick)) && zmsgIs(dir,D) && (  ( zmsgIs(which,M) && (zviewpointPermitRotX||zviewpointPermitRotY||zviewpointPermitRotZ) ) || zmsgIs(which,R)  ) ) {
	if( (zmsgIs(type,ZUIMouseClickOn) || zmsgIs(type,MouseClick)) && zmsgIs(dir,D) && (  ( button==zviewpointRotateButton && (zviewpointPermitRotX||zviewpointPermitRotY||zviewpointPermitRotZ) ) || button==zviewpointTranslateButton  ) ) {

		// I added the checks on permitrot but I think that this is probably temporay.  I probably need to put in
		// some kind of better mapping system so that calling code can assign the mappings that they want

		// I had commented out the M button for some reason probably because
		// it conflicted with something.  But I need it in Jarle.  So this probably
		// needs to turn into a option but I will leave it on until
		// I see what it is that needs it turned off.  Of course the
		// higher level thing could trap it and "zmsgUsed" to make ti disappear

		viewpointMouseLast[0] = zmsgF(x);
		viewpointMouseLast[1] = zmsgF(y);

		dragging = zMouseMsgRequestExclusiveDrag( "type=Viewpoint_MouseDrag" );
		if( dragging ) {
			zviewpointRotating = button == zviewpointRotateButton;
			zviewpointTranslating = button == zviewpointTranslateButton;
		}
		zMsgUsed();
	}
	else if( zmsgIs( type, KeyDown ) ) {
		if( zmsgIs( which, down ) )  {
			zviewpointRotateTrackball( 0.f, -zviewpointRotateStep );
			zMsgUsed();
		}
		if( zmsgIs( which, up ) )  {
			zviewpointRotateTrackball( 0.f, +zviewpointRotateStep );
			zMsgUsed();
		}
		if( zmsgIs( which, left ) )  {
			zviewpointRotateTrackball( +zviewpointRotateStep, 0.f );
			zMsgUsed();
		}
		if( zmsgIs( which, right ) )  {
			zviewpointRotateTrackball( -zviewpointRotateStep, 0.f );
			zMsgUsed();
		}
	}
	else if( (zmsgIs(type,Key) && zmsgIs(which,wheelforward)) || (zmsgIs(type,Key) && !strcmp(msg->getS("which"),",") ) ) {
		newzviewpointScale = zviewpointScale * 0.8f;
		scaleChange = 1;
		zMsgUsed();
	}
	else if( (zmsgIs(type,Key) && zmsgIs(which,wheelbackward)) || (zmsgIs(type,Key) && !strcmp(msg->getS("which"),".") ) ) {
		newzviewpointScale = zviewpointScale * 1.2f;
		scaleChange = 1;
		zMsgUsed();
	}

	if( scaleChange && zviewpointPermitScale ) {
		float x = (float)zMouseMsgX;
		float y = (float)zMouseMsgY;

		// I want the world coord at which the mouse is pointing before the zoom 
		// to be the same as the world coord at which the mouse is pointing after the zoom
		// @TODO: convert his mess into a single function
		DMat4 preScale = zviewpointReferenceModel;
        DMat4 preScaleMat( scale3D( DVec3(zviewpointScale, zviewpointScale, zviewpointScale) ) );
		preScale.cat( preScaleMat );

		DVec3 pre0, pre1;
		gluUnProject( x, y, 0.f, preScale, zviewpointReferenceProj, zviewpointReferenceViewport, &pre0.x, &pre0.y, &pre0.z );
		gluUnProject( x, y, 1.f, preScale, zviewpointReferenceProj, zviewpointReferenceViewport, &pre1.x, &pre1.y, &pre1.z );
		FVec3 wp0 = zviewpointLinePlaneIntersect( FVec3::Origin, FVec3::ZAxis, FVec3((float)pre0.x,(float)pre0.y,(float)pre0.z), FVec3((float)pre1.x,(float)pre1.y,(float)pre1.z) );

		DMat4 postScale = zviewpointReferenceModel;
        DMat4 postScaleMat = ( scale3D( DVec3(newzviewpointScale, newzviewpointScale, newzviewpointScale) ) );
		postScale.cat( postScaleMat );
		
		DVec3 post0, post1;
		gluUnProject( x, y, 0.f, postScale, zviewpointReferenceProj, zviewpointReferenceViewport, &post0.x, &post0.y, &post0.z );
		gluUnProject( x, y, 1.f, postScale, zviewpointReferenceProj, zviewpointReferenceViewport, &post1.x, &post1.y, &post1.z );
		FVec3 wp1 = zviewpointLinePlaneIntersect( FVec3::Origin, FVec3::ZAxis, FVec3((float)post0.x,(float)post0.y,(float)post0.z), FVec3((float)post1.x,(float)post1.y,(float)post1.z) );

		wp1.sub( wp0 );
		zviewpointTrans.add( wp1 );

		zviewpointScale = newzviewpointScale;
	}


	if( zmsgIs(type,Viewpoint_MouseDrag) ) {
		if( zmsgI(releaseDrag) ) {
			zMouseMsgCancelExclusiveDrag();
			zviewpointRotating = zviewpointTranslating = 0;
		}
		else {
			if( zviewpointRotating ) {
				float dx = +0.01f * ( viewpointMouseLast[0] - zmsgF(x) );
				float dy = -0.01f * ( viewpointMouseLast[1] - zmsgF(y) );
				float side = zmsgI( shift ) ? ( (zmsgF(localX) < zmsgF(w)/2) ? -1.f : 1.f ) : 0.f;
					// note: the side doesn't really work if the object is being rendered in a ZUI because the
					// w here refers to the screen, and not the ZUI.
				zviewpointRotateTrackball( dx, dy, side );
				viewpointMouseLast[0] = zmsgF(x);
				viewpointMouseLast[1] = zmsgF(y);
				zMsgUsed();
			}
//			else if( zmsgI(r) ) {
			else if( zviewpointTranslating ) {
				// COMPUTE how big is one pixel at the world z-plane of interest
				// For now, this plane normal to the camera and passes-though the origin
				// Do this by unprojecting rays at the mouse current and last and then
				// solving for the world position at the intersection of that plane

				// CAT in tranforms which take place before the translate
				DMat4 m = zviewpointReferenceModel;
                DMat4 _m( scale3D( DVec3(zviewpointScale, zviewpointScale, zviewpointScale) ) );
				m.cat( _m );
                DMat4 _m1( trans3D( DVec3(zviewpointTrans )) );
				m.cat( _m1 );

				DVec3 p0, p1, p2, p3;
				gluUnProject( zmsgF(x), zmsgF(y), 0.f, m, zviewpointReferenceProj, zviewpointReferenceViewport, &p0.x, &p0.y, &p0.z );
				gluUnProject( zmsgF(x), zmsgF(y), 1.f, m, zviewpointReferenceProj, zviewpointReferenceViewport, &p1.x, &p1.y, &p1.z );
				gluUnProject( viewpointMouseLast[0], viewpointMouseLast[1], 0.f, m, zviewpointReferenceProj, zviewpointReferenceViewport, &p2.x, &p2.y, &p2.z );
				gluUnProject( viewpointMouseLast[0], viewpointMouseLast[1], 1.f, m, zviewpointReferenceProj, zviewpointReferenceViewport, &p3.x, &p3.y, &p3.z );
				FVec3 wp0 = zviewpointLinePlaneIntersect( FVec3::Origin, FVec3::ZAxis, FVec3((float)p0.x,(float)p0.y,(float)p0.z), FVec3((float)p1.x,(float)p1.y,(float)p1.z) );
				FVec3 wp1 = zviewpointLinePlaneIntersect( FVec3::Origin, FVec3::ZAxis, FVec3((float)p2.x,(float)p2.y,(float)p2.z), FVec3((float)p3.x,(float)p3.y,(float)p3.z) );
				wp0.sub( wp1 );

				FVec3 delta( wp0.x, wp0.y, 0.f );

				if( zmsgI(shift) ) {
					delta.x = 0.f;
					delta.y = 0.f;
					delta.z = wp0.y * 4.f;
				}

				zviewpointTrans.add( delta );

				viewpointMouseLast[0] = zmsgF(x);
				viewpointMouseLast[1] = zmsgF(y);
				zMsgUsed();
			}
		}
	}
}
Пример #3
0
void Law2_ScGeom_CFpmPhys_CohesiveFrictionalPM::go(shared_ptr<IGeom>& ig, shared_ptr<IPhys>& ip, Interaction* contact){
	ScGeom* geom = static_cast<ScGeom*>(ig.get()); 
	CFpmPhys* phys = static_cast<CFpmPhys*>(ip.get());
	const int &id1 = contact->getId1();
	const int &id2 = contact->getId2();
	Body* b1 = Body::byId(id1,scene).get();
	Body* b2 = Body::byId(id2,scene).get();
	
	Real displN = geom->penetrationDepth; // NOTE: the sign for penetrationdepth is different from ScGeom and Dem3DofGeom: geom->penetrationDepth>0 when spheres interpenetrate
	Real Dtensile=phys->FnMax/phys->kn;
	Real Dsoftening = phys->strengthSoftening*Dtensile; 
	
	/*to set the equilibrium distance between all cohesive elements when they first meet -> allows one to work with initial stress-free assembly*/
	if ( contact->isFresh(scene) ) { phys->initD = displN; phys->normalForce = Vector3r::Zero(); phys->shearForce = Vector3r::Zero();}
	Real D = displN - phys->initD; // interparticular distance is computed depending on the equilibrium distance

	/* Determination of interaction */
	if (D < 0){ //spheres do not touch 
	  if (!phys->isCohesive){ scene->interactions->requestErase(contact); return; } // destroy the interaction before calculation
	  if ((phys->isCohesive) && (abs(D) > (Dtensile + Dsoftening))) { // spheres are bonded and the interacting distance is greater than the one allowed ny the defined cohesion
	    phys->isCohesive=false; 
	    // update body state with the number of broken bonds
	    CFpmState* st1=dynamic_cast<CFpmState*>(b1->state.get());
	    CFpmState* st2=dynamic_cast<CFpmState*>(b2->state.get());
	    st1->numBrokenCohesive+=1;
	    st2->numBrokenCohesive+=1;
	    //// the same thing but from ConcretePM
	    //const shared_ptr<Body>& body1=Body::byId(contact->getId1(),scene), body2=Body::byId(contact->getId2(),scene); assert(body1); assert(body2);
	    //const shared_ptr<CFpmState>& st1=YADE_PTR_CAST<CFpmState>(body1->state), st2=YADE_PTR_CAST<CFpmState>(body2->state);
	    //{ boost::mutex::scoped_lock lock(st1->updateMutex); st1->numBrokenCohesive+=1; }
	    //{ boost::mutex::scoped_lock lock(st2->updateMutex); st2->numBrokenCohesive+=1; }
	    // end of update
	    scene->interactions->requestErase(contact); return;
	  }
	}	  
	
	/*NormalForce*/
	Real Fn=0, Dsoft=0;
		
	if ((D < 0) && (abs(D) > Dtensile)) { //to take into account strength softening
	  Dsoft = D+Dtensile; // Dsoft<0 for a negative value of Fn (attractive force)
	  Fn = -(phys->FnMax+(phys->kn/phys->strengthSoftening)*Dsoft); // computes FnMax - FnSoftening
	}
	else {
	  Fn = phys->kn*D;
	}
	phys->normalForce = Fn*geom->normal;  // NOTE normal is position2-position1 - It is directed from particle1 to particle2
	        
	/*ShearForce*/
	Vector3r& shearForce = phys->shearForce; 
		
	// using scGeom function rotateAndGetShear	
	State* st1 = Body::byId(id1,scene)->state.get();
	State* st2 = Body::byId(id2,scene)->state.get();

	geom->rotate(phys->shearForce);
	const Vector3r& dus = geom->shearIncrement();
	
	//Linear elasticity giving "trial" shear force
	shearForce -= phys->ks*dus;
	// needed for the next timestep
	phys->prevNormal = geom->normal;
		
	/* Morh-Coulomb criterion */
	Real maxFs = phys->FsMax + Fn*phys->tanFrictionAngle;

	if (shearForce.squaredNorm() > maxFs*maxFs){ 
	  shearForce*=maxFs/shearForce.norm(); // to fix the shear force to its yielding value
	}
	
	/* Apply forces */
	Vector3r f = phys->normalForce + shearForce;
	// these lines to adapt to periodic boundary conditions (NOTE applyForceAtContactPoint computes torque induced by normal and shear force too)
	if (!scene->isPeriodic)  
	applyForceAtContactPoint(f , geom->contactPoint , id2, st2->se3.position, id1, st1->se3.position);
	else { // in scg we do not wrap particles positions, hence "applyForceAtContactPoint" cannot be used when scene is periodic
		scene->forces.addForce(id1,-f);
		scene->forces.addForce(id2,f);
		scene->forces.addTorque(id1,(geom->radius1-0.5*geom->penetrationDepth)* geom->normal.cross(-f));
		scene->forces.addTorque(id2,(geom->radius2-0.5*geom->penetrationDepth)* geom->normal.cross(-f));
	}
	
	/* Moment Rotation Law */
	// NOTE this part could probably be computed in ScGeom to avoid copy/paste multiplication !!!
	Quaternionr delta( b1->state->ori * phys->initialOrientation1.conjugate() *phys->initialOrientation2 * b2->state->ori.conjugate()); delta.normalize(); //relative orientation
	AngleAxisr aa(delta); // axis of rotation - this is the Moment direction UNIT vector; angle represents the power of resistant ELASTIC moment
	if(aa.angle() > Mathr::PI) aa.angle() -= Mathr::TWO_PI; // angle is between 0 and 2*pi, but should be between -pi and pi 
	  
	phys->cumulativeRotation = aa.angle();
	  
	//Find angle*axis. That's all.  But first find angle about contact normal. Result is scalar. Axis is contact normal.
	Real angle_twist(aa.angle() * aa.axis().dot(geom->normal) ); //rotation about normal
	Vector3r axis_twist(angle_twist * geom->normal);
	Vector3r moment_twist(axis_twist * phys->kr);
	  
	Vector3r axis_bending(aa.angle()*aa.axis() - axis_twist); //total rotation minus rotation about normal
	Vector3r moment_bending(axis_bending * phys->kr);
	Vector3r moment = moment_twist + moment_bending;
	
	Real MomentMax = phys->maxBend*std::fabs(phys->normalForce.norm());
	Real scalarMoment = moment.norm();

	/*Plastic moment */
	if(scalarMoment > MomentMax) 
	{
	  Real ratio = 0;
	  ratio *= MomentMax/scalarMoment; // to fix the moment to its yielding value
	  moment *= ratio;		
	  moment_twist *=  ratio;
	  moment_bending *= ratio;
	}

	phys->moment_twist = moment_twist;
	phys->moment_bending = moment_bending;
	  
	scene->forces.addTorque(id1,-moment);
	scene->forces.addTorque(id2, moment);

}
Пример #4
0
/* We resolve the second subproblem through sky-plane projection */
Sequence second_subproblem (Tensor5D& W_1, Tensor5D& W_2, Tensor5D& Y, double& mu, SequenceSet& allSeqs, vector<int> lenSeqs) {
    /*{{{*/
    int numSeq = allSeqs.size();
    int T2 = W_2[0][0].size();
    // reinitialize W_2 to all-zero matrix
    for (int n = 0; REINIT_W_ZERO_TOGGLE and n < numSeq; n ++) {
        int T1 = W_2[n].size();
        for (int i = 0; i < T1; i ++)  
            for (int j = 0; j < T2; j ++) 
                for (int d = 0; d < NUM_DNA_TYPE; d ++) 
                    for (int m = 0; m < NUM_MOVEMENT; m ++) 
                        W_2[n][i][j][d][m] = 0.0;
    }

    vector<Tensor4D> delta (numSeq, Tensor4D(0, Tensor(T2, Matrix(NUM_DNA_TYPE,
                        vector<double>(NUM_MOVEMENT, 0.0)))));  
    tensor5D_init (delta, allSeqs, lenSeqs, T2);
    Tensor tensor (T2, Matrix (NUM_DNA_TYPE, vector<double>(NUM_DNA_TYPE, 0.0)));
    Matrix mat_insertion (T2, vector<double>(NUM_DNA_TYPE, 0.0));

    Trace trace (0, Cell(2)); // 1d: j, 2d: ATCG
    int fw_iter = -1;
    while (fw_iter < MAX_2nd_FW_ITER) {
        fw_iter ++;
        // 1. compute delta
#ifdef PARRALLEL_COMPUTING
//#pragma omp parallel for
#endif
        for (int n = 0; n < numSeq; n ++) {
            int T1 = W_2[n].size();
            for (int i = 0; i < T1; i ++) { 
                for (int j = 0; j < T2; j ++) 
                    for (int d = 0; d < NUM_DNA_TYPE; d ++) 
                        for (int m = 0; m < NUM_MOVEMENT; m ++) {
                            delta[n][i][j][d][m] = -1.0* mu * (W_2[n][i][j][d][m] - W_1[n][i][j][d][m]) + Y[n][i][j][d][m];
#ifdef SECOND_SUBPROBLEM_DEBUG
                            if (delta[n][i][j][d][m] > 0)
                                cout <<"delta: " << n << "," << i << "," << j << "," << d  << "," << m << ": "
                                    << delta[n][i][j][d][m] << endl;
#endif
                            if (m == DELETION_A or m == MATCH_A)
                                tensor[j][d][dna2T3idx('A')] += max(0.0, delta[n][i][j][d][m]);
                            else if (m == DELETION_T or m == MATCH_T)
                                tensor[j][d][dna2T3idx('T')] += max(0.0, delta[n][i][j][d][m]);
                            else if (m == DELETION_C or m == MATCH_C)
                                tensor[j][d][dna2T3idx('C')] += max(0.0, delta[n][i][j][d][m]);
                            else if (m == DELETION_G or m == MATCH_G)
                                tensor[j][d][dna2T3idx('G')] += max(0.0, delta[n][i][j][d][m]);
                            else if (m == DELETION_START or m == MATCH_START)
                                tensor[j][d][dna2T3idx('*')] += max(0.0, delta[n][i][j][d][m]);
                            else if (m == DELETION_END or m == MATCH_END)
                                tensor[j][d][dna2T3idx('#')] += max(0.0, delta[n][i][j][d][m]);
                            else if (m == INSERTION) {
                                mat_insertion[j][d] += max(0.0, delta[n][i][j][d][m]);
                            }
                        }
            }
        }
#ifdef SECOND_SUBPROBLEM_DEBUG
        cout << "tensor transition input list:" << endl;
        for (int j = 0; j < T2; j ++) 
            for (int d = 0; d < NUM_DNA_TYPE; d ++) 
                for (int k = 0; k < NUM_DNA_TYPE; k ++) {
                    if (tensor[j][d][k] > 0)
                        cout << "(" << j << ", " << d << ", " << k << ")=" << tensor[j][d][k] << endl;
                }
#endif

        double delta_square = 0.0;
        for (int n = 0; n < numSeq; n ++) 
            delta_square += tensor4D_frob_prod (delta[n], delta[n]);
        //cout << "delta_square: " << delta_square << endl;
        if ( delta_square < 1e-12 ) {
            //cout << "small delta. early stop." << endl;
            break;
        }

        // 2. determine the trace: run viterbi algorithm
        trace.clear();
	refined_viterbi_algo (trace, tensor, mat_insertion);
        Tensor5D S (numSeq, Tensor4D(0, Tensor(T2, Matrix(NUM_DNA_TYPE, vector<double>(NUM_MOVEMENT, 0.0))))); 
        tensor5D_init (S, allSeqs, lenSeqs, T2);

        // 3. recover values for S 
        // 3b. set a number of selected elements to 1
        for (int t = 0; t < trace.size(); t++) {
            int sj = trace[t].location[0];
            int sd = trace[t].location[1];
            int sm = dna2T3idx(trace[t].acidB);
            // cout << trace[t].acidB;
            for (int n = 0; n < numSeq; n ++) {
                int T1 = S[n].size();
                for (int i = 0; i < T1; i ++) {
                    for (int m = 0; m < NUM_MOVEMENT; m ++)
                        if (delta[n][i][sj][sd][m] > 0.0) { 
                            if (m == DEL_BASE_IDX + sm or m == MTH_BASE_IDX + sm)
                                S[n][i][sj][sd][m] = 1.0;
                            else if (m == INSERTION and trace[t].action == INSERTION) {
                                S[n][i][sj][sd][m] = 1.0;
                            }
                        }
                }
            }
        }
        // cout <<  endl;

#ifdef SECOND_SUBPROBLEM_DEBUG
        cout << "Result of viterbi:" << endl;
        for (int t = 0; t < trace.size(); t++) 
            cout << "(" <<  trace[t].location[0] << ", " << trace[t].acidA << ", "<< trace[t].acidB << ")=" << trace[t].score << endl;
        double S_s = 0.0;
        for (int n = 0; n < numSeq; n ++) 
            S_s += tensor4D_frob_prod (S[n], S[n]);
        cout << "S_s: " << S_s << endl;
        for (int n = 0; n < numSeq; n ++) 
            tensor4D_dump(S[n]);
#endif

        // 4. Exact Line search: determine the optimal step size \gamma
        // gamma = [ ( Y_2 + mu*W - mu*Z ) dot (W_2 - S) ] / || W_2 - S ||^2
        //           ---------------combo------------------
        double numerator = 0.0, denominator = 0.0;
        for (int n = 0; n < numSeq; n ++) {
            int T1 = S[n].size();
            for (int i = 0; i < T1; i ++) 
                for (int j = 0; j < T2; j ++) 
                    for (int d = 0; d < NUM_DNA_TYPE; d ++) 
                        for (int m = 0; m < NUM_MOVEMENT; m ++) {
                            double wms = W_2[n][i][j][d][m] - S[n][i][j][d][m];
                            numerator += (-1.0*Y[n][i][j][d][m] + mu*W_2[n][i][j][d][m] - mu*W_1[n][i][j][d][m]) * wms;
                            denominator += mu * wms * wms;
                        }
        }
#ifdef SECOND_SUBPROBLEM_DEBUG
        cout << "numerator: " << numerator << ", denominator: " << denominator << endl;
#endif
        if ( denominator < 10e-6) {
            //cout << "small denominator: " << denominator << endl;
            break;
        }
        double gamma = numerator / denominator;
        if (fw_iter == 0) gamma = 1.0;
        gamma = max(gamma, 0.0);
        gamma = min(gamma, 1.0);
        // cout << "gamma: " << gamma << ", mu*||W-S||^2: " << denominator << endl;

        // 3. update W
        for (int n = 0; n < numSeq; n ++) {
            int T1 = S[n].size();
            for (int i = 0; i < T1; i ++) 
                for (int j = 0; j < T2; j ++) 
                    for (int d = 0; d < NUM_DNA_TYPE; d ++) 
                        for (int m = 0; m < NUM_MOVEMENT; m ++)
                            W_2[n][i][j][d][m] = (1-gamma) * W_2[n][i][j][d][m] + gamma* S[n][i][j][d][m];
        }

        // 4. output iteration tracking info
        // second_subproblem_log(fw_iter, W, Z, Y, mu);
        // 5. early stop condition
        if (fabs(gamma) < EPS_2nd_FW) break; 
    }
    
    Sequence recSeq;
    for (int t = 0; t < trace.size(); t++) 
        recSeq.push_back(trace[t].acidB);
    return recSeq;
    /*}}}*/
}
void Foam::inclinedFilmNusseltHeightFvPatchScalarField::updateCoeffs()
{
    if (updated())
    {
        return;
    }

    const label patchI = patch().index();

    const scalar t = db().time().timeOutputValue();

    // retrieve the film region from the database

    const regionModels::regionModel& region =
        db().time().lookupObject<regionModels::regionModel>
        (
            "surfaceFilmProperties"
        );

    const regionModels::surfaceFilmModels::kinematicSingleLayer& film =
        dynamic_cast
        <
            const regionModels::surfaceFilmModels::kinematicSingleLayer&
        >(region);

    // calculate the vector tangential to the patch

    const vectorField n(patch().nf());

    const volVectorField& nHat = film.nHat();

    const vectorField nHatp(nHat.boundaryField()[patchI].patchInternalField());

    vectorField nTan(nHatp ^ n);
    nTan /= mag(nTan) + ROOTVSMALL;

    // calculate distance in patch tangential direction

    const vectorField& Cf = patch().Cf();
    scalarField d(nTan & Cf);

    // TODO: currently re-evaluating the entire gTan field to return this patch
    const scalarField gTan(film.gTan()().boundaryField()[patchI] & n);

    if (patch().size() && (max(mag(gTan)) < SMALL))
    {
       WarningIn
        (
            "void Foam::inclinedFilmNusseltHeightFvPatchScalarField::"
            "updateCoeffs()"
        )
            << "Tangential gravity component is zero.  This boundary condition "
            << "is designed to operate on patches inclined with respect to "
            << "gravity"
            << nl;
    }

    const volScalarField& mu = film.mu();
    // The use of the first internal cell for properties doesn't seem correct, kvm
    const scalarField mup(mu.boundaryField()[patchI].patchInternalField());
    // const scalarField mup(mu.boundaryField()[patchI]);

    const volScalarField& rho = film.rho();
    const scalarField rhop(rho.boundaryField()[patchI].patchInternalField());
    // const scalarField rhop(rho.boundaryField()[patchI]);
    
    // calculate the wavy film height

    const scalar GMean = GammaMean_->value(t);
    const scalar a = a_->value(t);
    const scalar omega = omega_->value(t);


    // solve for deltaMean via Bi-Section method
    scalar fxC = 10.0;
    scalar tol = 0.00001;
    label iter=0;
    scalar deltaMeanA = 2e-2;
    scalar deltaMeanB = 2e-6;
    scalar deltaMeanC;

    //  Info << " acoeff " << a << nl;
    scalarField C(pow(3.0*sqr(mup/rhop)/mup/(-gTan + ROOTVSMALL), 0.33333333));
    scalarField delta(deltaMeanA + a*sin(omega*constant::mathematical::twoPi*d));

    while(fabs(fxC)>tol){

        label deltaSize = delta.size();
        reduce(deltaSize, sumOp<label>());
        delta = (deltaMeanA + a*sin(omega*constant::mathematical::twoPi*d));
        scalar fxA = GMean - gSum(pow(delta/C,3))/deltaSize; 
        // DEBUG(delta.size());
        // DEBUG(deltaSize);
        if(fxA > 0.0){
            WarningIn
                (
                 "void Foam::inclinedFilmNusseltHeightFvPatchScalarField::"
                 "updateCoeffs()"
                )
                << "Initial guess for deltaMeanA too low:"
                << deltaMeanA
                << nl;
        }


        delta = (deltaMeanB + a*sin(omega*constant::mathematical::twoPi*d));
        scalar fxB = GMean - gSum(pow(delta/C,3))/deltaSize;

        if(fxB < 0.0){
            WarningIn
                (
                 "void Foam::inclinedFilmNusseltHeightFvPatchScalarField::"
                 "updateCoeffs()"
                )
                << "Initial guess for deltaMeanB too high:"
                << deltaMeanB
                << nl;
        }
        //  Info << "fxA " << fxA << nl;
        //  Info << "fxB " << fxB << nl;

        deltaMeanC = 0.5*(deltaMeanA+deltaMeanB);

        delta = (deltaMeanC + a*sin(omega*constant::mathematical::twoPi*d));
        fxC = GMean - gSum(pow(delta/C,3))/deltaSize;

        //  Info << iter << " fxC " << fxC << nl;

        if( fxC < 0.0 ) {
            deltaMeanA = deltaMeanC;
        }
        else{
            deltaMeanB = deltaMeanC;
        }
        iter++;
        if(iter>1e5){
            WarningIn
                (
                 "void Foam::inclinedFilmNusseltHeightFvPatchScalarField::"
                 "updateCoeffs()"
                )
                << "Maximum number of bisection method iterations reached."
                << nl;
            break;
        }
    }

    scalar deltaMean = deltaMeanC;
    delta = (deltaMean + a*sin(omega*constant::mathematical::twoPi*d));
    //  Info << "delta " << delta << nl;

    // scalarField G(GMean + GMean*a*sin(omega*constant::mathematical::twoPi*d));
    
    // correction to mean 
    // scalar uncorrectedMean = gSum(G)/G.size();
    // DEBUG(uncorrectedMean);
    // G *= GMean/(uncorrectedMean+SMALL);

    // set internal values
    // volScalarField& rho2 = const_cast<volScalarField&>(film.rho());
    // const labelUList& faceCells = patch().faceCells();
    // forAll(faceCells,i)
    // {
    //     label cellI = faceCells[i];
    //     rho2[cellI] = 1.0;
    // }
    // Info << rho2 << nl;

    scalarField G(pow(delta/C,3));

    const scalarField Re(max(G, 0.0)/mup);

    // DEBUG(mup[0]);
    // DEBUG(rhop[0]);
    // DEBUG(gTan[0]);
    // DEBUG(Re[0]);
    // DEBUG(G[0]);
    // const scalarField h(pow(3.0*sqr(mup/rhop)/(-gTan + ROOTVSMALL), 0.33333333)*pow(Re, 0.33333333));
    // DEBUG(h[0]);

    operator==
    (
        pow(3.0*sqr(mup/rhop)/(-gTan + ROOTVSMALL), 0.33333333)*pow(Re, 0.33333333)
    );

    fixedValueFvPatchScalarField::updateCoeffs();
}
Пример #6
0
    void newton_raphson_constrained_system_method_test()
    {
      typedef eli::mutil::nls::newton_raphson_constrained_system_method<data__, 3, 1> nrcs_type;

      data__ delta(std::sqrt(std::numeric_limits<data__>::epsilon()));
      nrcs_type nrcm;
      typename nrcs_type::solution_matrix rhs, root, x0, x_exact;
      int stat;

      nrcm.set_absolute_tolerance(delta);
      nrcm.set_max_iteration(200);
      nrcm.set_norm_type(nrcs_type::max_norm);
      nrcm.set_lower_condition(0, 0, nrcs_type::NRC_EXCLUSIVE);
      nrcm.set_upper_condition(0, 4, nrcs_type::NRC_EXCLUSIVE);

      // decoupled system
      // set right hand side, initial guess & exact answer
      x_exact << 2, 3, 1;
      rhs = my_decoupled_system_function<data__>(x_exact);
      x0 << 1.5, 2.5, 1.5;
      nrcm.set_initial_guess(x0);

      // test using user defined functions
      stat = nrcm.find_root(root, std::ptr_fun(my_decoupled_system_function<data__>), std::ptr_fun(my_decoupled_system_function_derivative<data__>), rhs);
      TEST_ASSERT(stat==nrcs_type::converged);
      TEST_ASSERT(nrcm.get_iteration_count()<nrcm.get_max_iteration());
      TEST_ASSERT((x_exact-root).norm()<=2*delta);

      nrcm.set_max_iteration(2);
      stat = nrcm.find_root(root, std::ptr_fun(my_decoupled_system_function<data__>), std::ptr_fun(my_decoupled_system_function_derivative<data__>), rhs);
      TEST_ASSERT(stat==nrcs_type::max_iteration);

      // test using functor
      nrcm.set_absolute_tolerance(delta);
      nrcm.set_max_iteration(200);
      nrcm.set_initial_guess(x0);

      stat = nrcm.find_root(root, my_decoupled_system_functor<data__>(), my_decoupled_system_functor_derivative<data__>(), rhs);
      TEST_ASSERT(stat==nrcs_type::converged);
      TEST_ASSERT(nrcm.get_iteration_count()<nrcm.get_max_iteration());
      TEST_ASSERT((x_exact-root).norm()<=2*delta);

      // linear coupled system
      // set right hand side, initial guess & exact answer
      x_exact << 2, 3, 1;
      rhs = my_coupled_linear_system_function<data__>(x_exact);
      x0 << 1.5, 2.5, 1.5;
      nrcm.set_initial_guess(x0);

      // test using user defined functions
      stat = nrcm.find_root(root, std::ptr_fun(my_coupled_linear_system_function<data__>), std::ptr_fun(my_coupled_linear_system_function_derivative<data__>), rhs);
      TEST_ASSERT(stat==nrcs_type::converged);
      TEST_ASSERT(nrcm.get_iteration_count()<2);
      TEST_ASSERT((x_exact-root).norm()<delta);

      // test using functor
      nrcm.set_absolute_tolerance(delta);
      nrcm.set_max_iteration(200);
      nrcm.set_initial_guess(x0);

      stat = nrcm.find_root(root, my_coupled_linear_system_functor<data__>(), my_coupled_linear_system_functor_derivative<data__>(), rhs);
      TEST_ASSERT(stat==nrcs_type::converged);
      TEST_ASSERT(nrcm.get_iteration_count()<2);
      TEST_ASSERT((x_exact-root).norm()<delta);

      // nonlinear coupled system
      // set right hand side, initial guess & exact answer
      x_exact << 2, 3, 1;
      rhs = my_coupled_nonlinear_system_function<data__>(x_exact);
      x0 << 1.5, 2.5, 1.5;
      nrcm.set_initial_guess(x0);

      // test using user defined functions
      stat = nrcm.find_root(root, std::ptr_fun(my_coupled_nonlinear_system_function<data__>), std::ptr_fun(my_coupled_nonlinear_system_function_derivative<data__>), rhs);
      TEST_ASSERT(stat==nrcs_type::converged);
      TEST_ASSERT(nrcm.get_iteration_count()<nrcm.get_max_iteration());
      TEST_ASSERT((x_exact-root).norm()<delta);

      // test using functor
      nrcm.set_absolute_tolerance(delta);
      nrcm.set_max_iteration(200);
      nrcm.set_initial_guess(x0);

      stat = nrcm.find_root(root, my_coupled_nonlinear_system_functor<data__>(), my_coupled_nonlinear_system_functor_derivative<data__>(), rhs);
      TEST_ASSERT(stat==nrcs_type::converged);
      TEST_ASSERT(nrcm.get_iteration_count()<nrcm.get_max_iteration());
      TEST_ASSERT((x_exact-root).norm()<delta);
    }
void vmsTrafficUsageModeMgr::ApplySpeedLimitForItems(bool bForDownload, ManageForSpeedItemsList *pItems, UINT64 uLimit, bool bIsHighestPriorityItems, UINT64* puUnusedLimit)
{
	LOGFN ("vmsTrafficUsageModeMgr::ApplySpeedLimitForItems");

	assert (puUnusedLimit != NULL);

	pItems->state &= ~ManageForSpeedItemsList::MSILS_USES_ALL_BANDWIDTH_PROVIDED;

	if (pItems->vItems.empty ())
	{
		*puUnusedLimit = uLimit;
		return;
	}

	size_t cProcessed = 0; 
	std::vector <bool> vProcessed; 
	vProcessed.assign (pItems->vItems.size (), false);
	std::vector <UINT64> vLimits; 
	vLimits.assign (pItems->vItems.size (), 0);

	UINT64 uEatenTotal = 0;

	
	
	bool bMaxLimitPerOneMustBeRecalculated = true;

	while (bMaxLimitPerOneMustBeRecalculated) 
	{
		UINT64 uMaxLimitPerOne = uLimit == UINT64_MAX ? UINT64_MAX : (uLimit - uEatenTotal) / (vProcessed.size () - cProcessed);
		bMaxLimitPerOneMustBeRecalculated = false;		

		for (size_t i = 0; i < pItems->vItems.size (); i++) 
		{
			if (vProcessed [i])
				continue;

			ManageForSpeedItem *pItem = &pItems->vItems [i];

			if (!pItem->pDldr->isRequiresTraffic (bForDownload))
			{
				vProcessed [i] = true;
				
				
				
				vLimits [i] = uMaxLimitPerOne;
				uEatenTotal += min (pItem->pDldr->getSpeed (bForDownload), uMaxLimitPerOne);
				
				cProcessed++;
				bMaxLimitPerOneMustBeRecalculated = cProcessed != vProcessed.size ();
				continue;
			}

			UINT64 uMaxLimitForThis = uMaxLimitPerOne;
			if (!uMaxLimitForThis)
				uMaxLimitForThis = 1;
			if (pItem->pDldr->getInternalSpeedLimit (bForDownload) < uMaxLimitForThis)
				uMaxLimitForThis = pItem->pDldr->getInternalSpeedLimit (bForDownload);
			if (pItem->pDldr->isIgnoreAllSpeedLimits (bForDownload))
				uMaxLimitForThis = UINT64_MAX;
			if (uMaxLimitForThis < 100 && !pItem->pDldr->isResumeSupported (bForDownload))
				uMaxLimitForThis = 100;

			UINT64 uCurrentLimit = pItem->pDldr->getSpeedLimit (bForDownload);
			UINT64 uCurrentMaximumSpeed = pItem->getData (bForDownload).vSpeed.getCurrentMaximumValue ();

			
			if (uCurrentLimit <= uMaxLimitForThis && 
				uCurrentMaximumSpeed < uCurrentLimit / 1.1)
			{
				
				
				
				vLimits [i] = uMaxLimitForThis;
				uEatenTotal += uCurrentMaximumSpeed; 
				if (uEatenTotal > uLimit)
					uEatenTotal = uLimit; 
				vProcessed [i] = true;
				cProcessed++;
				bMaxLimitPerOneMustBeRecalculated = cProcessed != vProcessed.size ();
				continue;
			}

			if (!bMaxLimitPerOneMustBeRecalculated)
				vLimits [i] = uMaxLimitForThis;
		}
	}

	

	if (cProcessed != vProcessed.size ())
	{
		for (size_t i = 0; i < pItems->vItems.size (); i++)
		{
			if (vProcessed [i])
				continue;
			if (vLimits [i] == UINT64_MAX)
			{
				uEatenTotal = UINT64_MAX;
				break;
			}
			uEatenTotal += vLimits [i]; 
		}
	}

	if (uEatenTotal > uLimit)
		uEatenTotal = uLimit; 

	

	for (size_t i = 0; i < pItems->vItems.size (); i++)
	{
		LOG ("set limit of %I64d for %i item", vLimits [i], i);
		pItems->vItems [i].pDldr->setSpeedLimit (bForDownload, vLimits [i]);
	}

	

	NetworkStat& ns = refgetNetworkStat (bForDownload);

	
	UINT64 uLimit2 = uLimit;

	if (bIsHighestPriorityItems)
	{
		
		if (ns.uCurrentBandwidth < uLimit2)
		{
			uLimit2 = ns.uCurrentBandwidth;
			if (uEatenTotal != UINT64_MAX && uEatenTotal > uLimit2)
				uEatenTotal = uLimit2;
		}
	}

	if (uEatenTotal != UINT64_MAX)
	{
		
		uEatenTotal *= 1.05;
		if (uEatenTotal > uLimit2)
			uEatenTotal = uLimit2;

		if (uLimit2 != UINT64_MAX)
		{
			if (uEatenTotal != uLimit2)
			{
				
				if (uLimit2 / delta (uLimit2, uEatenTotal) >= 10)
					uEatenTotal = uLimit2; 
			}
		}
	}

	if (pItems->totalSpeedExplorer.isExploring ())
	{
		if (uEatenTotal != UINT64_MAX)
		{
			
			uEatenTotal += pItems->totalSpeedExplorer.getAdjustingValue ();
			if (uEatenTotal > uLimit2)
				uEatenTotal = uLimit2;
		}
	}

	*puUnusedLimit = uLimit2 > uEatenTotal ? uLimit2 - uEatenTotal : 0;

	if (*puUnusedLimit == 0)
		pItems->state |= ManageForSpeedItemsList::MSILS_USES_ALL_BANDWIDTH_PROVIDED;

	if (ns.currentBandwidthExplorer.isExploring ())
	{
		*puUnusedLimit += ns.currentBandwidthExplorer.getAdjustingValue ();
		if (*puUnusedLimit > uLimit)
		{
			assert (uEatenTotal <= uLimit);
			*puUnusedLimit = uLimit - uEatenTotal;
		}
	}
}
Пример #8
0
bool Scrollbar::gestureEvent(const PlatformGestureEvent& evt,
                             bool* shouldUpdateCapture) {
  DCHECK(shouldUpdateCapture);
  switch (evt.type()) {
    case PlatformEvent::GestureTapDown:
      setPressedPart(theme().hitTest(*this, evt.position()));
      m_pressedPos = orientation() == HorizontalScrollbar
                         ? convertFromRootFrame(evt.position()).x()
                         : convertFromRootFrame(evt.position()).y();
      *shouldUpdateCapture = true;
      return true;
    case PlatformEvent::GestureTapDownCancel:
      if (m_pressedPart != ThumbPart)
        return false;
      m_scrollPos = m_pressedPos;
      return true;
    case PlatformEvent::GestureScrollBegin:
      switch (evt.source()) {
        case PlatformGestureSourceTouchpad:
          // Update the state on GSB for touchpad since GestureTapDown
          // is not generated by that device. Touchscreen uses the tap down
          // gesture since the scrollbar enters a visual active state.
          *shouldUpdateCapture = true;
          setPressedPart(NoPart);
          m_pressedPos = 0;
          return true;
        case PlatformGestureSourceTouchscreen:
          if (m_pressedPart != ThumbPart)
            return false;
          m_scrollPos = m_pressedPos;
          return true;
        default:
          ASSERT_NOT_REACHED();
          return true;
      }
      break;
    case PlatformEvent::GestureScrollUpdate:
      switch (evt.source()) {
        case PlatformGestureSourceTouchpad: {
          FloatSize delta(-evt.deltaX(), -evt.deltaY());
          if (m_scrollableArea &&
              m_scrollableArea->userScroll(evt.deltaUnits(), delta)
                  .didScroll()) {
            return true;
          }
          return false;
        }
        case PlatformGestureSourceTouchscreen:
          if (m_pressedPart != ThumbPart)
            return false;
          m_scrollPos += orientation() == HorizontalScrollbar ? evt.deltaX()
                                                              : evt.deltaY();
          moveThumb(m_scrollPos, false);
          return true;
        default:
          ASSERT_NOT_REACHED();
          return true;
      }
      break;
    case PlatformEvent::GestureScrollEnd:
    case PlatformEvent::GestureLongPress:
    case PlatformEvent::GestureFlingStart:
      m_scrollPos = 0;
      m_pressedPos = 0;
      setPressedPart(NoPart);
      return false;
    case PlatformEvent::GestureTap: {
      if (m_pressedPart != ThumbPart && m_pressedPart != NoPart &&
          m_scrollableArea &&
          m_scrollableArea
              ->userScroll(
                  pressedPartScrollGranularity(),
                  toScrollDelta(pressedPartScrollDirectionPhysical(), 1))
              .didScroll()) {
        return true;
      }
      m_scrollPos = 0;
      m_pressedPos = 0;
      setPressedPart(NoPart);
      return false;
    }
    default:
      // By default, we assume that gestures don't deselect the scrollbar.
      return true;
  }
}
Пример #9
0
bool Weapon::update(Game* _game)
{
	int clip = 1;
	if(mClipSize > 0)
		clip = mClip;

	mCounter += _game->getDelta();
	if(mActive && mCounter >= mShootRate && clip > 0)
	{
		if(_game->mousePressed("left"))
		{
			// launch bullets
			EventManager* evm = EventManager::getSingleton();
			sf::Vector2i mousePosition = evm->getMousePos(_game);

			bool canShoot = false;
			if(mousePosition.y < mOwner->getPosition().y + mOwner->getAABB().height)
				canShoot = true;

			if(canShoot)
			{
				sf::View view = _game->getCamera();
				sf::Vector2f mousePosTrans = _game->getWindow()->mapPixelToCoords(mousePosition, view);
				sf::Vector2f shootPoint(mX + mShootPoint.x - 8, mY + mShootPoint.y);

				sf::Vector2f delta(mousePosTrans.x - shootPoint.x, mousePosTrans.y - shootPoint.y);
				float angle = atan2(delta.y, delta.x);
				float power = 500.f;

				int id = 7;
				if(mName == "FireballLauncher")
					id = 23;

				Bullet* bullet = new Bullet(id, shootPoint.x, shootPoint.y, sf::Vector2f(cos(angle) * power, sin(angle) * power), mDamage, EMITTERTYPE_Circle);
				bullet->setUniqueType("Bullet");
				bullet->setOwner(mOwner);
				ignore(bullet);
				mOwner->ignore(bullet);
				_game->pushObject(bullet);
				static_cast<Player*>(mOwner)->changeAnim("forward");

				// update weapon
				mClip--;
				mCounter = 0.f;
				std::stringstream ss;
				ss << "Clip: " << mClip << "/" << mClipCapacity;
				Text* text = static_cast<Text*>(_game->getInterface()->getInterface(2, "clipText"));
				text->setString(ss.str());
				
				if(mName == "FireballLauncher")
					_game->playSound("fireball");
				else if(mName == "Pistol")
					_game->playSound("pistol");
				else if(mName == "Shotgun")
					_game->playSound("shotgun");
			}
		}
	}

	mReloadCount += _game->getDelta();
	if(/*_game->keyPressed("r") &&*/ mClip <= 0 && !mReload /*&& mClip < mClipSize*/)
	{
		mReload   = true;
		mLastClip = mClip;
		mClip	  = 0;
		if(mReloadVisual)
			mReloadVisual->setActive(true);
	}

	if(mReload && mReloadCount > mReloadTime)
	{
		int capacity = mClipSize - mLastClip;
		if(capacity >= 0)
			mClipCapacity  -= mClipSize - mLastClip;
		else if(capacity < 0)
			mClipCapacity = 0;

		if(mClipCapacity > 0)
		{
			mClip			= mClipSize;
			mReloadCount	= .0f;
			mReload			= false;

			std::stringstream ss;
			ss << "Clip: " << mClip << "/" << mClipCapacity;
			Text* text = static_cast<Text*>(_game->getInterface()->getInterface(2, "clipText"));
			text->setString(ss.str());
			_game->playSound("reload");
			_game->playSound("reload");
		}

		if(mReloadVisual)
			mReloadVisual->setActive(false);
	}

	stringstream ss;
	ss << "Weapon Damage: " << mDamage;
	static_cast<Text*>(_game->getInterface()->getInterface(2, "damageText"))->setString(ss.str());
	
	Object::update(_game);
	return true;
}
Пример #10
0
tmp<volSymmTensorField> Smagorinsky2::B() const
{
    volSymmTensorField D = dev(symm(fvc::grad(U())));

    return (((2.0/3.0)*I)*k() - 2.0*nuSgs_*D - (2.0*cD2_)*delta()*(D&D));
}
Пример #11
0
void QGraphicsWidgetPrivate::windowFrameMouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    Q_Q(QGraphicsWidget);
    ensureWindowData();
    if (!(event->buttons() & Qt::LeftButton) || windowData->hoveredSubControl != QStyle::SC_TitleBarLabel)
        return;

    QLineF delta(q->mapFromScene(event->buttonDownScenePos(Qt::LeftButton)), event->pos());
    QLineF parentDelta(q->mapToParent(delta.p1()), q->mapToParent(delta.p2()));
    QLineF parentXDelta(q->mapToParent(QPointF(delta.p1().x(), 0)), q->mapToParent(QPointF(delta.p2().x(), 0)));
    QLineF parentYDelta(q->mapToParent(QPointF(0, delta.p1().y())), q->mapToParent(QPointF(0, delta.p2().y())));

    QRectF newGeometry;
    switch (windowData->grabbedSection) {
    case Qt::LeftSection:
        newGeometry = QRectF(windowData->startGeometry.topLeft()
                             + QPointF(parentXDelta.dx(), parentXDelta.dy()),
                             windowData->startGeometry.size() - QSizeF(delta.dx(), delta.dy()));
        break;
    case Qt::TopLeftSection:
        newGeometry = QRectF(windowData->startGeometry.topLeft()
                             + QPointF(parentDelta.dx(), parentDelta.dy()),
                             windowData->startGeometry.size() - QSizeF(delta.dx(), delta.dy()));
        break;
    case Qt::TopSection:
        newGeometry = QRectF(windowData->startGeometry.topLeft()
                             + QPointF(parentYDelta.dx(), parentYDelta.dy()),
                             windowData->startGeometry.size() - QSizeF(0, delta.dy()));
        break;
    case Qt::TopRightSection:
        newGeometry = QRectF(windowData->startGeometry.topLeft()
                             + QPointF(parentYDelta.dx(), parentYDelta.dy()),
                             windowData->startGeometry.size() - QSizeF(-delta.dx(), delta.dy()));
        break;
    case Qt::RightSection:
        newGeometry = QRectF(windowData->startGeometry.topLeft(),
                             windowData->startGeometry.size() + QSizeF(delta.dx(), 0));
        break;
    case Qt::BottomRightSection:
        newGeometry = QRectF(windowData->startGeometry.topLeft(),
                             windowData->startGeometry.size() + QSizeF(delta.dx(), delta.dy()));
        break;
    case Qt::BottomSection:
        newGeometry = QRectF(windowData->startGeometry.topLeft(),
                             windowData->startGeometry.size() + QSizeF(0, delta.dy()));
        break;
    case Qt::BottomLeftSection:
        newGeometry = QRectF(windowData->startGeometry.topLeft()
                             + QPointF(parentXDelta.dx(), parentXDelta.dy()),
                             windowData->startGeometry.size() - QSizeF(delta.dx(), -delta.dy()));
        break;
    case Qt::TitleBarArea:
        newGeometry = QRectF(windowData->startGeometry.topLeft()
                             + QPointF(parentDelta.dx(), parentDelta.dy()),
                             windowData->startGeometry.size());
        break;
    case Qt::NoSection:
        break;
    }

    if (windowData->grabbedSection != Qt::NoSection) {
        _q_boundGeometryToSizeConstraints(windowData->startGeometry, &newGeometry,
                                          windowData->grabbedSection,
                                          q->effectiveSizeHint(Qt::MinimumSize),
                                          q->effectiveSizeHint(Qt::MaximumSize),
                                          q);
        q->setGeometry(newGeometry);
    }
}
Пример #12
0
osg::Node *createHUD(osgText::Text *updateText)
{
	osg::Camera *hudCamera = new osg::Camera;
	hudCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
	hudCamera->setProjectionMatrixAsOrtho2D(0,1280,0,1024);
	hudCamera->setViewMatrix(osg::Matrix::identity());
	hudCamera->setRenderOrder(osg::Camera::POST_RENDER);
	hudCamera->setClearMask(GL_DEPTH_BUFFER_BIT);

	//std::string timesFont(

	osg::Vec3 position(150.f,800.0f,0.0f);
	osg::Vec3 delta(0.0f,-60.0f,0.0f);

	{
		osg::Geode *geode = new osg::Geode;
		osg::StateSet *stateset = geode->getOrCreateStateSet();
		stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
		stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
		geode->setName("simple");
		hudCamera->addChild(geode);

		osgText::Text *text = new osgText::Text;
		geode->addDrawable( text );

		text->setText("Picking in head up Displays is simple!");
		text->setCharacterSize(10.f);
		text->setPosition(position);

		position+=delta;
	}

	for ( int i=0; i<5; ++i ) {
		osg::Vec3 dy(0.0f,-30.0f,0.0f);
		osg::Vec3 dx(120.0f,0.0f,0.0f);
		osg::Geode *geode = new osg::Geode;
		osg::StateSet *stateset = geode->getOrCreateStateSet();
		const char *opts[] = {"one", "Two", "Three", "January", "Feb", "2003"};
		osg::Geometry *quad = new osg::Geometry;
		stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
		stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
		std::string name = "subOption";
		name+=" ";
		name+=std::string(opts[i]);
		geode->setName(name);
		osg::Vec3Array *vertices = new osg::Vec3Array(4);
		osg::Vec4Array *colors = new osg::Vec4Array;
		colors->push_back(osg::Vec4(0.4-0.1*i,0.1*i,0.2*i,1.0));
		quad->setColorArray(colors);
		quad->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);
		(*vertices)[0] = position;
		(*vertices)[1] = position+dx;
		(*vertices)[2] = position+dx+dy;
		(*vertices)[3] = position+dy;
		quad->setVertexArray(vertices);
		quad->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
		geode->addDrawable(quad);
		hudCamera->addChild(geode);

		position+=delta;
	}

	{
		osg::Geode *geode = new osg::Geode;
		osg::StateSet *stateset = geode->getOrCreateStateSet();
		stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
		stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
		geode->setName("The text Label");
		geode->addDrawable(updateText);
		hudCamera->addChild(geode);

		updateText->setCharacterSize(10.f);
		updateText->setColor(osg::Vec4(1.0f,1.0f,0.0f,1.0f));
		updateText->setText("");
		updateText->setPosition(position);
		updateText->setDataVariance(osg::Object::DYNAMIC);

		position += delta;
	}

	return hudCamera;
}
Пример #13
0
        void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override {
            const PLSQuadEdgeEffect& qe = args.fGP.cast<PLSQuadEdgeEffect>();
            GrGLSLVertexBuilder* vsBuilder = args.fVertBuilder;
            GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
            GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;

            // emit attributes
            varyingHandler->emitAttributes(qe);

            GrGLSLVertToFrag uv(kVec2f_GrSLType);
            varyingHandler->addVarying("uv", &uv, kHigh_GrSLPrecision);
            vsBuilder->codeAppendf("%s = %s;", uv.vsOut(), qe.inUV()->fName);

            GrGLSLVertToFrag ep1(kVec2f_GrSLType);
            varyingHandler->addVarying("endpoint1", &ep1, kHigh_GrSLPrecision);
            vsBuilder->codeAppendf("%s = vec2(%s.x, %s.y);", ep1.vsOut(), 
                                  qe.inEndpoint1()->fName, qe.inEndpoint1()->fName);

            GrGLSLVertToFrag ep2(kVec2f_GrSLType);
            varyingHandler->addVarying("endpoint2", &ep2, kHigh_GrSLPrecision);
            vsBuilder->codeAppendf("%s = vec2(%s.x, %s.y);", ep2.vsOut(), 
                                  qe.inEndpoint2()->fName, qe.inEndpoint2()->fName);

            GrGLSLVertToFrag delta(kVec2f_GrSLType);
            varyingHandler->addVarying("delta", &delta, kHigh_GrSLPrecision);
            vsBuilder->codeAppendf("%s = vec2(%s.x - %s.x, %s.y - %s.y) * 0.5;", 
                                   delta.vsOut(), ep1.vsOut(), ep2.vsOut(), ep2.vsOut(), 
                                   ep1.vsOut());

            GrGLSLVertToFrag windings(kInt_GrSLType);
            varyingHandler->addFlatVarying("windings", &windings, kLow_GrSLPrecision);
            vsBuilder->codeAppendf("%s = %s;", 
                                   windings.vsOut(), qe.inWindings()->fName);

            // Setup position
            this->setupPosition(vsBuilder, gpArgs, qe.inPosition()->fName);

            // emit transforms
            this->emitTransforms(vsBuilder, varyingHandler, uniformHandler, gpArgs->fPositionVar, 
                                 qe.inPosition()->fName, qe.localMatrix(), args.fTransformsIn, 
                                 args.fTransformsOut);

            GrGLSLFragmentBuilder* fsBuilder = args.fFragBuilder;
            SkAssertResult(fsBuilder->enableFeature(
                           GrGLSLFragmentShaderBuilder::kPixelLocalStorage_GLSLFeature));
            SkAssertResult(fsBuilder->enableFeature(
                    GrGLSLFragmentShaderBuilder::kStandardDerivatives_GLSLFeature));
            static const int QUAD_ARGS = 2;
            GrGLSLShaderVar inQuadArgs[QUAD_ARGS] = {
                GrGLSLShaderVar("dot", kFloat_GrSLType, 0, kHigh_GrSLPrecision),
                GrGLSLShaderVar("uv", kVec2f_GrSLType, 0, kHigh_GrSLPrecision)
            };
            SkString inQuadName;

            const char* inQuadCode = "if (uv.x * uv.x <= uv.y) {"
                                     "return dot >= 0.0;"
                                     "} else {"
                                     "return false;"
                                     "}";
            fsBuilder->emitFunction(kBool_GrSLType, "in_quad", QUAD_ARGS, inQuadArgs, inQuadCode, 
                                    &inQuadName);
            fsBuilder->declAppendf(GR_GL_PLS_PATH_DATA_DECL);
            // keep the derivative instructions outside the conditional
            fsBuilder->codeAppendf("highp vec2 uvdX = dFdx(%s);", uv.fsIn());
            fsBuilder->codeAppendf("highp vec2 uvdY = dFdy(%s);", uv.fsIn());
            fsBuilder->codeAppend("highp vec2 uvIncX = uvdX * 0.45 + uvdY * -0.1;");
            fsBuilder->codeAppend("highp vec2 uvIncY = uvdX * 0.1 + uvdY * 0.55;");
            fsBuilder->codeAppendf("highp vec2 uv = %s.xy - uvdX * 0.35 - uvdY * 0.25;", 
                                   uv.fsIn());
            fsBuilder->codeAppendf("highp vec2 firstSample = %s.xy - vec2(0.25);",
                                   fsBuilder->fragmentPosition());
            fsBuilder->codeAppendf("highp float d = dot(%s, (firstSample - %s).yx) * 2.0;", 
                                   delta.fsIn(), ep1.fsIn());
            fsBuilder->codeAppendf("pls.windings[0] += %s(d, uv) ? %s : 0;", inQuadName.c_str(), 
                                   windings.fsIn());
            fsBuilder->codeAppend("uv += uvIncX;");
            fsBuilder->codeAppendf("d += %s.x;", delta.fsIn());
            fsBuilder->codeAppendf("pls.windings[1] += %s(d, uv) ? %s : 0;", inQuadName.c_str(), 
                                   windings.fsIn());
            fsBuilder->codeAppend("uv += uvIncY;");
            fsBuilder->codeAppendf("d += %s.y;", delta.fsIn());
            fsBuilder->codeAppendf("pls.windings[2] += %s(d, uv) ? %s : 0;", inQuadName.c_str(), 
                                   windings.fsIn());
            fsBuilder->codeAppend("uv -= uvIncX;");
            fsBuilder->codeAppendf("d -= %s.x;", delta.fsIn());
            fsBuilder->codeAppendf("pls.windings[3] += %s(d, uv) ? %s : 0;", inQuadName.c_str(), 
                                   windings.fsIn());
        }
Пример #14
0
Vector MultiColvarBase::getSeparation( const Vector& vec1, const Vector& vec2 ) const {
  if(usepbc){ return pbcDistance( vec1, vec2 ); }
  else{ return delta( vec1, vec2 ); }
}
Пример #15
0
bool CMonoActor::SetAspectProfile( EEntityAspects aspect, uint8 profile )
{
	bool res(false);

	if (aspect == eEA_Physics)
	{
		if (m_currentPhysProfile==profile && !gEnv->pSystem->IsSerializingFile()) //rephysicalize when loading savegame
			return true;

		bool wasFrozen=(m_currentPhysProfile==eAP_Frozen);

		switch (profile)
		{
		case eAP_NotPhysicalized:
			{
				SEntityPhysicalizeParams params;
				params.type = PE_NONE;
				GetEntity()->Physicalize(params);
			}
			res=true;
			break;
		case eAP_Spectator:
		case eAP_Alive:
			{
				// if we were asleep, we just want to wakeup
				if (profile==eAP_Alive && (m_currentPhysProfile==eAP_Sleep))
				{
					ICharacterInstance *pCharacter=GetEntity()->GetCharacter(0);
					if (pCharacter && pCharacter->GetISkeletonAnim())
					{
						IPhysicalEntity *pPhysicalEntity=0;
						Matrix34 delta(IDENTITY);

						pCharacter->GetISkeletonPose()->StandUp(GetEntity()->GetWorldTM(), false, pPhysicalEntity, delta);

						if (pPhysicalEntity)
						{
							IEntityPhysicalProxy *pPhysicsProxy=static_cast<IEntityPhysicalProxy *>(GetEntity()->GetProxy(ENTITY_PROXY_PHYSICS));
							if (pPhysicsProxy)
							{
								GetEntity()->SetWorldTM(delta);
								pPhysicsProxy->AssignPhysicalEntity(pPhysicalEntity);
							}
						}

						if(m_pAnimatedCharacter)
						{
							m_pAnimatedCharacter->ForceTeleportAnimationToEntity();
							m_pAnimatedCharacter->ForceRefreshPhysicalColliderMode();
						}
					}
				}
				else
				{
				//	Physicalize(wasFrozen?STANCE_PRONE:STANCE_NULL);

					if (profile==eAP_Spectator)
					{
						if (ICharacterInstance *pCharacter=GetEntity()->GetCharacter(0))
							pCharacter->GetISkeletonPose()->DestroyCharacterPhysics(1);

						if(m_pAnimatedCharacter)
						{
							m_pAnimatedCharacter->ForceRefreshPhysicalColliderMode();
							m_pAnimatedCharacter->RequestPhysicalColliderMode( eColliderMode_Spectator, eColliderModeLayer_Game, "Actor::SetAspectProfile");
						}
					}
					else if (profile==eAP_Alive)
					{
						if (m_currentPhysProfile==eAP_Spectator)
						{
							if(m_pAnimatedCharacter)
								m_pAnimatedCharacter->RequestPhysicalColliderMode( eColliderMode_Undefined, eColliderModeLayer_Game, "Actor::SetAspectProfile");
							
							if (IPhysicalEntity *pPhysics=GetEntity()->GetPhysics())
							{
								if (ICharacterInstance *pCharacter=GetEntity()->GetCharacter(0))
								{
									pCharacter->GetISkeletonPose()->DestroyCharacterPhysics(2);

									if (IPhysicalEntity *pCharPhysics=pCharacter->GetISkeletonPose()->GetCharacterPhysics())
									{
										pe_params_articulated_body body;
										body.pHost=pPhysics;
										pCharPhysics->SetParams(&body);
									}
								}
							}
						}
					}
				}
			}
			res=true;
			break;
		case eAP_Linked:
			// make sure we are alive, for when we transition from ragdoll to linked...
			//if (!GetEntity()->GetPhysics() || GetEntity()->GetPhysics()->GetType()!=PE_LIVING)
				//Physicalize();
			res=true;
			break;
		case eAP_Sleep:
			//RagDollize(true);
			res=true;
			break;
		case eAP_Ragdoll:
			// killed while sleeping?
			/*if (m_currentPhysProfile==eAP_Sleep) 
				GoLimp();
			else
				RagDollize(false);*/
			res=true;
			break;
		case eAP_Frozen:
			/*if (!GetEntity()->GetPhysics() || ((GetEntity()->GetPhysics()->GetType()!=PE_LIVING) && (GetEntity()->GetPhysics()->GetType()!=PE_ARTICULATED)))
				Physicalize();
			Freeze(true);*/
			res=true;
			break;
		}

		/*IPhysicalEntity *pPE=GetEntity()->GetPhysics();
		pe_player_dynamics pdyn;

		if (profile!=eAP_Frozen && wasFrozen)
		{
			Freeze(false);

			if (profile==eAP_Alive)
			{
				EStance stance;
				if (!TrySetStance(stance=STANCE_STAND))
					if (!TrySetStance(stance=STANCE_CROUCH))
					{
						pdyn.bActive=0;
						pPE->SetParams(&pdyn);

						if (!TrySetStance(stance=STANCE_PRONE))
							stance=STANCE_NULL;

						pdyn.bActive=1;
						pPE->SetParams(&pdyn);
					}
					
				if (stance!=STANCE_NULL)
				{
					m_stance=STANCE_NULL;
					m_desiredStance=stance;

					UpdateStance();
				}

				GetGameObject()->ChangedNetworkState(IPlayerInput::INPUT_ASPECT);
			}
		}

		if (res)
			ProfileChanged(profile);*/

		m_currentPhysProfile = profile;
	}

	return res;
}
Пример #16
0
 BBox BBox::expand(float f) {
     Vector3 delta(f, f, f);
     pMin -= delta;
     pMax += delta;
     return *this;
 }
void Foam::simpleTwoStroke::addZonesAndModifiers()
{
    // Add the zones and mesh modifiers to operate piston motion

    if
    (
        pointZones().size() > 0
        || faceZones().size() > 0
        || cellZones().size() > 0
    )
    {
        Info<< "Time = " << engTime().theta() << endl;
        Info<< "void simpleTwoStroke::addZonesAndModifiers() : "
            << "Zones and modifiers already present.  Skipping."
            << endl;

        if (topoChanger_.size() == 0)
        {
            FatalErrorIn
            (
                "void simpleTwoStroke::addZonesAndModifiers()"
            )   << "Mesh modifiers not read properly"
                << abort(FatalError);
        }

        setVirtualPistonPosition();
        checkAndCalculate();

        return;


    }

    Info << "checkAndCalculate()" << endl;
    checkAndCalculate();

    Info<< "Time = " << engTime().theta() << endl
        << "Adding zones to the engine mesh" << endl;


    //fz = 4: virtual piston, outSidePort, insidePort, cutFaceZone
    //pz = 2: piston points, cutPointZone
    //cz = 1: moving mask

    List<pointZone*> pz(3);
    List<faceZone*> fz(4);
    List<cellZone*> cz(1);

    label nPointZones = 0;
    label nFaceZones = 0;
    label nCellZones = 0;

    // Add the piston zone
    if (piston().patchID().active())
    {

        // Piston position

        Info << "Adding face zone for piston layer addition/removal" << endl;

        label pistonPatchID = piston().patchID().index();

        scalar zPist =
            max(boundary()[pistonPatchID].patch().localPoints()).z();

        scalar zPistV = zPist + offSet();

        labelList zone1(faceCentres().size());
        boolList flipZone1(faceCentres().size(), false);
        label nZoneFaces1 = 0;

        bool foundAtLeastOne = false;
        scalar zHigher = GREAT;
        scalar dh = GREAT;
        scalar dl = GREAT;

        forAll (faceCentres(), faceI)
        {
            // The points have to be in the cylinder and not in the ports....

            scalar zc = faceCentres()[faceI].z();

            scalar xc = faceCentres()[faceI].x();
            scalar yc = faceCentres()[faceI].y();

            vector n = faceAreas()[faceI]/mag(faceAreas()[faceI]);
            scalar dd = n & vector(0,0,1);

            if(sqrt(sqr(xc)+sqr(yc)) <  0.5 * engTime().bore().value())
            {
                if (dd > 0.1)
                {
                    if (zPistV - zc > 0 && zPistV - zc < dl)
                    {
                        dl = zPistV - zc;
                    }

                    if (zc - zPistV > 0 && zc - zPistV < dh)
                    {
                        zHigher = zc;
                        dh = zc - zHigher;
                    }

                    if
                    (
                        zc > zPistV - delta()
                        && zc < zPistV + delta()
                    )
                    {
                        foundAtLeastOne = true;
                        if ((faceAreas()[faceI] & vector(0,0,1)) < 0)
                        {
                            flipZone1[nZoneFaces1] = true;
                        }

                        zone1[nZoneFaces1] = faceI;
                        nZoneFaces1++;
                    }
                }
            }
        }
Пример #18
0
	void GarbageHistoric::printPrediction(){
		std::vector<int> centroid (this->garbage->getCentroid());
		std::vector<int> delta (this->deltaPos);
		//~ printf("Historic age: %d , centroid (%d-%d),deltaPos (%d-%d)\n , last appereance: %d, apperances :%d \n", 
			//~ this->age, centroid[0],centroid[1],delta[0],delta[1],this->lastAppeareance,this->appeareances);	
	}
Пример #19
0
    void doc_manager::populate(void)
    {
        
        add_class_descriptor(ml::k_base);
        
        add_class_descriptors(ml::k_base, {
            ml::k_classification,
            ml::k_regression
        });
        
        add_class_descriptors(ml::k_regression, {
            ml::k_ann,
            ml::k_linreg,
            ml::k_logreg
        });
        
        add_class_descriptors(ml::k_classification, {
            ml::k_svm,
            ml::k_adaboost,
            ml::k_anbc,
            ml::k_dtw,
            ml::k_hmmc,
            ml::k_softmax,
            ml::k_randforest,
            ml::k_mindist,
            ml::k_knn,
            ml::k_gmm,
            ml::k_dtree
        });
        
        add_class_descriptors(ml::k_feature_extraction, {
            ml::k_peak,
            ml::k_minmax,
            ml::k_zerox
        });
        
        descriptors[ml::k_ann].desc("Artificial Neural Network").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/MLP");
        descriptors[ml::k_linreg].desc("Linear Regression").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/LinearRegression");
        descriptors[ml::k_logreg].desc("Logistic Regression").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/LogisticRegression");
        descriptors[ml::k_peak].desc("Peak Detection").url("").num_outlets(1);
        descriptors[ml::k_minmax].desc("Minimum / Maximum Detection").url("").num_outlets(1);
        descriptors[ml::k_zerox].desc("Zero Crossings Detection").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/ZeroCrossingCounter");
        descriptors[ml::k_svm].desc("Support Vector Machine").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/SVM");
        descriptors[ml::k_adaboost].desc("Adaptive Boosting").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/AdaBoost");
        descriptors[ml::k_anbc].desc("Adaptive Naive Bayes Classifier").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/ANBC");
        descriptors[ml::k_dtw].desc("Dynamic Time Warping").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/DTW");
        descriptors[ml::k_hmmc].desc("Continuous Hidden Markov Model").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/HMM");
        descriptors[ml::k_softmax].desc("Softmax Classifier").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/Softmax");
        descriptors[ml::k_randforest].desc("Random Forests").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/RandomForests");
        descriptors[ml::k_mindist].desc("Minimum Distance").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/MinDist");
        descriptors[ml::k_knn].desc("K Nearest Neighbour").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/KNN");
        descriptors[ml::k_gmm].desc("Gaussian Mixture Model").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/GMMClassifier");
        descriptors[ml::k_dtree].desc("Decision Trees").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/DecisionTree");
        
        for (auto& desc : {&descriptors[ml::k_hmmc], &descriptors[ml::k_dtw]})
        {
            desc->notes(
                        "add and map messages for time series should be delimited with record messages, e.g. record 1, add 1 40 50, add 1 41 50, record 0"
            );
        }
        
        // base descriptor
        message_descriptor add(
                              "add",
                              "list comprising a class id followed by n features, <class> <feature 1> <feature 2> etc",
                               "1 0.2 0.7 0.3 0.1"
                              );

        
        message_descriptor train(
                                "train",
                                "train the model based on vectors added with 'add'"
                                );
        
        message_descriptor map(
                              "map",
                              "generate the output value(s) for the input feature vector",
                               "0.2 0.7 0.3 0.1"
                              );
        
        message_descriptor write(
                                 "write",
                                 "write training data and / or model, first argument gives path to write file",
                                 "/path/to/my_ml-lib_data"
                                 );
        
        message_descriptor read(
                                "read",
                                "read training data and / or model, first argument gives path to the read file",
                                "/path/to/my_ml-lib_data"
                                );
        
        message_descriptor clear(
                                 "clear",
                                 "clear the stored training data and model"
                                 );
        
        message_descriptor help(
                               "help",
                               "post usage statement to the console"
                               );
        
        valued_message_descriptor<int> scaling(
                                               "scaling",
                                               "sets whether values are automatically scaled",
                                               {0, 1},
                                               1
                                               );
        
        valued_message_descriptor<int> record(
                                              "record",
                                              "start or stop time series recording for a single example of a given class",
                                              {0, 1},
                                              0
                                              );
        
        ranged_message_descriptor<float> training_rate(
                                                       "training_rate",
                                                       "set the learning rate, used to update the weights at each step of learning algorithms such as stochastic gradient descent.",
                                                       0.01,
                                                       1.0,
                                                       0.1
                                                       );
        
        ranged_message_descriptor<float> min_change(
                                                    "min_change",
                                                    "set the minimum change that must be achieved between two training epochs for the training to continue",
                                                    0.0,
                                                    1.0,
                                                    1.0e-5
                                                    );
        
        ranged_message_descriptor<int> max_iterations(
                                                      "max_iterations",
                                                      "set the maximum number of training iterations",
                                                      0,
                                                      1000,
                                                      100
                                                      );
        
        record.insert_before = "add";
        descriptors[ml::k_base].add_message_descriptor(add, write, read, train, clear, map, help, scaling, training_rate, min_change, max_iterations);

        // generic classification descriptor
        valued_message_descriptor<bool> null_rejection(
                                                       "null_rejection",
                                                       "toggle NULL rejection off or on, when 'on' classification results below the NULL-rejection threshold will be discarded",
                                                       {false, true},
                                                       true
                                                       );
        
        ranged_message_descriptor<float> null_rejection_coeff(
                                                              "null_rejection_coeff",
                                                              "set a multiplier for the NULL-rejection threshold ",
                                                              0.1,
                                                              1.0,
                                                              0.9
                                                              );
        
        valued_message_descriptor<int> probs(
                                             "probs",
                                             "determines whether probabilities are sent from the right outlet",
                                             {0, 1},
                                             0
                                             );
        
        descriptors[ml::k_classification].add_message_descriptor(null_rejection_coeff, probs, null_rejection);
        
        // generic feature extraction descriptor
//        descriptors[ml::k_feature_extraction].add_message_descriptor(null_rejection_coeff, null_rejection);

        // generic regression descriptor
       
        
//        descriptors[ml::k_regression].add_message_descriptor(training_rate, min_change, max_iterations);
        
        // Object-specific descriptors
        //-- Regressifiers
        //---- ann
        valued_message_descriptor<ml::data_type> mode("mode",
                                                      "set the mode of the ANN, " + std::to_string(ml::LABELLED_CLASSIFICATION) + " for classification, " + std::to_string(ml::LABELLED_REGRESSION) + " for regression",
                                                      {ml::LABELLED_CLASSIFICATION, ml::LABELLED_REGRESSION, ml::LABELLED_TIME_SERIES_CLASSIFICATION},
                                                      ml::defaults::data_type
                                                      );
        
        
        message_descriptor add_ann(
                              "add",
                              "class id followed by n features, <class> <feature 1> <feature 2> etc when in classification mode or N output values followed by M input values when in regression mode (N = num_outputs)",
                                   "1 0.2 0.7 0.3 0.1"

                              );
      
        ranged_message_descriptor<int> num_outputs(
                                                   "num_outputs",
                                                   "set the number of neurons in the output layer",
                                                   1,
                                                   1000,
                                                   ml::defaults::num_output_dimensions
                                                   );
        
        ranged_message_descriptor<int> num_hidden(
                                                  "num_hidden",
                                                  "set the number of neurons in the hidden layer",
                                                  1,
                                                  1000,
                                                  ml::defaults::num_hidden_neurons
                                                  );
        
        ranged_message_descriptor<int> min_epochs(
                                                  "min_epochs",
                                                  "setting the minimum number of training iterations",
                                                  1,
                                                  1000,
                                                  10
                                                  );
        
        // TODO: check if the "epochs" are still needed or if we can use "iterations" as inherited from ml_regression
        ranged_message_descriptor<int> max_epochs(
                                                  "max_epochs",
                                                  "setting the maximum number of training iterations",
                                                  1,
                                                  10000,
                                                  100
                                                  );

        ranged_message_descriptor<float> momentum(
                                                  "momentum",
                                                  "set the momentum",
                                                  0.0,
                                                  1.0,
                                                  0.5
                                                  );
        
        ranged_message_descriptor<float> gamma(
                                                  "gamma",
                                                  "set the gamma",
                                                  0.0,
                                                  10.0,
                                                  2.0
                                                  );
        
        // TODO: have optional value_labels for value labels
        valued_message_descriptor<int> input_activation_function(
                                                                 "input_activation_function",
                                                                 "set the activation function for the input layer, 0:LINEAR, 1:SIGMOID, 2:BIPOLAR_SIGMOID",
                                                                 {0, 1, 2},
                                                                 0
                                                                 );
        
        valued_message_descriptor<int> hidden_activation_function(
                                                                 "hidden_activation_function",
                                                                 "set the activation function for the hidden layer, 0:LINEAR, 1:SIGMOID, 2:BIPOLAR_SIGMOID",
                                                                 {0, 1, 2},
                                                                 0
                                                                 );
        
        valued_message_descriptor<int> output_activation_function(
                                                                 "output_activation_function",
                                                                 "set the activation function for the output layer, 0:LINEAR, 1:SIGMOID, 2:BIPOLAR_SIGMOID",
                                                                 {0, 1, 2},
                                                                 0
                                                                 );

                                                                 
        ranged_message_descriptor<int> rand_training_iterations(
                                                                 "rand_training_iterations",
                                                                 "set the number of random training iterations",
                                                                 0,
                                                                 1000,
                                                                 10
                                                                 );

        valued_message_descriptor<bool> use_validation_set(
                                                           "use_validation_set",
                                                           "set whether to use a validation training set",
                                                           {false, true},
                                                           true
                                                           );
        
        ranged_message_descriptor<int> validation_set_size(
                                                           "validation_set_size",
                                                           "set the size of the validation set",
                                                           1,
                                                           100,
                                                           20
                                                           );
        
        valued_message_descriptor<bool> randomize_training_order(
                                                           "randomize_training_order",
                                                           "sets whether to randomize the training order",
                                                           {false, true},
                                                           false
                                                           );
        
        
        descriptors[ml::k_ann].add_message_descriptor(add_ann, probs, mode, null_rejection, null_rejection_coeff, num_outputs, num_hidden, min_epochs, max_epochs, momentum, gamma, input_activation_function, hidden_activation_function, output_activation_function, rand_training_iterations, use_validation_set, validation_set_size, randomize_training_order);
        
        
        //-- Classifiers
        //---- ml.svm
        ranged_message_descriptor<int> type(
                                            "type",
                                            "set SVM type,"
                                            " 0:C-SVC (multi-class),"
                                            " 1:nu-SVC (multi-class),"
                                            " 2:one-class SVM,"
                                           // " 3:epsilon-SVR (regression),"
                                           // " 4:nu-SVR (regression)"
                                            ,
                                            0,
                                            2,
                                            0
                                            //        "	0 -- C-SVC		(multi-class classification)\n"
                                            //        "	1 -- nu-SVC		(multi-class classification)\n"
                                            //        "	2 -- one-class SVM\n"
                                            //        "	3 -- epsilon-SVR	(regression)\n"
                                            //        "	4 -- nu-SVR		(regression)\n"

                                            );
        
        ranged_message_descriptor<int> kernel(
                                              "kernel",
                                              "set type of kernel function, "
                                              "0:linear, " // (u'*v),"
                                              "1:polynomial, " // (gamma*u'*v + coef0)^degree,"
                                              "2:radial basis function, " //: exp(-gamma*|u-v|^2),"
                                              "3:sigmoid, " //  tanh(gamma*u'*v + coef0),"
                                              "4:precomputed kernel (kernel values in training_set_file)",
                                              0,
                                              4,
                                              0
                                              //        "	0 -- linear: u'*v\n"
                                              //        "	1 -- polynomial: (gamma*u'*v + coef0)^degree\n"
                                              //        "	2 -- radial basis function: exp(-gamma*|u-v|^2)\n"
                                              //        "	3 -- sigmoid: tanh(gamma*u'*v + coef0)\n"
                                              //        "	4 -- precomputed kernel (kernel values in training_set_file)\n"
                                              );
        
        ranged_message_descriptor<float> degree(
                                              "degree",
                                              "set degree in kernel function",
                                              0,
                                              20,
                                              3
                                              );
        
        ranged_message_descriptor<float> svm_gamma(
                                              "gamma",
                                              "set gamma in kernel function",
                                              0.0,
                                              1.0,
                                              0.5
                                              );
        
        ranged_message_descriptor<float> coef0(
                                               "coef0",
                                               "coef0 in kernel function",
                                               INFINITY * -1.f, INFINITY,
                                               0.0
                                               );
        
        ranged_message_descriptor<float> cost(
                                               "cost",
                                               "set the parameter C of C-SVC, epsilon-SVR, and nu-SVR",
                                               INFINITY * -1.f, INFINITY,
                                               1.0
                                               );
        
        ranged_message_descriptor<float> nu(
                                              "nu",
                                              "set the parameter nu of nu-SVC, one-class SVM, and nu-SVR",
                                              INFINITY * -1.f, INFINITY,
                                              0.5
                                              );
        
        message_descriptor cross_validation(
                                            "cross_validation",
                                            "perform cross validation"
                                            );
        
        ranged_message_descriptor<int> num_folds(
                                                 "num_folds",
                                                 "set the number of folds used for cross validation",
                                                 1, 100,
                                                 10
                                                 );
        
        descriptors[ml::k_svm].add_message_descriptor(cross_validation, num_folds, type, kernel, degree, svm_gamma, coef0, cost, nu);
        
        //---- ml.adaboost        
        ranged_message_descriptor<int> num_boosting_iterations(
                                                                "num_boosting_iterations",
                                                               "set the number of boosting iterations that should be used when training the model",
                                                               0,
                                                               200,
                                                               20
                                                               );
        
        valued_message_descriptor<int> prediction_method(
                                                        "prediction_method",
                                                         "set the Adaboost prediction method, 0:MAX_VALUE, 1:MAX_POSITIVE_VALUE",
                                                         {GRT::AdaBoost::MAX_VALUE, GRT::AdaBoost::MAX_POSITIVE_VALUE},
                                                         GRT::AdaBoost::MAX_VALUE
                                                         
        );
        
        valued_message_descriptor<int> set_weak_classifier(
                                                           "set_weak_classifier",
                                                           "sets the weak classifier to be used by Adaboost, 0:DECISION_STUMP, 1:RADIAL_BASIS_FUNCTION",
                                                           {ml::weak_classifiers::DECISION_STUMP, ml::weak_classifiers::RADIAL_BASIS_FUNCTION},
                                                           ml::weak_classifiers::DECISION_STUMP
                                                           );
        
        valued_message_descriptor<int> add_weak_classifier(
                                                           "add_weak_classifier",
                                                           "add a weak classifier to the list of classifiers used by Adaboost",
                                                           {ml::weak_classifiers::DECISION_STUMP, ml::weak_classifiers::RADIAL_BASIS_FUNCTION},
                                                           ml::weak_classifiers::DECISION_STUMP
                                                           );

        descriptors[ml::k_adaboost].add_message_descriptor(num_boosting_iterations, prediction_method, set_weak_classifier, add_weak_classifier);
        
        //---- ml.anbc
        message_descriptor weights("weights",
                                   "vector of 1 integer and N floating point values where the integer is a class label and the floats are the weights for that class. Sending weights with a vector size of zero clears all weights"
                                   );
        
        descriptors[ml::k_anbc].add_message_descriptor(weights);
        
        //---- ml.dtw
        valued_message_descriptor<int> rejection_mode(
                                                      "rejection_mode",
                                                      "sets the method used for null rejection, 0:TEMPLATE_THRESHOLDS, 1:CLASS_LIKELIHOODS, 2:THRESHOLDS_AND_LIKELIHOODS",
                                                      {GRT::DTW::TEMPLATE_THRESHOLDS, GRT::DTW::CLASS_LIKELIHOODS, GRT::DTW::THRESHOLDS_AND_LIKELIHOODS},
                                                      GRT::DTW::TEMPLATE_THRESHOLDS
                                                      );
        
        ranged_message_descriptor<float> warping_radius(
                                                        "warping_radius",
                                                        "sets the radius of the warping path, which is used if the constrain_warping_path is set to 1",
                                                        0.0,
                                                        1.0,
                                                        0.2
                                                        );
        
        valued_message_descriptor<bool> offset_time_series(
                                                           "offset_time_series",
                                                           "set if each timeseries should be offset by the first sample in the time series",
                                                           {false, true},
                                                           false
                                                           );
        
        valued_message_descriptor<bool> constrain_warping_path(
                                                           "constrain_warping_path",
                                                           "sets the warping path should be constrained to within a specific radius from the main diagonal of the cost matrix",
                                                           {false, true},
                                                           true
                                                           );
        
        valued_message_descriptor<bool> enable_z_normalization(
                                                               "enable_z_normalization",
                                                               "turn z-normalization on or off for training and prediction",
                                                               {false, true},
                                                               false
                                                               );
        
        valued_message_descriptor<bool> enable_trim_training_data(
                                                               "enable_trim_training_data",
                                                               "enabling data trimming prior to training",
                                                               {false, true},
                                                               false
                                                               );
  
        descriptors[ml::k_dtw].insert_message_descriptor(record);
        descriptors[ml::k_dtw].add_message_descriptor(rejection_mode, warping_radius, offset_time_series, constrain_warping_path, enable_z_normalization, enable_trim_training_data);
        
        //---- ml.hmmc
        valued_message_descriptor<int> model_type(
                                                  "model_type",
                                                  "set the model type used, 0:ERGODIC, 1:LEFTRIGHT",
                                                  {HMM_ERGODIC, HMM_LEFTRIGHT},
                                                  HMM_LEFTRIGHT
                                                  );
        
        ranged_message_descriptor<int> delta(
                                             "delta",
                                             "control how many states a model can transition to if the LEFTRIGHT model type is used",
                                             1,
                                             100,
                                             11
                                             );
        
        ranged_message_descriptor<int> max_num_iterations(
                                                          "max_num_iterations",
                                                          "set the maximum number of training iterations",
                                                          1,
                                                          1000,
                                                          100
                                                          );
        
        ranged_message_descriptor<int> committee_size(
                                                      "committee_size",
                                                      "set the committee size for the number of votes combined to make a prediction",
                                                      1,
                                                      1000,
                                                      5
                                                      );
        
        ranged_message_descriptor<int> downsample_factor(
                                                      "downsample_factor",
                                                         "set the downsample factor for the resampling of each training time series. A factor of 5 will result in each time series being resized (smaller) by a factor of 5",
                                                      1,
                                                      1000,
                                                      5
                                                      );
        
        descriptors[ml::k_hmmc].insert_message_descriptor(record);
        descriptors[ml::k_hmmc].add_message_descriptor(model_type, delta, max_num_iterations, committee_size, downsample_factor);
        
        //---- ml.softmax
        
        //---- ml.randforest
        ranged_message_descriptor<int> num_random_splits(
                                                         "num_random_splits",
                                                         "set the number of steps that will be used to search for the best spliting value for each node",
                                                         1,
                                                         1000,
                                                         100
                                                         );
        
        ranged_message_descriptor<int> min_samples_per_node2(
                                                            "min_samples_per_node",
                                                            "set the minimum number of samples that are allowed per node",
                                                            1,
                                                            100,
                                                            5
                                                            );
        
        ranged_message_descriptor<int> max_depth(
                                                 "max_depth",
                                                 "sets the maximum depth of the tree, any node that reaches this depth will automatically become a leaf node",
                                                 1,
                                                 100,
                                                 10
                                                 );

        descriptors[ml::k_randforest].add_message_descriptor(num_random_splits, min_samples_per_node2, max_depth);
        
        //----ml.mindist
        ranged_message_descriptor<int> num_clusters(
                                                    "num_clusters",
                                                    "set how many clusters each model will try to find during the training phase",
                                                    1,
                                                    100,
                                                    10
                                                    );

        descriptors[ml::k_mindist].add_message_descriptor(num_clusters);
                
        //---- ml.knn
//        "best_k_value_search:\tbool (0 or 1) set whether k value search is enabled or not (default 0)\n";

        ranged_message_descriptor<int> k(
                                         "k",
                                         "sets the K nearest neighbours that will be searched for by the algorithm during prediction",
                                         1,
                                         500,
                                         10
                                         );
        
        ranged_message_descriptor<int> min_k_search_value(
                                         "min_k_search_value",
                                         "set the minimum K value to use when searching for the best K value",
                                         1,
                                         500,
                                         1
                                         );
        
        ranged_message_descriptor<int> max_k_search_value(
                                                          "max_k_search_value",
                                                          "set the maximum K value to use when searching for the best K value",
                                                          1,
                                                          500,
                                                          10
                                                          );
        
        valued_message_descriptor<bool> best_k_value_search(
                                                            "best_k_value_search",
                                                            "set whether k value search is enabled or not",
                                                            {false, true},
                                                            false
                                                            );
        
        descriptors[ml::k_knn].add_message_descriptor(k, min_k_search_value, max_k_search_value, best_k_value_search);
        
        //---- ml.gmm
        ranged_message_descriptor<int> num_mixture_models(
                                                          "num_mixture_models",
                                                          "sets the number of mixture models used for class",
                                                          1,
                                                          20,
                                                          2
                                                          );

        descriptors[ml::k_gmm].add_message_descriptor(num_mixture_models);

        //---- ml.dtree
        valued_message_descriptor<bool> training_mode(
                                                      "training_mode",
                                                      "set the training mode",
                                                      {GRT::Tree::BEST_ITERATIVE_SPILT, GRT::Tree::BEST_RANDOM_SPLIT},
                                                      GRT::Tree::BEST_ITERATIVE_SPILT
                                                      );
        
        ranged_message_descriptor<int> num_splitting_steps(
                                                          "num_splitting_steps",
                                                          "set the number of steps that will be used to search for the best spliting value for each node",
                                                          1,
                                                          500,
                                                          100
                                                          );
        
        ranged_message_descriptor<int> min_samples_per_node(
                                                          "min_samples_per_node",
                                                          "sets the minimum number of samples that are allowed per node, if the number of samples at a node is below this value then the node will automatically become a leaf node",
                                                          1,
                                                          100,
                                                          5
                                                          );
        
        ranged_message_descriptor<int> dtree_max_depth(
                                                 "max_depth",
                                                 "sets the maximum depth of the tree, any node that reaches this depth will automatically become a leaf node",
                                                 1,
                                                 100,
                                                 10
                                                 );
        
        valued_message_descriptor<bool> remove_features_at_each_split(
                                                               "remove_features_at_each_split",
                                                               "set if a feature is removed at each spilt so it can not be used again",
                                                               {false, true},
                                                               false
                                                               );
        descriptors[ml::k_dtree].add_message_descriptor(training_mode, num_splitting_steps, min_samples_per_node, dtree_max_depth, remove_features_at_each_split);

        //-- Feature extraction
        
        //---- ml.peak
        ranged_message_descriptor<int> search_window_size(
                                                          "search_window_size",
                                                          "set the search window size in values",
                                                          1,
                                                          500,
                                                          5
                                                          );
        
        ranged_message_descriptor<float> peak(
                                              "float",
                                              "set the current value of the peak detector, a bang will be output when a peak is detected",
                                              INFINITY * -1.f, INFINITY,
                                              1
                                              );
        
        message_descriptor reset(
                                "reset",
                                "reset the peak detector"
                                );
        
        message_descriptor peak_help(
                                 "help",
                                 "post usage statement to the console"
                                 );


        descriptors[ml::k_peak].add_message_descriptor(peak, reset, search_window_size, peak_help);
        
        //---- ml.minmax
        
        message_descriptor input(
                                 "list",
                                 "list of float values in which to find minima and maxima",
                                 "0.1 0.5 -0.3 0.1 0.2 -0.1 0.7 0.1 0.3"
                                 );
        
        ranged_message_descriptor<float> minmax_delta(
                                                      "delta",
                                                      "setting the minmax delta. Input values will be considered to be peaks if they are greater than the previous and next value by at least the delta value",
                                                      0,
                                                      1,
                                                      0.1
                                                      );
        
        descriptors[ml::k_minmax].add_message_descriptor(input, minmax_delta);
        
        //---- ml.zerox
        
        valued_message_descriptor<float> zerox_map(
                                                   "map",
                                                   "a stream of input values in which to detect zero crossings",
                                                   0.5
                                                   );
        
        ranged_message_descriptor<float> dead_zone_threshold(
                                                             "dead_zone_threshold",
                                                             "set the dead zone threshold",
                                                             0.f,
                                                             1.f,
                                                             0.01f
                                                             );
        
        ranged_message_descriptor<int> zerox_search_window_size(
                                                          "search_window_size",
                                                          "set the search window size in values",
                                                          1,
                                                          500,
                                                          20
                                                          );
        
        descriptors[ml::k_zerox].add_message_descriptor(zerox_map, dead_zone_threshold, zerox_search_window_size);
    }
Пример #20
0
// Cursor control
int PCBNEW_CONTROL::CursorControl( const TOOL_EVENT& aEvent )
{
    long type = aEvent.Parameter<long>();
    bool fastMove = type & COMMON_ACTIONS::CURSOR_FAST_MOVE;
    type &= ~COMMON_ACTIONS::CURSOR_FAST_MOVE;

    GRID_HELPER gridHelper( m_frame );
    VECTOR2D cursor = getViewControls()->GetCursorPosition();
    VECTOR2I gridSize = gridHelper.GetGrid();
    VECTOR2D newCursor = gridHelper.Align( cursor );

    if( fastMove )
        gridSize = gridSize * 10;

    switch( type )
    {
        case COMMON_ACTIONS::CURSOR_UP:
            newCursor -= VECTOR2D( 0, gridSize.y );
            break;

        case COMMON_ACTIONS::CURSOR_DOWN:
            newCursor += VECTOR2D( 0, gridSize.y );
            break;

        case COMMON_ACTIONS::CURSOR_LEFT:
            newCursor -= VECTOR2D( gridSize.x, 0 );
            break;

        case COMMON_ACTIONS::CURSOR_RIGHT:
            newCursor += VECTOR2D( gridSize.x, 0 );
            break;

        case COMMON_ACTIONS::CURSOR_CLICK:              // fall through
        case COMMON_ACTIONS::CURSOR_DBL_CLICK:
        {
            TOOL_ACTIONS action = TA_NONE;
            int modifiers = 0;

            modifiers |= wxGetKeyState( WXK_SHIFT ) ? MD_SHIFT : 0;
            modifiers |= wxGetKeyState( WXK_CONTROL ) ? MD_CTRL : 0;
            modifiers |= wxGetKeyState( WXK_ALT ) ? MD_ALT : 0;

            if( type == COMMON_ACTIONS::CURSOR_CLICK )
                action = TA_MOUSE_CLICK;
            else if( type == COMMON_ACTIONS::CURSOR_DBL_CLICK )
                action = TA_MOUSE_DBLCLICK;
            else
                assert( false );

            TOOL_EVENT evt( TC_MOUSE, action, BUT_LEFT | modifiers );
            evt.SetMousePosition( getViewControls()->GetCursorPosition() );
            m_toolMgr->ProcessEvent( evt );

            return 0;
        }
        break;
    }

    // Handler cursor movement
    KIGFX::VIEW* view = getView();
    newCursor = view->ToScreen( newCursor );
    newCursor.x = KiROUND( newCursor.x );
    newCursor.y = KiROUND( newCursor.y );

    // Pan the screen if required
    const VECTOR2I& screenSize = view->GetGAL()->GetScreenPixelSize();
    BOX2I screenBox( VECTOR2I( 0, 0 ), screenSize );

    if( !screenBox.Contains( newCursor ) )
    {
        VECTOR2D delta( 0, 0 );

        if( newCursor.x < screenBox.GetLeft() )
        {
            delta.x = newCursor.x - screenBox.GetLeft();
            newCursor.x = screenBox.GetLeft();
        }
        else if( newCursor.x > screenBox.GetRight() )
        {
            delta.x = newCursor.x - screenBox.GetRight();
            // -1 is to keep the cursor within the drawing area,
            // so the cursor coordinates are still updated
            newCursor.x = screenBox.GetRight() - 1;
        }

        if( newCursor.y < screenBox.GetTop() )
        {
            delta.y = newCursor.y - screenBox.GetTop();
            newCursor.y = screenBox.GetTop();
        }
        else if( newCursor.y > screenBox.GetBottom() )
        {
            delta.y = newCursor.y - screenBox.GetBottom();
            // -1 is to keep the cursor within the drawing area,
            // so the cursor coordinates are still updated
            newCursor.y = screenBox.GetBottom() - 1;
        }

        view->SetCenter( view->GetCenter() + view->ToWorld( delta, false ) );
    }

    m_frame->GetGalCanvas()->WarpPointer( newCursor.x, newCursor.y );

    return 0;
}
void Foam::layerAR::addZonesAndModifiers()
{
    // Add the zones and mesh modifiers to operate piston motion

    if
    (
        pointZones().size() > 0
     || faceZones().size() > 0
     || cellZones().size() > 0
    )
    {
        Info<< "void layerAR::addZonesAndModifiers() : "
            << "Zones and modifiers already present.  Skipping."
            << endl;

        if (topoChanger_.size() == 0)
        {
            FatalErrorIn
            (
                "void layerAR::addZonesAndModifiers()"
            )   << "Mesh modifiers not read properly"
                << abort(FatalError);
        }

        setVirtualPistonPosition();
        checkAndCalculate();

        return;
    }

    checkAndCalculate();

    Info<< "Time = " << engTime().theta() << endl
        << "Adding zones to the engine mesh" << endl;

    //fz = 1: faces where layer are added/removed
    //pz = 2: points below the virtual piston faces and head points

    List<pointZone*> pz(2);
    List<faceZone*> fz(1);
    List<cellZone*> cz(0);

    label nPointZones = 0;
    label nFaceZones = 0;

    // Add the piston zone
    if (piston().patchID().active() && offSet() > SMALL)
    {

        // Piston position

        label pistonPatchID = piston().patchID().index();

        scalar zPist = max(boundary()[pistonPatchID].patch().localPoints()).z();

        scalar zPistV = zPist + offSet();

        labelList zone1(faceCentres().size());
        boolList flipZone1(faceCentres().size(), false);
        label nZoneFaces1 = 0;

        bool foundAtLeastOne = false;
        scalar zHigher = GREAT;
        scalar dh = GREAT;
        scalar dl = GREAT;

        forAll (faceCentres(), faceI)
        {
            scalar zc = faceCentres()[faceI].z();
            vector n = faceAreas()[faceI]/mag(faceAreas()[faceI]);
            scalar dd = n & vector(0,0,1);

            if (dd > 0.1)
            {
                if (zPistV - zc > 0 && zPistV - zc < dl)
                {
                    dl = zPistV - zc;
                }

                if (zc - zPistV > 0 && zc - zPistV < dh)
                {
                    zHigher = zc;
                    dh = zc - zHigher;
                }

                if
                (
                    zc > zPistV - delta()
                    && zc < zPistV + delta()
                )
                {
                    foundAtLeastOne = true;
                    if ((faceAreas()[faceI] & vector(0,0,1)) < 0)
                    {
                        flipZone1[nZoneFaces1] = true;
                    }

                    zone1[nZoneFaces1] = faceI;
                    nZoneFaces1++;
                }
            }
        }
Пример #22
0
int get_source(sym_file* symbols, UInt32 codeOffset, char symbolName[256], char fileName[256], UInt32* fileOffset)
{
	const DiskSymbolHeaderBlock& header = symbols->mHeader;
	const ResourceTableEntry& codeEntry = symbols->mCodeEntry;

	// since module entries can't span pages, must compute which page module entry size.
	UInt32 modulesPerPage = (header.dshb_page_size / sizeof(ModulesTableEntry));

	// search for MTE nearest specified offset.
	// seek to first MTE.
	for (UInt16 i = codeEntry.rte_mte_first; i <= codeEntry.rte_mte_last; i++) {
		ModulesTableEntry moduleEntry;
		UInt32 modulePage = (i / modulesPerPage);
		UInt32 moduleIndex = (i % modulesPerPage);
		symbols->seek((header.dshb_mte.dti_first_page + modulePage) * header.dshb_page_size + moduleIndex * sizeof(ModulesTableEntry));
		if (symbols->read(&moduleEntry, sizeof(moduleEntry)) == sizeof(moduleEntry)) {
			if (isMeatyModule(moduleEntry) && (codeOffset >= moduleEntry.mte_res_offset) && (codeOffset - moduleEntry.mte_res_offset) < moduleEntry.mte_size) {
				FileReferenceTableEntry frte;
				if (getFileReferenceTableEntry(symbols, moduleEntry.mte_imp_fref, &frte)) {
					UInt32 length;
					// get the name of the symbol.
					const UInt8* moduleName = symbols->getName(moduleEntry.mte_nte_index);
					// printf("module name = %#s\n", moduleName);
					// trim off the leading "."
					length = moduleName[0] - 1;
					BlockMoveData(moduleName + 2, symbolName, length);
					symbolName[length] = '\0';
					// get the name of the file.
					const UInt8* name = symbols->getName(frte.frte_fn.nte_index);
					length = name[0];
					BlockMoveData(name + 1, fileName, length);
					fileName[length] = '\0';
					// printf("file name = %s\n", fileName);
					// try to refine the location, using the contained statements table entries.
					UInt32 closestFileOffset = moduleEntry.mte_imp_fref.fref_offset;
					UInt32 closestCodeOffset = moduleEntry.mte_res_offset;
					UInt32 closestCodeDelta = 0xFFFFFFFF;
					UInt32 currentFileOffset, currentCodeOffset = moduleEntry.mte_res_offset, currentCodeDelta;
					for (UInt32 j = moduleEntry.mte_csnte_idx_1; j <= moduleEntry.mte_csnte_idx_2; j++) {
						// only consider offsets less than the actual code offset, so we'll be sure
						// to match the nearest line before the code offset. this could probably be
						// a termination condition as well.
						if (currentCodeOffset > codeOffset)
							break;
						ContainedStatementsTableEntry statementEntry;
						if (getContainedStatementTableEntry(symbols, j, &statementEntry)) {
							switch (statementEntry.csnte_file.change) {
							case kSourceFileChange:
								currentFileOffset = statementEntry.csnte_file.fref.fref_offset;
								break;
							case kEndOfList:
								break;
							default:
								currentFileOffset += statementEntry.csnte.file_delta;
								currentCodeOffset = moduleEntry.mte_res_offset + statementEntry.csnte.mte_offset;
								if (currentCodeOffset <= codeOffset) {
									currentCodeDelta = delta(currentCodeOffset, codeOffset);
									if (currentCodeDelta < closestCodeDelta) {
										closestFileOffset = currentFileOffset;
										closestCodeOffset = currentCodeOffset;
										closestCodeDelta = currentCodeDelta;
									}
								}
								break;
							}
						}
					}
					*fileOffset = closestFileOffset;
					// printf("closest file offset = %d\n", closestFileOffset);
					// printf("closest code offset = %d\n", closestCodeOffset);
					return 1;
				}
			}
		}
	}
	return 0;
}
Пример #23
0
void Pitch_pathFinder (Pitch me, double silenceThreshold, double voicingThreshold,
	double octaveCost, double octaveJumpCost, double voicedUnvoicedCost,
	double ceiling, int pullFormants)
{
	if (Melder_debug == 33)
		Melder_casual (U"Pitch path finder:"
			U"\nSilence threshold = ", silenceThreshold,
			U"\nVoicing threshold = ", voicingThreshold,
			U"\nOctave cost = ", octaveCost,
			U"\nOctave jump cost = ", octaveJumpCost,
			U"\nVoiced/unvoiced cost = ", voicedUnvoicedCost,
			U"\nCeiling = ", ceiling,
			U"\nPull formants = ", pullFormants);
	try {
		long maxnCandidates = Pitch_getMaxnCandidates (me);
		long place;
		volatile double maximum, value;
		double ceiling2 = pullFormants ? 2 * ceiling : ceiling;
		/* Next three lines 20011015 */
		double timeStepCorrection = 0.01 / my dx;
		octaveJumpCost *= timeStepCorrection;
		voicedUnvoicedCost *= timeStepCorrection;

		my ceiling = ceiling;
		autoNUMmatrix <double> delta (1, my nx, 1, maxnCandidates);
		autoNUMmatrix <long> psi (1, my nx, 1, maxnCandidates);

		for (long iframe = 1; iframe <= my nx; iframe ++) {
			Pitch_Frame frame = & my frame [iframe];
			double unvoicedStrength = silenceThreshold <= 0 ? 0 :
				2 - frame->intensity / (silenceThreshold / (1 + voicingThreshold));
			unvoicedStrength = voicingThreshold + (unvoicedStrength > 0 ? unvoicedStrength : 0);
			for (long icand = 1; icand <= frame->nCandidates; icand ++) {
				Pitch_Candidate candidate = & frame->candidate [icand];
				int voiceless = candidate->frequency == 0 || candidate->frequency > ceiling2;
				delta [iframe] [icand] = voiceless ? unvoicedStrength :
					candidate->strength - octaveCost * NUMlog2 (ceiling / candidate->frequency);
			}
		}

		/* Look for the most probable path through the maxima. */
		/* There is a cost for the voiced/unvoiced transition, */
		/* and a cost for a frequency jump. */

		for (long iframe = 2; iframe <= my nx; iframe ++) {
			Pitch_Frame prevFrame = & my frame [iframe - 1], curFrame = & my frame [iframe];
			double *prevDelta = delta [iframe - 1], *curDelta = delta [iframe];
			long *curPsi = psi [iframe];
			for (long icand2 = 1; icand2 <= curFrame -> nCandidates; icand2 ++) {
				double f2 = curFrame -> candidate [icand2]. frequency;
				maximum = -1e30;
				place = 0;
				for (long icand1 = 1; icand1 <= prevFrame -> nCandidates; icand1 ++) {
					double f1 = prevFrame -> candidate [icand1]. frequency;
					double transitionCost;
					bool previousVoiceless = f1 <= 0 || f1 >= ceiling2;
					bool currentVoiceless = f2 <= 0 || f2 >= ceiling2;
					if (currentVoiceless) {
						if (previousVoiceless) {
							transitionCost = 0;   // both voiceless
						} else {
							transitionCost = voicedUnvoicedCost;   // voiced-to-unvoiced transition
						}
					} else {
						if (previousVoiceless) {
							transitionCost = voicedUnvoicedCost;   // unvoiced-to-voiced transition
							if (Melder_debug == 30) {
								/*
								 * Try to take into account a frequency jump across a voiceless stretch.
								 */
								long place1 = icand1;
								for (long jframe = iframe - 2; jframe >= 1; jframe --) {
									place1 = psi [jframe + 1] [place1];
									f1 = my frame [jframe]. candidate [place1]. frequency;
									if (f1 > 0 && f1 < ceiling) {
										transitionCost += octaveJumpCost * fabs (NUMlog2 (f1 / f2)) / (iframe - jframe);
										break;
									}
								}
							}
						} else {
							transitionCost = octaveJumpCost * fabs (NUMlog2 (f1 / f2));   // both voiced
						}
					}
					value = prevDelta [icand1] - transitionCost + curDelta [icand2];
					//if (Melder_debug == 33) Melder_casual ("Frame %ld, current candidate %ld (delta %g), previous candidate %ld (delta %g), "
					//	"transition cost %g, value %g, maximum %g", iframe, icand2, curDelta [icand2], icand1, prevDelta [icand1], transitionCost, value, maximum);
					if (value > maximum) {
						maximum = value;
						place = icand1;
					} else if (value == maximum) {
						if (Melder_debug == 33)
							Melder_casual (
								U"A tie in frame ", iframe,
								U", current candidate ", icand2,
								U", previous candidate ", icand1
							);
					}
				}
				curDelta [icand2] = maximum;
				curPsi [icand2] = place;
			}
		}

		/* Find the end of the most probable path. */

		place = 1;
		maximum = delta [my nx] [place];
		for (long icand = 2; icand <= my frame [my nx]. nCandidates; icand ++) {
			if (delta [my nx] [icand] > maximum) {
				place = icand;
				maximum = delta [my nx] [place];
			}
		}

		/* Backtracking: follow the path backwards. */

		for (long iframe = my nx; iframe >= 1; iframe --) {
			if (Melder_debug == 33)
				Melder_casual (
					U"Frame ", iframe, U":",
					U" swapping candidates 1 and ", place
				);
			Pitch_Frame frame = & my frame [iframe];
			structPitch_Candidate help = frame -> candidate [1];
			frame -> candidate [1] = frame -> candidate [place];
			frame -> candidate [place] = help;
			place = psi [iframe] [place];   // This assignment is challenging to CodeWarrior 11.
		}

		/* Pull formants: devoice frames with frequencies between ceiling and ceiling2. */

		if (ceiling2 > ceiling) {
			if (Melder_debug == 33)
				Melder_casual (U"Pulling formants...");
			for (long iframe = my nx; iframe >= 1; iframe --) {
				Pitch_Frame frame = & my frame [iframe];
				Pitch_Candidate winner = & frame -> candidate [1];
				double f = winner -> frequency;
				if (f > ceiling && f <= ceiling2) {
					for (long icand = 2; icand <= frame -> nCandidates; icand ++) {
						Pitch_Candidate loser = & frame -> candidate [icand];
						if (loser -> frequency == 0.0) {
							structPitch_Candidate help = * winner;
							* winner = * loser;
							* loser = help;
							break;
						}
					}
				}
			}
		}
	} catch (MelderError) {
		Melder_throw (me, U": path not found.");
	}
}
//-----------------------------------------------------------------------------
// setMorphFromMesh()
//-----------------------------------------------------------------------------
BOOL LLPolyMorphData::setMorphFromMesh(LLPolyMesh *morph)
{
	if (!morph)
		return FALSE;

	LLVector4a *morph_coords     = morph->getWritableCoords();
	LLVector4a *morph_normals    = morph->getWritableNormals();
	LLVector4a *morph_binormals  = morph->getWritableBinormals();
	LLVector2 *morph_tex_coords = morph->getWritableTexCoords();

	// We now have the morph loaded as a mesh.  We have to subtract the
	// base mesh to get the delta morph.

	LLPolyMesh delta(mMesh, NULL);
	U32 nverts = delta.getNumVertices();

	LLVector4a *delta_coords     = delta.getWritableCoords();
	LLVector4a *delta_normals    = delta.getWritableNormals();
	LLVector4a *delta_binormals  = delta.getWritableBinormals();
	LLVector2 *delta_tex_coords = delta.getWritableTexCoords();

	U32 num_significant = 0;
	U32 vert_index;
	for( vert_index = 0; vert_index < nverts; vert_index++)
	{
		delta_coords[vert_index].setSub(	morph_coords[vert_index], delta_coords[vert_index]);
		delta_normals[vert_index].setSub(	morph_normals[vert_index], delta_normals[vert_index]);
		delta_binormals[vert_index].setSub(	morph_binormals[vert_index], delta_binormals[vert_index]);
		delta_tex_coords[vert_index] =		morph_tex_coords[vert_index] - delta_tex_coords[vert_index];

		// For the normals and binormals, we really want the deltas
		// to be perpendicular to the mesh (bi)normals in the plane
		// that contains both the mesh and morph (bi)normals, such
		// that the morph (bi)normals form the hypotenuses of right
		// triangles. Right now, we just compute the difference vector.

		if (delta_coords[vert_index].getLength3().getF32()		> SIGNIFICANT_DELTA
		||  delta_normals[vert_index].getLength3().getF32()		> SIGNIFICANT_DELTA
		||  delta_binormals[vert_index].getLength3().getF32()	> SIGNIFICANT_DELTA
		||  delta_tex_coords[vert_index].length()				> SIGNIFICANT_DELTA)
		{
			num_significant++;
		}
	}

	//-------------------------------------------------------------------------
	// compute new morph
	//-------------------------------------------------------------------------

	// If the morph matches the base mesh, we store one vertex to prevent
	// zero length vectors.

	U32 nindices = num_significant;
	if (num_significant == 0)
		nindices = 1;

	LLVector4a* new_coords     = new LLVector4a[nindices];
	LLVector4a* new_normals    = new LLVector4a[nindices];
	LLVector4a* new_binormals  = new LLVector4a[nindices];
	LLVector2* new_tex_coords = new LLVector2[nindices];
	U32* new_vertex_indices   = new U32[nindices];

    // We'll set the distortion directly
	mTotalDistortion = 0.f;
	mMaxDistortion   = 0.f;
	mAvgDistortion.clear();

	U32 morph_index = 0;
	for( vert_index = 0; vert_index < nverts; vert_index++)
	{
		if (delta_coords[vert_index].getLength3().getF32()		> SIGNIFICANT_DELTA
		||  delta_normals[vert_index].getLength3().getF32()		> SIGNIFICANT_DELTA
		||  delta_binormals[vert_index].getLength3().getF32()	> SIGNIFICANT_DELTA
		||  delta_tex_coords[vert_index].length()				> SIGNIFICANT_DELTA
		||  num_significant == 0)
		{
			new_vertex_indices[morph_index] = vert_index;

			new_coords[morph_index]     = delta_coords[vert_index];
			new_normals[morph_index]    = delta_normals[vert_index];
			new_binormals[morph_index]  = delta_binormals[vert_index];
			new_tex_coords[morph_index] = delta_tex_coords[vert_index];

			F32 magnitude = new_coords[morph_index].getLength3().getF32();

			mTotalDistortion += magnitude;
			LLVector4a t;
			t.setAbs(new_coords[morph_index]);
			mAvgDistortion.add(t);

			if (magnitude > mMaxDistortion)
			{
				mMaxDistortion = magnitude;
			}

			morph_index++;
			num_significant = 1;
		}
	}

	mAvgDistortion.mul(1.f/(F32)nindices);
	mAvgDistortion.normalize3();

	//-------------------------------------------------------------------------
	// compute the change in the morph
	//-------------------------------------------------------------------------

	// Because meshes are set by continually updating morph weights
	// there is no easy way to reapply the morphs, so we just compute
	// the change in this morph and apply that appropriately weighted.

	for( morph_index = 0; morph_index < mNumIndices; morph_index++)
	{
		vert_index = mVertexIndices[morph_index];

		delta_coords[vert_index].sub(	mCoords[morph_index]);
		delta_normals[vert_index].sub(	mNormals[morph_index]);
		delta_binormals[vert_index].sub(mBinormals[morph_index]);
		delta_tex_coords[vert_index] -= mTexCoords[morph_index];
	}

	//-------------------------------------------------------------------------
	// Update all avatars
	//-------------------------------------------------------------------------

	std::vector< LLCharacter* >::iterator avatar_it;
	for(avatar_it = LLCharacter::sInstances.begin(); avatar_it != LLCharacter::sInstances.end(); ++avatar_it)
	{
		LLVOAvatar* avatarp = (LLVOAvatar*)*avatar_it;

		LLPolyMorphTarget* param = (LLPolyMorphTarget*) avatarp->getVisualParam(mName.c_str());
		if (!param)
		{
			continue;
		}

		F32 weight = param->getLastWeight();
		if (weight == 0.0f)
		{
			continue;
		}

		LLPolyMesh* mesh = avatarp->getMesh(mMesh);
		if (!mesh)
		{
			continue;
		}

		// If we have a vertex mask, just remove it.  It will be recreated.
		/*if (param->undoMask(TRUE))
		{
			continue;
		}*/

		LLVector4a *mesh_coords           = mesh->getWritableCoords();
		LLVector4a *mesh_normals          = mesh->getWritableNormals();
		LLVector4a *mesh_binormals        = mesh->getWritableBinormals();
		LLVector2 *mesh_tex_coords        = mesh->getWritableTexCoords();
		LLVector4a *mesh_scaled_normals   = mesh->getScaledNormals();
		LLVector4a *mesh_scaled_binormals = mesh->getScaledBinormals();

		for( vert_index = 0; vert_index < nverts; vert_index++)
		{
			delta_coords[vert_index].mul(weight);
			mesh_coords[vert_index].add(delta_coords[vert_index]);

			mesh_tex_coords[vert_index]       += delta_tex_coords[vert_index] * weight;

			delta_normals[vert_index].mul(weight * NORMAL_SOFTEN_FACTOR);
			mesh_scaled_normals[vert_index].add(delta_normals[vert_index]);
			
			LLVector4a normalized_normal       = mesh_scaled_normals[vert_index];
			normalized_normal.normalize3();
			mesh_normals[vert_index]           = normalized_normal;

			delta_binormals[vert_index].mul(weight * NORMAL_SOFTEN_FACTOR);
			mesh_scaled_binormals[vert_index].add(delta_binormals[vert_index]);

			LLVector4a tangent;
			tangent.setCross3(mesh_scaled_binormals[vert_index], normalized_normal);
			LLVector4a normalized_binormal;
			normalized_binormal.setCross3(normalized_normal, tangent);
			normalized_binormal.normalize3();
			mesh_binormals[vert_index]         = normalized_binormal;
		}

		avatarp->dirtyMesh();
	}

	//-------------------------------------------------------------------------
	// reallocate vertices
	//-------------------------------------------------------------------------
	delete [] mVertexIndices;
	delete [] mCoords;
	delete [] mNormals;
	delete [] mBinormals;
	delete [] mTexCoords;

	mVertexIndices = new_vertex_indices;
	mCoords        = new_coords;
	mNormals       = new_normals;
	mBinormals     = new_binormals;
	mTexCoords     = new_tex_coords;
	mNumIndices    = nindices;

	return TRUE;
}
Пример #25
0
//***************************************************************************
// code below is used for multiple child processes
//***************************************************************************
void main(int argc, char *argv[])
{
   int row, col, pipe_end, symbol, usec;
   sem_t *sem_video, *sem_me;
   char str[100];     // str for common usage

// sprintf(str, "%s%s%s%u%s", "echo '-- debug ", symbol=='C'?"chaser":"runner", " -- PID: ", getpid(), "'  > /dev/pts/5");
// system(str);

   row = atoi( argv[1] );
   col = atoi( argv[2] );
   pipe_end = atoi( argv[3] );
   symbol = argv[4][0];    // my assigned symbol, 'C' or 'R'

// sprintf(str, "%s%s%s%u%s%u%s", "echo '-- debug ", symbol=='C'?"chaser":"runner", " -- Starting Row,Col: ", row, ",", col, "'  > /dev/pts/5");
// system(str);

   sprintf(str, "%u", getppid()); // get parent pid to build key str
   sem_video = sem_open( str, O_CREAT, S_IRWXU, 0 ); // obtain semaphore

   sprintf(str, "%u", symbol+getppid()); // get parent pid PLUS MY SYMBOL to build key str
   sem_me = sem_open( str, O_CREAT, S_IRWXU, 0 ); // obtain semaphore

	/*
	 * Let's initiate some randomness based on the current time,
	 * then seed random randomly to be more random.
	 */
	srand( (unsigned int)time(NULL) );
/*	int k; for (k=0; k<rand()%100+50; k++) srand( rand() );*/

char tmp[100]; strcpy(tmp, str);
// sprintf(str, "%s%s%s%s%s", "echo '-- debug ", symbol=='C'?"chaser":"runner", " -- sem key: ", tmp, "'  > /dev/pts/5");
// system( str );

   while(1)
   {

// system( symbol=='C'?"echo -- debug chaser 1 > /dev/pts/5":"echo -- debug runner 1 > /dev/pts/5" );
      sem_wait( sem_me ); // wait until parent post (so can syn children)

// system( symbol=='C'?"echo -- debug chaser 2 > /dev/pts/5":"echo -- debug runner 2 > /dev/pts/5" );

      PutChar( row, col, symbol, sem_video );     // show symbol 1st

// system( symbol=='C'?"echo -- debug chaser 3 > /dev/pts/5":"echo -- debug runner 3 > /dev/pts/5" );


// sprintf(str, "%s%s%s%i%s", "echo '-- debug ", symbol=='C'?"chaser":"runner", " -- row: ", row, "'  > /dev/pts/5");
// system( str );
// sprintf(str, "%s%s%s%i%s", "echo '-- debug ", symbol=='C'?"chaser":"runner", " -- col: ", col, "'  > /dev/pts/5");
// system( str );
      //write to pipe... tell parent where I'm (row)
      write(pipe_end, &row, sizeof(int));
      //write to pipe... tell parent where I'm (col)
      write(pipe_end, &col, sizeof(int));

// system( symbol=='C'?"echo -- debug chaser 4 > /dev/pts/5":"echo -- debug runner 4 > /dev/pts/5" );


      usec = USEC;      // sleep period may be 1/2/or 3 portions of USEC
      usleep(usec);

// system( symbol=='C'?"echo -- debug chaser 5 > /dev/pts/5":"echo -- debug runner 5 > /dev/pts/5" );

      PutChar( row, col, ' ', sem_video );  // put out a space (erase)

// system( symbol=='C'?"echo -- debug chaser 6 > /dev/pts/5":"echo -- debug runner 6 > /dev/pts/5" );

      if(row == 1) row += delta(true, false);
      else if(row == MAX_ROW) row += delta(false, true);
      else row += delta(false, false);
      if(col == 1) col += delta(true, false);
      else if(col == MAX_COL) col += delta(false, true);
      else col += delta(false, false);

// system( symbol=='C'?"echo -- debug chaser 7 > /dev/pts/5":"echo -- debug runner 7 > /dev/pts/5" );
   }
}
Пример #26
0
osg::Camera* createHUD()
{
    // create a camera to set up the projection and model view matrices, and the subgraph to drawn in the HUD
    osg::Camera* camera = new osg::Camera;

    // set the projection matrix
    camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1280,0,1024));

    // set the view matrix    
    camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
    camera->setViewMatrix(osg::Matrix::identity());

    // only clear the depth buffer
    camera->setClearMask(GL_DEPTH_BUFFER_BIT);

    // draw subgraph after main camera view.
    camera->setRenderOrder(osg::Camera::POST_RENDER);

    // we don't want the camera to grab event focus from the viewers main camera(s).
    camera->setAllowEventFocus(false);
    


    // add to this camera a subgraph to render
    {

        osg::Geode* geode = new osg::Geode();

        std::string timesFont("fonts/arial.ttf");

        // turn lighting off for the text and disable depth test to ensure its always ontop.
        osg::StateSet* stateset = geode->getOrCreateStateSet();
        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);

        osg::Vec3 position(150.0f,800.0f,0.0f);
        osg::Vec3 delta(0.0f,-120.0f,0.0f);

        {
            osgText::Text* text = new  osgText::Text;
            geode->addDrawable( text );

            text->setFont(timesFont);
            text->setPosition(position);
            text->setText("Head Up Displays are simple :-)");

            position += delta;
        }    


        {
            osgText::Text* text = new  osgText::Text;
            geode->addDrawable( text );

            text->setFont(timesFont);
            text->setPosition(position);
            text->setText("All you need to do is create your text in a subgraph.");

            position += delta;
        }    


        {
            osgText::Text* text = new  osgText::Text;
            geode->addDrawable( text );

            text->setFont(timesFont);
            text->setPosition(position);
            text->setText("Then place an osg::Camera above the subgraph\n"
                          "to create an orthographic projection.\n");

            position += delta;
        } 

        {
            osgText::Text* text = new  osgText::Text;
            geode->addDrawable( text );

            text->setFont(timesFont);
            text->setPosition(position);
            text->setText("Set the Camera's ReferenceFrame to ABSOLUTE_RF to ensure\n"
                          "it remains independent from any external model view matrices.");

            position += delta;
        } 

        {
            osgText::Text* text = new  osgText::Text;
            geode->addDrawable( text );

            text->setFont(timesFont);
            text->setPosition(position);
            text->setText("And set the Camera's clear mask to just clear the depth buffer.");

            position += delta;
        }    

        {
            osgText::Text* text = new  osgText::Text;
            geode->addDrawable( text );

            text->setFont(timesFont);
            text->setPosition(position);
            text->setText("And finally set the Camera's RenderOrder to POST_RENDER\n"
                          "to make sure its drawn last.");

            position += delta;
        }    


        {
            osg::BoundingBox bb;
            for(unsigned int i=0;i<geode->getNumDrawables();++i)
            {
                bb.expandBy(geode->getDrawable(i)->getBound());
            }

            osg::Geometry* geom = new osg::Geometry;

            osg::Vec3Array* vertices = new osg::Vec3Array;
            float depth = bb.zMin()-0.1;
            vertices->push_back(osg::Vec3(bb.xMin(),bb.yMax(),depth));
            vertices->push_back(osg::Vec3(bb.xMin(),bb.yMin(),depth));
            vertices->push_back(osg::Vec3(bb.xMax(),bb.yMin(),depth));
            vertices->push_back(osg::Vec3(bb.xMax(),bb.yMax(),depth));
            geom->setVertexArray(vertices);

            osg::Vec3Array* normals = new osg::Vec3Array;
            normals->push_back(osg::Vec3(0.0f,0.0f,1.0f));
            geom->setNormalArray(normals);
            geom->setNormalBinding(osg::Geometry::BIND_OVERALL);

            osg::Vec4Array* colors = new osg::Vec4Array;
            colors->push_back(osg::Vec4(1.0f,1.0,0.8f,0.2f));
            geom->setColorArray(colors);
            geom->setColorBinding(osg::Geometry::BIND_OVERALL);

            geom->addPrimitiveSet(new osg::DrawArrays(GL_QUADS,0,4));

            osg::StateSet* stateset = geom->getOrCreateStateSet();
            stateset->setMode(GL_BLEND,osg::StateAttribute::ON);
            //stateset->setAttribute(new osg::PolygonOffset(1.0f,1.0f),osg::StateAttribute::ON);
            stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);

            geode->addDrawable(geom);
        }

        camera->addChild(geode);
    }

    return camera;
}
Пример #27
0
 double delta( const item_t& item ) const { return delta( &item ); }
Пример #28
0
		//----------------------------------------------
		//----------------------------------------------
		void PointerSystem::OnMouseWheeled(s32 in_delta)
		{
            ChilliSource::Vector2 delta(0.0f, (f32)in_delta);
            AddPointerScrollEvent(m_pointerId, delta);
		}
Пример #29
0
///combined discrete/continuous sphere-triangle
bool SphereTriangleDetector::collide(const btVector3& sphereCenter,btVector3 &point, btVector3& resultNormal, btScalar& depth, btScalar &timeOfImpact, btScalar contactBreakingThreshold)
{

	const btVector3* vertices = &m_triangle->getVertexPtr(0);
	const btVector3& c = sphereCenter;
	btScalar r = m_sphere->getRadius();

	btVector3 delta (0,0,0);

	btVector3 normal = (vertices[1]-vertices[0]).cross(vertices[2]-vertices[0]);
	normal.normalize();
	btVector3 p1ToCentre = c - vertices[0];
	btScalar distanceFromPlane = p1ToCentre.dot(normal);

	if (distanceFromPlane < btScalar(0.))
	{
		//triangle facing the other way
	
		distanceFromPlane *= btScalar(-1.);
		normal *= btScalar(-1.);
	}

	btScalar contactMargin = contactBreakingThreshold;
	bool isInsideContactPlane = distanceFromPlane < r + contactMargin;
	bool isInsideShellPlane = distanceFromPlane < r;
	
	btScalar deltaDotNormal = delta.dot(normal);
	if (!isInsideShellPlane && deltaDotNormal >= btScalar(0.0))
		return false;

	// Check for contact / intersection
	bool hasContact = false;
	btVector3 contactPoint;
	if (isInsideContactPlane) {
		if (facecontains(c,vertices,normal)) {
			// Inside the contact wedge - touches a point on the shell plane
			hasContact = true;
			contactPoint = c - normal*distanceFromPlane;
		} else {
			// Could be inside one of the contact capsules
			btScalar contactCapsuleRadiusSqr = (r + contactMargin) * (r + contactMargin);
			btVector3 nearestOnEdge;
			for (int i = 0; i < m_triangle->getNumEdges(); i++) {
				
				btVector3 pa;
				btVector3 pb;
				
				m_triangle->getEdge(i,pa,pb);

				btScalar distanceSqr = SegmentSqrDistance(pa,pb,c, nearestOnEdge);
				if (distanceSqr < contactCapsuleRadiusSqr) {
					// Yep, we're inside a capsule
					hasContact = true;
					contactPoint = nearestOnEdge;
				}
				
			}
		}
	}

	if (hasContact) {
		btVector3 contactToCentre = c - contactPoint;
		btScalar distanceSqr = contactToCentre.length2();
		if (distanceSqr < (r - MAX_OVERLAP)*(r - MAX_OVERLAP)) {
			btScalar distance = btSqrt(distanceSqr);
			resultNormal = contactToCentre;
			resultNormal.normalize();
			point = contactPoint;
			depth = -(r-distance);
			return true;
		}

		if (delta.dot(contactToCentre) >= btScalar(0.0)) 
			return false;
		
		// Moving towards the contact point -> collision
		point = contactPoint;
		timeOfImpact = btScalar(0.0);
		return true;
	}
	
	return false;
}
Пример #30
0
int
main(int argc, char *argv[])
{
	/* These are static so that they're initially zero.  */
	static char *		abbrev;
	static size_t		abbrevsize;

	int		i;
	bool		vflag;
	bool		Vflag;
	char *		cutarg;
	char *		cuttimes;
	time_t		cutlotime;
	time_t		cuthitime;
	time_t		now;
	bool iflag = false;

	cutlotime = absolute_min_time;
	cuthitime = absolute_max_time;
#if HAVE_GETTEXT
	(void) setlocale(LC_ALL, "");
#ifdef TZ_DOMAINDIR
	(void) bindtextdomain(TZ_DOMAIN, TZ_DOMAINDIR);
#endif /* defined TEXTDOMAINDIR */
	(void) textdomain(TZ_DOMAIN);
#endif /* HAVE_GETTEXT */
	progname = argv[0];
	for (i = 1; i < argc; ++i)
		if (strcmp(argv[i], "--version") == 0) {
			(void) printf("zdump %s%s\n", PKGVERSION, TZVERSION);
			return EXIT_SUCCESS;
		} else if (strcmp(argv[i], "--help") == 0) {
			usage(stdout, EXIT_SUCCESS);
		}
	vflag = Vflag = false;
	cutarg = cuttimes = NULL;
	for (;;)
	  switch (getopt(argc, argv, "c:it:vV")) {
	  case 'c': cutarg = optarg; break;
	  case 't': cuttimes = optarg; break;
	  case 'i': iflag = true; break;
	  case 'v': vflag = true; break;
	  case 'V': Vflag = true; break;
	  case -1:
	    if (! (optind == argc - 1 && strcmp(argv[optind], "=") == 0))
	      goto arg_processing_done;
	    /* Fall through.  */
	  default:
	    usage(stderr, EXIT_FAILURE);
	  }
 arg_processing_done:;

	if (iflag | vflag | Vflag) {
		intmax_t	lo;
		intmax_t	hi;
		char *loend, *hiend;
		intmax_t cutloyear = ZDUMP_LO_YEAR;
		intmax_t cuthiyear = ZDUMP_HI_YEAR;
		if (cutarg != NULL) {
			lo = strtoimax(cutarg, &loend, 10);
			if (cutarg != loend && !*loend) {
				hi = lo;
				cuthiyear = hi;
			} else if (cutarg != loend && *loend == ','
				   && (hi = strtoimax(loend + 1, &hiend, 10),
				       loend + 1 != hiend && !*hiend)) {
				cutloyear = lo;
				cuthiyear = hi;
			} else {
				fprintf(stderr, _("%s: wild -c argument %s\n"),
					progname, cutarg);
				return EXIT_FAILURE;
			}
		}
		if (cutarg != NULL || cuttimes == NULL) {
			cutlotime = yeartot(cutloyear);
			cuthitime = yeartot(cuthiyear);
		}
		if (cuttimes != NULL) {
			lo = strtoimax(cuttimes, &loend, 10);
			if (cuttimes != loend && !*loend) {
				hi = lo;
				if (hi < cuthitime) {
					if (hi < absolute_min_time)
						hi = absolute_min_time;
					cuthitime = hi;
				}
			} else if (cuttimes != loend && *loend == ','
				   && (hi = strtoimax(loend + 1, &hiend, 10),
				       loend + 1 != hiend && !*hiend)) {
				if (cutlotime < lo) {
					if (absolute_max_time < lo)
						lo = absolute_max_time;
					cutlotime = lo;
				}
				if (hi < cuthitime) {
					if (hi < absolute_min_time)
						hi = absolute_min_time;
					cuthitime = hi;
				}
			} else {
				(void) fprintf(stderr,
					_("%s: wild -t argument %s\n"),
					progname, cuttimes);
				return EXIT_FAILURE;
			}
		}
	}
	gmtzinit();
	INITIALIZE (now);
	if (! (iflag | vflag | Vflag))
	  now = time(NULL);
	longest = 0;
	for (i = optind; i < argc; i++) {
		size_t arglen = strlen(argv[i]);
		if (longest < arglen)
			longest = arglen < INT_MAX ? arglen : INT_MAX;
	}

	for (i = optind; i < argc; ++i) {
		timezone_t tz = tzalloc(argv[i]);
		char const *ab;
		time_t t;
		struct tm tm, newtm;
		bool tm_ok;

		if (!tz) {
			errx(EXIT_FAILURE, "%s", argv[i]);
		}
		if (! (iflag | vflag | Vflag)) {
			show(tz, argv[i], now, false);
			tzfree(tz);
			continue;
		}
		warned = false;
		t = absolute_min_time;
		if (! (iflag | Vflag)) {
			show(tz, argv[i], t, true);
			t += SECSPERDAY;
			show(tz, argv[i], t, true);
		}
		if (t < cutlotime)
			t = cutlotime;
		tm_ok = my_localtime_rz(tz, &t, &tm) != NULL;
		if (tm_ok) {
			ab = saveabbr(&abbrev, &abbrevsize, &tm);
			if (iflag) {
				showtrans("\nTZ=%f", &tm, t, ab, argv[i]);
				showtrans("-\t-\t%Q", &tm, t, ab, argv[i]);
			}
		} else
			ab = NULL;
		while (t < cuthitime) {
			time_t newt = ((t < absolute_max_time - SECSPERDAY / 2
			    && t + SECSPERDAY / 2 < cuthitime)
			    ? t + SECSPERDAY / 2 : cuthitime);
			struct tm *newtmp = localtime_rz(tz, &newt, &newtm);
			bool newtm_ok = newtmp != NULL;
			if (! (tm_ok & newtm_ok
			    ? (delta(&newtm, &tm) == newt - t
			    && newtm.tm_isdst == tm.tm_isdst
			    && strcmp(abbr(&newtm), ab) == 0)
			    : tm_ok == newtm_ok)) {
				newt = hunt(tz, argv[i], t, newt);
				newtmp = localtime_rz(tz, &newt, &newtm);
				newtm_ok = newtmp != NULL;
				if (iflag)
					showtrans("%Y-%m-%d\t%L\t%Q",
					    newtmp, newt, newtm_ok ?
					    abbr(&newtm) : NULL, argv[i]);
				else {
					show(tz, argv[i], newt - 1, true);
					show(tz, argv[i], newt, true);
				}
			}
			t = newt;
			tm_ok = newtm_ok;
			if (newtm_ok) {
				ab = saveabbr(&abbrev, &abbrevsize, &newtm);
				tm = newtm;
			}
		}
		if (! (iflag | Vflag)) {
			t = absolute_max_time;
			t -= SECSPERDAY;
			show(tz, argv[i], t, true);
			t += SECSPERDAY;
			show(tz, argv[i], t, true);
		}
		tzfree(tz);
	}
	close_file(stdout);
	if (errout && (ferror(stderr) || fclose(stderr) != 0))
		return EXIT_FAILURE;
	return EXIT_SUCCESS;
}