Exemplo n.º 1
0
/*------------------------------------------------------------------*/
bool AzRgforest::growForest()
{
    clock_t b_time;
    time_begin(&b_time);

    /*---  find the best split  ---*/
    AzTrTsplit best_split;
    searchBestSplit(&best_split);
    if (shouldExit(&best_split)) { /* exit if no more split */
        return true; /* exit */
    }

    /*---  split the node  ---*/
    double w_inc;
    int leaf_nx[2] = {-1,-1};
    const AzRgfTree *tree = splitNode(&best_split, &w_inc, leaf_nx);

    if (lmax_timer.reachedMax(l_num, "AzRgforest: #leaf", out)) {
        return true; /* #leaf reached max; exit */
    }

    /*---  update target  ---*/
    updateTarget(tree, leaf_nx, w_inc);

    time_end(b_time, &search_time);
    return false; /* don't exit */
}
Exemplo n.º 2
0
	void SVIDomeSimulator::update(){
		updateTarget();


       /* float centerX = 0.5f;
        float centerY = 0.5f;

        float heightScale = mControlTarget.x;
        float radius = mControlTarget.y;

        for (SVIInt y = 0; y < mGridSize-1; ++y){
            float yUnitCoord = (float)y / ((float)mGridSize-1);
            float thetaValueY = SVI_PI * yUnitCoord;
            for (SVIInt x = 0; x < mGridSize-1; ++x){
                float xUnitCoord = (float)x / ((float)mGridSize-1);

                float fDistSqr = (xUnitCoord - centerX) * (xUnitCoord - centerX) + (yUnitCoord - centerY) * (yUnitCoord - centerY);
                float fDistRatio = sqrt(fDistSqr) / radius;
                float fEffectiveness = fDistRatio > 1.0f ? 1.0f : fDistRatio; 

                float thetaValue = SVI_PI*0.5f + SVI_PI * 0.5f * fEffectiveness;
                float zFactor = sin(thetaValue) * heightScale;                


                SVIPivot * pPivot = &mPivots[y * mGridSize + x];
                SVIVector3& position = pPivot->getPosition();
                position.z = zFactor;
            }
        }*/
    }
//Manges AIS target list
void manageTargetList(aisP *aisPacket, struct aisTargetLog *targetLog, struct cntyCodes *cc){
    gpsPos myPos; //Get station current GPS coords
    returnGPSPos(&myPos);
            
    if(isNewTarget(targetLog, aisPacket)){
        if(aisPacket->msgType != 24)
            pushTarget(targetLog, aisPacket, cc, &myPos);
    }else{
        if(aisPacket->msgType != 24)
            updateTarget(targetLog, aisPacket, &myPos);
    }

    //Msg type 24, partno 0 contains vessel name
    if(aisPacket->msgType == 24 && aisPacket->partNo == 0)
        updateVesselName(targetLog, aisPacket);
    if(aisPacket->msgType == 24 && aisPacket->partNo == 1)
        updateVesselDetails(targetLog, aisPacket);

    if(aisPacket->msgType == 5 || aisPacket->msgType == 19){
        updateVesselName(targetLog, aisPacket);
        if(aisPacket->length > 0)
            updateVesselDetails(targetLog, aisPacket);
    }

    bubbleSortLinkedListAsc(targetLog);
    printTargetList(targetLog, &myPos);
}
Exemplo n.º 4
0
//------------------------------------------------------------------------------
void Missile::frameMove(float dt)
{
    Projectile::frameMove(dt);


    updateTarget(dt);


    Vector cur_dir = getGlobalLinearVel();
    cur_dir.normalize();

    Vector target_dir = target_ - getPosition();
    float l = target_dir.length();
    if (equalsZero(l)) return;
    target_dir /= l;

    float alpha = acosf(vecDot(&cur_dir, &target_dir));

    if (alpha > agility_*dt )
    {
        Matrix m;
        Vector axis;
        vecCross(&axis, &target_dir, &cur_dir);
        if (!equalsZero(axis.length()))
        {
            m.loadRotationVector(agility_*dt, axis);
            target_dir = m.transformVector(cur_dir);
        } else target_dir = cur_dir;
    }
    setGlobalLinearVel(target_dir*speed_);    
}
Exemplo n.º 5
0
bool ActionBase::update() {
	++m_counter;
	if (m_counter < 0) {
		return false;
	}
	Vec2f pos;
	float alpha;
	const float two_e = 2.f * 2.71828183f;
	float tt = float(m_counter) / float(m_length);
	if (m_inverse) {
		tt = 1.f - tt;
	}
	if (m_startPos != m_destPos) {
		float t = tt;
		if (m_transFuncPos == TransitionFunc::SQUARED) {
			t *= t;
		} else if (m_transFuncPos == TransitionFunc::EXPONENTIAL) {
			t = exp(t * two_e - two_e);
		} else if (m_transFuncPos == TransitionFunc::SQUARE_ROOT) {
			t = sqrt(t);
		} else if (m_transFuncPos == TransitionFunc::LOGARITHMIC) {
			t = (log(t) + two_e) / two_e;
		}
		t = clamp(t, 0.f, 1.f);
		if (m_inverse) {
			pos = m_destPos.lerp(t, m_startPos);
		} else {
			pos = m_startPos.lerp(t, m_destPos);
		}
	} else {
		pos = m_startPos;
	}
	if (m_startAlpha != m_destAlpha) {
		float t = tt;
		if (m_transFuncAlpha == TransitionFunc::SQUARED) {
			t *= t;
		} else if (m_transFuncAlpha == TransitionFunc::EXPONENTIAL) {
			t = exp(t * two_e - two_e);
		} else if (m_transFuncPos == TransitionFunc::SQUARE_ROOT) {
			t = sqrt(t);
		} else if (m_transFuncAlpha == TransitionFunc::LOGARITHMIC) {
			t = (log(t) + two_e) / two_e;
		}
		t = clamp(t, 0.f, 1.f);
		if (m_inverse) {
			alpha = m_destAlpha + (m_startAlpha - m_destAlpha) * t;
		} else {
			alpha = m_startAlpha + (m_destAlpha - m_startAlpha) * t;
		}
	} else {
		alpha = m_startAlpha;
	}
	updateTarget(pos, alpha);
	if (m_counter == m_length) {
		//Finished(this);
		return true;
	}
	return false;
}
Exemplo n.º 6
0
void QStyleAnimation::updateCurrentTime(int)
{
    if (++_skip >= _fps) {
        _skip = 0;
        if (target() && isUpdateNeeded())
            updateTarget();
    }
}
Exemplo n.º 7
0
RandomMover::RandomMover() {

	updateTarget();

	m_fSpeed = 10.0f;

	Game::instance()->registerEventHandler(Event::GAME_UPDATE, this, &RandomMover::update);
}
Exemplo n.º 8
0
void ThirdPersonCamera::control()
{
	float pitchChange = 0.0f;
	float yawChange = 0.0f;
	m_forwardSpeed = 0.0f;


	// SDL_ShowCursor(SDL_DISABLE);
	Uint8* state = SDL_GetKeyState(NULL);

	if (state[SDLK_w])
		m_forwardSpeed = BALL_FORWARD_SPEED;

	if (state[SDLK_s])
		m_forwardSpeed = -BALL_FORWARD_SPEED;

	if (state[SDLK_a])
		yawChange = BALL_HEADING_SPEED;

	if (state[SDLK_d])
		yawChange = -BALL_HEADING_SPEED;

	if (state[SDLK_m])
		m_offsetDistance += 1;

	if (state[SDLK_n])
		m_offsetDistance -= 1;


	if (state[SDLK_l])
		pitchChange += 0.1;

	if (state[SDLK_k])
		pitchChange -= 0.1;


	m_pitch += pitchChange;


//	utl::debug("m_pitch", m_pitch);

	if (m_forwardSpeed < 0)
		m_yaw -= yawChange;
	else
		m_yaw += yawChange;

	if (m_yaw > 360)
		m_yaw -= 360;

	if (m_yaw < -360)
		m_yaw += 360;

	updateTarget();
}
Exemplo n.º 9
0
double BoostedTrees::train(DataSet& train_data, DataSet& test_data){
    double ce, rce, rmse, tce, trce, trmse;
    learnBiasConstant(train_data);
    clock_t clock_begin = clock();
    fprintf(stderr, "training data initialized  ... ok \n");
     //fprintf(stderr, "ok -2\n");
    vector<double> train_preds;
    vector<double> test_preds;
    initVector(train_preds, train_data.size);
    initVector(test_preds, test_data.size);
    eval(train_data, train_preds);
    eval(test_data, test_preds);
    clock_t clock_end = clock();
    train_data.calRCE(train_preds, ce, rce, rmse);
    test_data.calRCE(test_preds, tce, trce, trmse);
    fprintf(stderr, "%d\t%.1f\t%f\t%f\t%f\t%f\t%f\t%f\n", 0,
              double(clock_end - clock_begin)/CLOCKS_PER_SEC,(float)rmse,
              (float)ce, (float) rce, (float)trmse, (float) tce, (float) trce);
    // eval_bdt(bdt, train, args);
     //  fprintf(stderr, "ok -1\n");
    fprintf(stderr, "training ... \n");
    fprintf(stderr, "round\ttime(s)\ttrain_rmse\ttrain_ce\ttrain_rce\ttest_rmse\ttest_ce \ttest_rce\n");


    for (int iter = 0; iter < args.rounds; iter++)  {
        // single regression tree
        DTNode* t = new DTNode(train_data.rawData, args, args.depth, 1, args.kfeatures, false);
        trees.push_back(t);
        //fprintf(stderr, "ok 1\n");
        // get classification on training data

        eval(train_data, train_preds);
        eval(test_data, test_preds);
        train_data.calRCE(train_preds, ce, rce, rmse);
        test_data.calRCE(test_preds, tce, trce, trmse);
        //fprintf(stderr, "ok 4\n");

        clock_end = clock();
        fprintf(stderr, "%d\t%.1f\t%f\t%f\t%f\t%f\t%f\t%f\n", iter,
                double(clock_end - clock_begin)/CLOCKS_PER_SEC,(float)rmse,
                (float)ce, (float) rce, (float)trmse, (float) tce, (float) trce);
        //fprintf(stderr, "ok 5\n");
        //train.update_target(train_preds);

        updateTarget(train_data, train_preds);

        if (args.print_features){
            cout << endl;
            t->printFeature();
            cout << endl;
        }
    }

}
Exemplo n.º 10
0
void QStyleAnimation::updateCurrentTime(int)
{
    if (QObject *tgt = target()) {
        if (tgt->isWidgetType()) {
            QWidget *widget = static_cast<QWidget *>(tgt);
            if (!widget->isVisible() || widget->window()->isMinimized())
                stop();
        }

        if (isUpdateNeeded())
            updateTarget();
    }
}
Exemplo n.º 11
0
void Player::updateSelf( const double & delta )
{
	mAliveTimer += delta;
	mKillTimer += delta;
	mTorchTimer += delta;
	mUsageText = "";

	if( mTextTime > 0.0f && !mTextMessage.isEmpty() )
	{
		mTextZoom += delta*10;
		mTextFade -= delta*50;
		mTextTime -= delta;
	}
	else
	{
		mTextFade = 0.0f;
	}

	if( mGodMode )
	{
		setState( ALIVE );
		setLife( 100 );
	}

	switch( state() )
	{
		case SPAWNING:
			setState( ALIVE );
			break;
		case ALIVE:
			updateRotation( delta );
			updatePosition( delta );
			updateTarget( delta );
			updateTorch( delta );

			if( mCurrentWeapon )
			{
				mCurrentWeapon->setPosition( QVector3D(-0.5f,-0.5f-0.1*QVector3D::dotProduct(QVector3D(0,1,0),direction()), 0.5f ) );
			}

			break;
		case DYING:
			setState( DEAD );
			drawMessage( "GAME OVER!" );
			break;
		case DEAD:
			break;
	}
}
Exemplo n.º 12
0
void RandomMover::update(const Event& e) {

	float delta = e.game.delta;

	GameObject* go = getGameObject();

	glm::vec3 diff = m_vTarget - go->getPosition();

	if (glm::length(diff) <= m_fSpeed * delta) {
	
		go->setPosition(m_vTarget);
		updateTarget();

	} else {
	
		go->setPosition(go->getPosition() + glm::normalize(diff) * m_fSpeed * delta);
	}
}
Exemplo n.º 13
0
void Monster::onThink(Duration elapsedTime) {
	Creature::onThink(elapsedTime);

	if (!isAlive()) {
		return;
	}

	if (despawn()) {
		exitWorld();
		return;
	}

	updateRelationship();
	updateTarget();
	updateRetargeting(elapsedTime);
	updateFollowing();
	updateBabbling(elapsedTime);

	// TODO refactor >>
	onThinkDefense(std::chrono::duration_cast<Milliseconds>(elapsedTime).count());
	// <<
}
Exemplo n.º 14
0
void WorldTestUnitAi :: update ()
{
	m_orrery.addTime(TimeSystem::getFrameDuration());

	mp_explosion_manager->update();

	m_target_disappear_time -= TimeSystem::getFrameDuration();
	updateTarget();
	m_agent.update(*this);

	TimeSystem::markAiStart(0.0f);
	m_agent.runAi(*this);
	m_agent_ai_time_cumulative += TimeSystem::getAiTimeElapsed();

	for(unsigned int i = 0; i < BULLET_COUNT_MAX; i++)
		if(ma_bullets[i].isAlive())
			ma_bullets[i].update(*this);

	checkCollisionsAll();

	assert(invariant());
}
Exemplo n.º 15
0
void WorldTestUnitAi :: reset ()
{
	assert(isModelsLoaded());

	assert(mp_explosion_manager != NULL);
	mp_explosion_manager->removeAll();

	m_orrery.setTime(0.0);

	initRingParticles();

	m_target_disappear_time  = 0.0;
	m_target_shot_count      = 0;
	m_target_collision_count = 0;
	updateTarget();

	m_agent.setPosition(Vector3(-(MOON_RADIUS + AGENT_START_ABOVE_MOON), 0.0, 0.0));
	m_agent.setVelocity(Vector3::getRandomUnitVector() * AGENT_SPEED_MAX);

	// REPLACE WITH YOUR OWN UNIT AI
	//m_agent.setUnitAi(new RedDuck::UnitAiStop(m_agent, *this));
	m_agent.setUnitAi(new SpaceMongols::UnitAiMoonGuard(m_agent, *this, ID_MOON));

	m_agent_collision_last     = PhysicsObjectId::ID_NOTHING;
	m_agent_collision_count    = 0;
	m_agent_ai_time_cumulative = 0.0f;
	m_agent_bullet_count       = 0;

	for(unsigned int i = 0; i < BULLET_COUNT_MAX; i++)
		ma_bullets[i].markDead(true);
	m_next_bullet = 0;

	for(unsigned int i = 0; i < SIMPLE_MARKER_COUNT_MAX; i++)
		ma_simple_markers[i].markDead();
	m_next_simple_marker = 0;

	assert(invariant());
}
Exemplo n.º 16
0
void Enemy::update(float timeStep)
{
	setMoving(false);
	for (auto& e : getManager()->getAll<Player>()) {
		Player* p = reinterpret_cast<Player*>(e);
        if (p->isMoving() && !p->isDead()) {
			setMoving(true);
            break;
        }
    }

    if (!isMoving()) return;

    //Update target depending on players movement and deadness.
    updateTarget();
    if (currentTarget == NULL) return;

    //Determine direction of enemy so correct sprite is drawn.
    updateDirection();

    //Movement phase
    updateMovement(timeStep);

}
void ADynamicCarController::Tick(float DeltaSeconds)
{
	Super::Tick(DeltaSeconds);

	if (play) {
		float deltaSec = GWorld->GetWorld()->GetDeltaSeconds();

		updateTarget();

		if (first) {
			first = false;
			FRotator rotation = agent->GetActorRotation();
			rotation.Yaw = getRotation(agent->GetActorLocation(), target);
			agent->SetActorRotation(rotation);

			if (followPath) {
				waypoints = DubinsPath::getPath(waypoints, to2D(agent->GetActorLocation()), rotation.Yaw, maxAngle, L, graph, errorTolerance);

				writeWaypointsToFile("Waypoints2.txt");

				if (waypoints.Num() > 0) {
					target = waypoints[0];
				}
			}
		}

		if (waypointReached()) {
			bool t35 = followPath && waypointsIndex >= waypoints.Num();
			bool t4 = avoidAgents && !followPath;

			if (t35 || t4) {
				play = false;
				GEngine->AddOnScreenDebugMessage(-1, 50.f, FColor::Green, FString::Printf(TEXT("Time: %f\r\n"), totalTime));
			}

			return;
		}

		float a = getAcceleration(deltaSec);

		v += a;

		v = UKismetMathLibrary::FClamp(v, -vMax, vMax);

		float rotation = rotate(deltaSec);

		FVector vPref = FVector(v * UKismetMathLibrary::DegCos(rotation) * deltaSec, v * UKismetMathLibrary::DegSin(rotation) * deltaSec, 0);

		vPref = vPref.GetClampedToMaxSize2D(UKismetMathLibrary::FMin(v * deltaSec, FVector2D::Distance(to2D(agent->GetActorLocation()), target)));

		FVector oldVel = velocity;

		if (avoidAgents) {
			adjustVelocity(to2D(vPref), deltaSec);
			//velocity = vPref;
		} else {
			velocity = vPref;
		}

		FVector2D q = to2D(velocity - oldVel);
		float dv = FMath::Sqrt(FVector2D::DotProduct(q, q));

		if (dv > aMax * deltaSec) {
			float f = aMax * deltaSec / dv;
			velocity = (1 - f) * oldVel + f * velocity;
		}

		float rot = agent->GetActorRotation().Yaw;

		if (velocity.Size2D() != 0) {
			if (angleDiff(rot, velocity.Rotation().Yaw) > 90) {
				velocity = -velocity;
				setRotation();
				velocity = -velocity;
			} else {
				setRotation();
			}
		}

		/*
		if (UKismetMathLibrary::Abs(angleDiff(rot, agent->GetActorRotation().Yaw)) / deltaSec > maxAngle * (v / L) + 5) {
			GEngine->AddOnScreenDebugMessage(-1, 50.f, FColor::Red, FString::Printf(TEXT("rot: %f yaw: %f -> %f (%f)      %d   %s -> %s"), rot, agent->GetActorRotation().Yaw, angleDiff(rot, agent->GetActorRotation().Yaw), UKismetMathLibrary::Abs(angleDiff(rot, agent->GetActorRotation().Yaw)) / deltaSec, vPref.Equals(velocity), *to2D(vPref).ToString(), *to2D(velocity).ToString()));
			DrawDebugLine(GWorld->GetWorld(), FVector(to2D(agent->GetActorLocation()), 20), FVector(to2D(agent->GetActorLocation()), 30), FColor::Red, false, 0.5, 0, 1);
			GEngine->DeferredCommands.Add(TEXT("pause"));
		}*/

		agent->SetActorLocation(agent->GetActorLocation() + velocity);

		/*
		DrawDebugLine(GWorld->GetWorld(), to3D(target), to3D(target) + collisionSize, collisionColor, false, 0.1, 0, 1);

		float a = getAcceleration(deltaSec);

		v += a;

		v = UKismetMathLibrary::FClamp(v, -vMax, vMax);

		float rotation = rotate(deltaSec);

		acceleration.X = a * UKismetMathLibrary::DegCos(rotation);
		acceleration.Y = a * UKismetMathLibrary::DegSin(rotation);

		drawLine(2 * acceleration / deltaSec, accelerationColor);

		velocity = FVector(v * UKismetMathLibrary::DegCos(rotation) * deltaSec, v * UKismetMathLibrary::DegSin(rotation) * deltaSec, 0);

		float rot = agent->GetActorRotation().Yaw;

		setRotation();

		GEngine->AddOnScreenDebugMessage(-1, 50.f, FColor::Red, FString::Printf(TEXT("%f"), UKismetMathLibrary::Abs(rot - agent->GetActorRotation().Yaw) / deltaSec));

		agent->SetActorLocation(agent->GetActorLocation() + velocity);

		DrawDebugLine(GWorld->GetWorld(), agent->GetActorLocation(), agent->GetActorLocation() + collisionSize, FColor::Green, false, 0.1, 0, 1);
		*/
	}
}
Exemplo n.º 18
0
void QStyleAnimation::updateCurrentTime(int)
{
    if (target() && isUpdateNeeded())
        updateTarget();
}
Exemplo n.º 19
0
void AiEntity::update() {
  Physics& physics = *mGameModel->physics;
  // this has to be non-NULL since AiManager::update() checks before calling this.
  // all the same...
  mPhysicsEntity = physics.getEntityByHandle(mPhysicsHandle);
  if (mPhysicsEntity == NULL) {
    // this is bad!
    printf("AiEntity::update(): error: NULL physics entity\n");
    mActive = false;
    return;
  }

  mWorldPosition = physics.getCenter(mPhysicsHandle);

  // won't know this until we read the mail
  mWasAttacked = false;

  readMail();

  // handle death
  // FIXME: the other half of this exists in AiManager...
  // ever get the urge to merge?
  if (mCurrentHealth <= 0.0) {
    // turn inventory items into phys entities
    for (int i = 0; i < AI_INVENTORY_SIZE; i++) {
      if (mInventory[i] > 0) {
        item_t item = mGameModel->itemManager->getItem(mInventory[i]);

        if (item.type == ITEMTYPE_GUN_ONE_HANDED && r_numi(0, 10) < 3) {
          mGameModel->itemManager->destroyItem(mInventory[i]);
        }
        else {
          v3d_t itemForce = v3d_random(20.0);
          itemForce.y = 10.0;
          PhysicsEntity* itemPhysicsEntity = physics.createEntity(OBJTYPE_ITEM, mWorldPosition, itemForce, true);
          if (itemPhysicsEntity != NULL) {
            physics.setItemHandleAndType(itemPhysicsEntity->handle, mInventory[i], mGameModel->itemManager->getItemType(mInventory[i]));
          }

        }

        mInventory[i] = 0;
      }
    }

    return;
  }

  double time = mGameModel->physics->getLastUpdateTime();

  // is it time to think yet?
  if (mNextUpdateTime < time) {
    updateTarget();

//    updateState(time, worldMap, physics, aiEntities, itemManager);

    mNextUpdateTime = time + 0.3;
  }

  if (mTargetPhysicsHandle > 0) {
    mTargetPhysicsEntity = physics.getEntityByHandle(mTargetPhysicsHandle);
  }

  bool couldHaveFiredGun = false;
  bool didFireGun = false;

  if (mTargetPhysicsEntity == NULL) {
    mTargetPhysicsHandle = 0;
  }
  else {
    // now shoot'm if you got'm!
    v3d_t targetPosition = mTargetPhysicsEntity->boundingBox.getCenterPosition();

    bool hasLineOfSight = mGameModel->location->getWorldMap()->lineOfSight(mWorldPosition, targetPosition);
    if (mTargetPhysicsEntity->type != OBJTYPE_TIGER_BAIT && hasLineOfSight) {
      if (mInventory[0] > 0 && mGameModel->itemManager->getItem(mInventory[0]).type == ITEMTYPE_GUN_ONE_HANDED) {
        couldHaveFiredGun = true;
      }

      didFireGun = useWeapon();
    }
  }

  // now for movement
  switch (mType) {
    case AITYPE_BALLOON:
      updateBalloon();
      break;

    case AITYPE_SHOOTER:
      if (!couldHaveFiredGun || (couldHaveFiredGun && !didFireGun && mNextShotTime <= time)) {
        updateHopper();
      }
      break;

    case AITYPE_HOPPER:
      updateHopper();
      break;

    case AITYPE_HUMAN:
      if (!couldHaveFiredGun || (couldHaveFiredGun && !didFireGun && mNextShotTime <= time)) {
        updateHopper();
      }
      break;

    case AITYPE_DUMMY:
      updateDummy();
      break;

    default:
      break;
  }
}