Exemplo n.º 1
0
void CAESinkPi::Drain()
{
  int delay = (int)(GetDelay() * 1000.0);
  if (delay)
    Sleep(delay);
  CLog::Log(LOGDEBUG, "%s:%s delay:%dms now:%dms", CLASSNAME, __func__, delay, (int)(GetDelay() * 1000.0));
}
Exemplo n.º 2
0
bool Player::DelayDraw(coord_def offset_, float size_)
{
	if(GetDelay() && GetMaxDelay())
	{
		float size__ = (float)GetDelay()*24.0f/GetMaxDelay();
		tex_gun.Draw((offset_.x+size__/2-12)*size_,(offset_.y)*size_,size_*size__,size_,0.0f);
	}
	return true;
}
Exemplo n.º 3
0
unsigned int CAESinkPi::AddPackets(uint8_t **data, unsigned int frames, unsigned int offset)
{
  if (!m_Initialized || !m_omx_output || !frames)
  {
    Sleep(10);
    return frames;
  }
  OMX_ERRORTYPE omx_err   = OMX_ErrorNone;
  OMX_BUFFERHEADERTYPE *omx_buffer = NULL;

  unsigned int channels    = m_format.m_channelLayout.Count();
  unsigned int sample_size = CAEUtil::DataFormatToBits(m_format.m_dataFormat) >> 3;
  const int planes = AE_IS_PLANAR(m_format.m_dataFormat) ? channels : 1;
  const int chans  = AE_IS_PLANAR(m_format.m_dataFormat) ? 1 : channels;
  const int pitch  = chans * sample_size;

  AEDelayStatus status;
  GetDelay(status);
  double delay = status.GetDelay();
  if (delay <= 0.0 && m_submitted)
    CLog::Log(LOGNOTICE, "%s:%s Underrun (delay:%.2f frames:%d)", CLASSNAME, __func__, delay, frames);

  omx_buffer = m_omx_output->GetInputBuffer(1000);
  if (omx_buffer == NULL)
  {
    CLog::Log(LOGERROR, "CAESinkPi::AddPackets timeout");
    return 0;
  }

  omx_buffer->nFilledLen = frames * m_format.m_frameSize;
  // must be true
  assert(omx_buffer->nFilledLen <= omx_buffer->nAllocLen);
  omx_buffer->nTimeStamp = ToOMXTime(0);
  omx_buffer->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;

  if (omx_buffer->nFilledLen)
  {
    int planesize = omx_buffer->nFilledLen / planes;
    for (int i=0; i < planes; i++)
      memcpy((uint8_t *)omx_buffer->pBuffer + i * planesize, data[i] + offset * pitch, planesize);
  }
  omx_err = m_omx_output->EmptyThisBuffer(omx_buffer);
  if (omx_err != OMX_ErrorNone)
  {
    CLog::Log(LOGERROR, "%s:%s frames=%d err=%x", CLASSNAME, __func__, frames, omx_err);
    m_omx_output->DecoderEmptyBufferDone(m_omx_output->GetComponent(), omx_buffer);
  }
  m_submitted++;
  GetDelay(status);
  delay = status.GetDelay();
  if (delay > m_latency)
    Sleep((int)(1000.0f * (delay - m_latency)));
  return frames;
}
Exemplo n.º 4
0
unsigned int CDVDAudio::AddPackets(const DVDAudioFrame &audioframe)
{
  m_bAbort = false;

  CSingleLock lock (m_critSection);

  if(!m_pAudioStream)
    return 0;

  CAESyncInfo info = m_pAudioStream->GetSyncInfo();
  if (info.state == CAESyncInfo::SYNC_INSYNC)
  {
    unsigned int newTime = info.errortime;
    if (newTime != m_syncErrorTime)
    {
      m_syncErrorTime = info.errortime;
      m_syncError = info.error / 1000 * DVD_TIME_BASE;
      m_resampleRatio = info.rr;
    }
  }
  else
  {
    m_syncErrorTime = 0;
    m_syncError = 0.0;
  }

  //Calculate a timeout when this definitely should be done
  double timeout;
  timeout  = DVD_SEC_TO_TIME(m_pAudioStream->GetDelay()) + audioframe.duration;
  timeout += DVD_SEC_TO_TIME(1.0);
  timeout += CDVDClock::GetAbsoluteClock();

  unsigned int total = audioframe.nb_frames;
  unsigned int frames = audioframe.nb_frames;
  unsigned int offset = 0;
  do
  {
    double pts = (offset == 0) ? audioframe.pts / DVD_TIME_BASE * 1000 : 0.0;
    unsigned int copied = m_pAudioStream->AddData(audioframe.data, offset, frames, pts);
    offset += copied;
    frames -= copied;
    if (frames <= 0)
      break;

    if (copied == 0 && timeout < CDVDClock::GetAbsoluteClock())
    {
      CLog::Log(LOGERROR, "CDVDAudio::AddPacketsRenderer - timeout adding data to renderer");
      break;
    }

    lock.Leave();
    Sleep(1);
    lock.Enter();
  } while (!m_bAbort);

  m_playingPts = audioframe.pts + audioframe.duration - GetDelay();
  m_timeOfPts = CDVDClock::GetAbsoluteClock();

  return total - frames;
}
Exemplo n.º 5
0
void EnemyMelee::Pat(Player* player)
{
	if(AccumulatedTime > GetDelay())
	{
		AccumulatedTime = 0.0;

		if(CalculateDistance_x() <= 192 && CalculateDistance_y() <= 192 && player->getIsHiding() != true)
		{
			Move();
		}
		else
		{
			if(Flush != true && colData[abs(static_cast<int>(GetPos_y())/32) + 25][static_cast<int>(GetPos_x())/32 + 1] < 100)
			{
				MoveRight();
			}

			if(Flush == true && colData[abs(static_cast<int>(GetPos_y())/32) + 25][static_cast<int>(GetPos_x())/32 - 1] < 100)
			{
				MoveLeft();
			}
		}


		if(colData[abs(static_cast<int>(GetPos_y())/32) + 25][static_cast<int>(GetPos_x())/32 + 1] >= 100)
		{
			Flush = true;
		}

		if(colData[abs(static_cast<int>(GetPos_y())/32) + 25][static_cast<int>(GetPos_x())/32 - 1] >= 100)
		{
			Flush = false;
		}
	}
}
Exemplo n.º 6
0
void ItemTemplate::GetDamage(uint32 itemLevel, float& minDamage, float& maxDamage) const
{
    minDamage = maxDamage = 0.0f;
    uint32 quality = ItemQualities(GetQuality()) != ITEM_QUALITY_HEIRLOOM ? ItemQualities(GetQuality()) : ITEM_QUALITY_RARE;
    if (GetClass() != ITEM_CLASS_WEAPON || quality > ITEM_QUALITY_ARTIFACT)
        return;

    // get the right store here
    if (GetInventoryType() > INVTYPE_RANGEDRIGHT)
        return;

    float dps = 0.0f;
    switch (GetInventoryType())
    {
        case INVTYPE_AMMO:
            dps = sItemDamageAmmoStore.AssertEntry(itemLevel)->DPS[quality];
            break;
        case INVTYPE_2HWEAPON:
            if (GetFlags2() & ITEM_FLAG2_CASTER_WEAPON)
                dps = sItemDamageTwoHandCasterStore.AssertEntry(itemLevel)->DPS[quality];
            else
                dps = sItemDamageTwoHandStore.AssertEntry(itemLevel)->DPS[quality];
            break;
        case INVTYPE_RANGED:
        case INVTYPE_THROWN:
        case INVTYPE_RANGEDRIGHT:
            switch (GetSubClass())
            {
                case ITEM_SUBCLASS_WEAPON_WAND:
                    dps = sItemDamageOneHandCasterStore.AssertEntry(itemLevel)->DPS[quality];
                    break;
                case ITEM_SUBCLASS_WEAPON_BOW:
                case ITEM_SUBCLASS_WEAPON_GUN:
                case ITEM_SUBCLASS_WEAPON_CROSSBOW:
                    if (GetFlags2() & ITEM_FLAG2_CASTER_WEAPON)
                        dps = sItemDamageTwoHandCasterStore.AssertEntry(itemLevel)->DPS[quality];
                    else
                        dps = sItemDamageTwoHandStore.AssertEntry(itemLevel)->DPS[quality];
                    break;
                default:
                    return;
            }
            break;
        case INVTYPE_WEAPON:
        case INVTYPE_WEAPONMAINHAND:
        case INVTYPE_WEAPONOFFHAND:
            if (GetFlags2() & ITEM_FLAG2_CASTER_WEAPON)
                dps = sItemDamageOneHandCasterStore.AssertEntry(itemLevel)->DPS[quality];
            else
                dps = sItemDamageOneHandStore.AssertEntry(itemLevel)->DPS[quality];
            break;
        default:
            return;
    }

    float avgDamage = dps * GetDelay() * 0.001f;
    minDamage = (GetStatScalingFactor() * -0.5f + 1.0f) * avgDamage;
    maxDamage = floor(float(avgDamage * (GetStatScalingFactor() * 0.5f + 1.0f) + 0.5f));
}
Exemplo n.º 7
0
/**
 * Returns a new DateTime representing the arrival time by adding the duration
 * and delay to the departure DateTime. Calls polymorphic function GetDelay for
 * appropriate derived class.
 */
DateTime FlightNode::GetArrivalTime() {  
  DateTime arrival = DateTime(departure_.minutes(), departure_.hours(),
                              departure_.day(), departure_.month(),
                              departure_.year());
  int min = duration_ + GetDelay(); 
  arrival.AddMinutes(min);
  
  return arrival;
}
Exemplo n.º 8
0
//
// Called when the contents of the delay editbox change
//
void CAccessDialog::OnChangeDelay()
{
	// Update the delay time if it's not blank.
	if (m_EDelayTime.LineLength()) {
		SetDelay(GetDlgItemInt(EDelayTime));
	} else if (GetFocus() != &m_EDelayTime) {
		// Entry box is empty and it no longer has focus.
		// Revert to the value in the access spec.
		SetDelay(GetDelay());
	}
}
Exemplo n.º 9
0
//
// Calls each of the Get functions.
//
void CAccessDialog::GetAll(Access_Spec * spec)
{
	spec->size = GetSize();
	spec->of_size = GetAccess();
	spec->reads = GetReads();
	spec->random = GetRandom();
	spec->delay = GetDelay();
	spec->burst = GetBurst();
	spec->align = GetAlign();
	spec->reply = GetReply();
}
Exemplo n.º 10
0
void cPlayer::NextFrame(int max)
{
	SetDelay(GetDelay()+1);
	if(GetState() == STATE_ATTACKUP || GetState() == STATE_ATTACKRIGHT || GetState() == STATE_ATTACKDOWN || GetState() == STATE_ATTACKLEFT || GetState() == STATE_SUPERATTACK)
	{
		if(GetDelay() == frame_attack_delay)
		{
			SetFrame(GetFrame()+1);
			SetFrame(GetFrame()%max);
			SetDelay(0);
		}
	}
	else
	{
		if(GetDelay() == frame_walk_delay)
		{
			SetFrame(GetFrame()+1);
			SetFrame(GetFrame()%max);
			SetDelay(0);
		}
	}
}
Exemplo n.º 11
0
unsigned int CAESinkPi::AddPackets(uint8_t *data, unsigned int frames, bool hasAudio, bool blocking)
{
  unsigned int sent = 0;

  if (!m_Initialized)
    return frames;

  OMX_ERRORTYPE omx_err   = OMX_ErrorNone;
  OMX_BUFFERHEADERTYPE *omx_buffer = NULL;
  while (sent < frames)
  {
    int timeout = blocking ? 1000 : 0;

    // delay compared to maximum we'd like (to keep lag low)
    double delay = GetDelay();
    bool too_laggy = delay - AUDIO_PLAYBUFFER > 0.0;
    omx_buffer = too_laggy ? NULL : m_omx_render.GetInputBuffer(timeout);

    if (omx_buffer == NULL)
    {
      if (too_laggy)
      {
        Sleep((int)((delay - AUDIO_PLAYBUFFER) * 1000.0));
        continue;
      }
      if (blocking)
        CLog::Log(LOGERROR, "COMXAudio::Decode timeout");
      break;
    }

    omx_buffer->nFilledLen = std::min(omx_buffer->nAllocLen, (frames - sent) * m_format.m_frameSize);
    omx_buffer->nTimeStamp = ToOMXTime(0);
    omx_buffer->nFlags = 0;
    memcpy(omx_buffer->pBuffer, (uint8_t *)data + sent * m_format.m_frameSize, omx_buffer->nFilledLen);
    sent += omx_buffer->nFilledLen / m_format.m_frameSize;

    if (sent == frames)
      omx_buffer->nFlags |= OMX_BUFFERFLAG_ENDOFFRAME;

    if (delay <= 0.0 && m_submitted)
      CLog::Log(LOGERROR, "%s:%s Underrun (delay:%.2f frames:%d)", CLASSNAME, __func__, delay, frames);

    omx_err = m_omx_render.EmptyThisBuffer(omx_buffer);
    if (omx_err != OMX_ErrorNone)
      CLog::Log(LOGERROR, "%s:%s frames=%d err=%x", CLASSNAME, __func__, frames, omx_err);
    m_submitted += omx_buffer->nFilledLen;
  }

  return sent;
}
Exemplo n.º 12
0
void OMXPlayerAudio::HandlePlayspeed(bool bDropPacket)
{
  if(!bDropPacket && m_speed == DVD_PLAYSPEED_NORMAL && m_av_clock->HasVideo())
  {
    if(GetDelay() < 0.1f && !m_av_clock->OMXAudioBuffer())
    {
      clock_gettime(CLOCK_REALTIME, &m_starttime);
      m_av_clock->OMXAudioBufferStart();
    }
    else if(GetDelay() > (AUDIO_BUFFER_SECONDS * 0.75f) && m_av_clock->OMXAudioBuffer())
    {
      m_av_clock->OMXAudioBufferStop();
    }
    else if(m_av_clock->OMXAudioBuffer())
    {
      clock_gettime(CLOCK_REALTIME, &m_endtime);
      if((m_endtime.tv_sec - m_starttime.tv_sec) > 1)
      {
        m_av_clock->OMXAudioBufferStop();
      }
    }
  }
}
//------------------------------------------------------------------------
void CMelee::NetAttack()
{
	MeleeDebugLog ("CMelee<%p> NetAttack", this);

	const ItemString &meleeAction = SelectMeleeAction();

	m_pWeapon->OnMelee(m_pWeapon->GetOwnerId());

	CActor* pOwner = m_pWeapon->GetOwnerActor();

	if (!DoSlideMeleeAttack(pOwner))
	{
		if(!gEnv->bMultiplayer || !g_pGameCVars->pl_melee.mp_melee_system || !StartMultiAnimMeleeAttack(pOwner))
		{
			FragmentID fragmentId = m_pWeapon->GetFragmentID(meleeAction.c_str());
			m_pWeapon->PlayAction(fragmentId, 0, false, CItem::eIPAF_Default);
		}
	}
	else
	{
		CRY_ASSERT(pOwner && (pOwner->GetActorClass() == CPlayer::GetActorClassType()));

		if( pOwner->IsPlayer() )
		{
			static_cast<CPlayer*> (pOwner)->StateMachineHandleEventMovement( SStateEventSlideKick(this) );
		}
	}

	m_attacking = true;
	m_slideKick = false;
	m_netAttacking = true;
	m_delayTimer = GetDelay();

	m_pWeapon->SetBusy(true);
	m_pWeapon->RequireUpdate(eIUS_FireMode);

	CPlayer *pOwnerPlayer = m_pWeapon->GetOwnerPlayer();
	if (pOwnerPlayer)
	{
		if (pOwnerPlayer->IsThirdPerson())
		{
			CAudioSignalPlayer::JustPlay(m_pMeleeParams->meleeparams.m_3PSignalId, pOwnerPlayer->GetEntityId());
		}
		else
		{
			CAudioSignalPlayer::JustPlay(m_pMeleeParams->meleeparams.m_FPSignalId, pOwnerPlayer->GetEntityId());
		}
	}
}
Exemplo n.º 14
0
bool Player::Shot(Game_Manager* gm_, coord_def c, float focus_, int item_num)
{
	if(GetStop())
		return false;
	Item* item_ = NULL;
	switch(item_num)
	{
	case 0:
		item_ = current_weapon;
		break;
	case 1:
		item_ = main_weapon;
		break;
	case 2:
		item_ = sub_weapon[0];
		break;
	case 3:
		item_ = sub_weapon[1];
		break;
	case 4:
		item_ = melee_weapon;
		break;
	}
	if(!GetDelay() && item_)
	{
		focus_ += GetFocusSum();
		InitNoneMoveCount();
		if(SetDelay(item_->Shot(gm_, this, GetTeam(), GetPos(), c, focus_)) == -1)
		{
			SetDelay(0);
			if(item_ == main_weapon)
			{
				Reload(gm_);
			}
			return false;
		}
		else
		{
			if(item_ == main_weapon)
			{
				if(GetFocus() < main_weapon->GetFocusMaxReact())
					UpDownFocus(main_weapon->GetFocusReact());
			}
			return true;
		}
	}
	return false;
}
Exemplo n.º 15
0
//***********************************************************************************************
void CWin32DirectSound::WaitCompletion()
{
  CSingleLock lock (m_critSection);
  DWORD status;
  unsigned int timeout;
  unsigned char* silence;

  if (!m_pBuffer)
    return ;

  if(FAILED(m_pBuffer->GetStatus(&status)) || (status & DSBSTATUS_PLAYING) == 0)
    return; // We weren't playing anyway

  // The drain should complete in the time occupied by the cache
  timeout  = (unsigned int)(1000 * GetDelay());
  unsigned int startTime = XbmcThreads::SystemClockMillis();
  silence  = (unsigned char*)calloc(1,m_dwChunkSize); // Initialize 'silence' to zero...

  while(AddPackets(silence, m_dwChunkSize) == 0)
  {
    if(FAILED(m_pBuffer->GetStatus(&status)) || (status & DSBSTATUS_PLAYING) == 0)
      break;

    if((XbmcThreads::SystemClockMillis() - startTime) > timeout)
    {
      CLog::Log(LOGWARNING, __FUNCTION__ ": timeout adding silence to buffer");
      break;
    }
  }
  free(silence);

  while(m_CacheLen)
  {
    if(FAILED(m_pBuffer->GetStatus(&status)) || (status & DSBSTATUS_PLAYING) == 0)
      break;

    if((XbmcThreads::SystemClockMillis() - startTime) > timeout)
    {
      CLog::Log(LOGDEBUG, "CWin32DirectSound::WaitCompletion - timeout waiting for silence");
      break;
    }
    else
      Sleep(1);
    GetSpace();
  }

  m_pBuffer->Stop();
}
Exemplo n.º 16
0
		bool Weapon::FrameNext(float dt){
			SPADES_MARK_FUNCTION();
			
			bool fired = false;
			bool dryFire = false;
			if(shooting && (!reloading || IsReloadSlow())){
				// abort slow reload
				reloading = false;
				if(time >= nextShotTime && ammo > 0) {
					fired = true;
					ammo--;
					if(world->GetListener())
						world->GetListener()->PlayerFiredWeapon(owner);
					nextShotTime = time + GetDelay();
				}else if(time >= nextShotTime){
					dryFire = true;
				}
			}
			if(reloading){
				if(time >= reloadEndTime) {
					// reload done
					reloading = false;
					if(IsReloadSlow()){
						ammo++;
						stock--;
						Reload();
					}else{
						int newStock;
						newStock = std::max(0, stock - GetClipSize() + ammo);
						ammo += stock - newStock;
						stock = newStock;
					}
					
					
					if(world->GetListener())
						world->GetListener()->PlayerReloadedWeapon(owner);
				}
			}
			time += dt;
			
			if(dryFire && !lastDryFire){
				if(world->GetListener())
					world->GetListener()->PlayerDryFiredWeapon(owner);
			}
			lastDryFire = dryFire;
			return fired;
		}
Exemplo n.º 17
0
bool Monster::Shot(Game_Manager* gm_, coord_def c, float focus_, int item_num)
{
	if(GetShotStop())
		return false;
	if(GetStop())
		return false;
	if(!GetDelay() && weapon)
	{
		focus_ += weapon->GetFocusBase()+GetFocusSum();
		while(SetDelay(weapon->Shot(gm_, this, GetTeam(), GetPos(), c, focus_)*panalty) < 0)
		{
			SetDelay(0.0f);
			weapon->Reload(); //몬스터는 무한 리로드한다.
		}
		if(GetFocus() < weapon->GetFocusMaxReact())
			UpDownFocus(weapon->GetFocusReact());
		return true;
	}
	return false;
}
Exemplo n.º 18
0
bool Named_fly_boss::Shot(Game_Manager* gm_, coord_def c, float focus_, int item_num)
{
	if(GetShotStop())
		return false;
	if(GetStop())
		return false;
	if(!GetDelay())
	{
		float length_ = distan_coord(GetPos(), c);

		if(length_ >120)
			return false;
		float angle_ = GetAngleToTarget(GetPos(), c);

		Unit* target_ = NULL;
		if(gm_)
		{
			for(list<Unit*>::iterator it = gm_->unit_list.begin();it != gm_->unit_list.end();it++)
			{
				if((*it)->isLive() && !(*it)->isNonTarget()  && (*it)->GetTeam() != GetTeam())
				{
					if((*it)->collution(c, 30.0f))
					{
						target_ = (*it);
						break;
					}
				}
			}
		}
		Unit* temp = new Mon_bug_child_fly(monster__bug_child_fly,this, target_, GetX(), GetY(), GetTeam(),200);
		temp->SetAi(MS_NORMAL, NULL, 2);
		temp->SetFlyAngle(GetAngle()+rand_float(-1.0f,1.0f,"Named_fly_boss::Shot delta angle"));
		gm_->unit_list.push_back(temp);			
		SetDelay(50.0f);
		return true;
	}
	return false;

}
Exemplo n.º 19
0
/*--------------------------------------------------------------------------------*/
double DistanceModel::GetDelay(const Position& pos, double delayscale) const
{
  return GetDelay(pos.Polar().pos.d, delayscale);
}
Exemplo n.º 20
0
void ItemTemplate::GetDamage(uint32 itemLevel, float& minDamage, float& maxDamage) const
{
    minDamage = maxDamage = 0.0f;
    uint32 quality = ItemQualities(GetQuality()) != ITEM_QUALITY_HEIRLOOM ? ItemQualities(GetQuality()) : ITEM_QUALITY_RARE;
    if (GetClass() != ITEM_CLASS_WEAPON || quality > ITEM_QUALITY_ARTIFACT)
        return;

    DBCStorage<ItemDamageEntry>* store = NULL;
    // get the right store here
    if (GetInventoryType() > INVTYPE_RANGEDRIGHT)
        return;

    switch (GetInventoryType())
    {
        case INVTYPE_AMMO:
            store = &sItemDamageAmmoStore;
            break;
        case INVTYPE_2HWEAPON:
            if (GetFlags2() & ITEM_FLAG2_CASTER_WEAPON)
                store = &sItemDamageTwoHandCasterStore;
            else
                store = &sItemDamageTwoHandStore;
            break;
        case INVTYPE_RANGED:
        case INVTYPE_THROWN:
        case INVTYPE_RANGEDRIGHT:
            switch (GetSubClass())
            {
                case ITEM_SUBCLASS_WEAPON_WAND:
                    store = &sItemDamageWandStore;
                    break;
                case ITEM_SUBCLASS_WEAPON_THROWN:
                    store = &sItemDamageThrownStore;
                    break;
                case ITEM_SUBCLASS_WEAPON_BOW:
                case ITEM_SUBCLASS_WEAPON_GUN:
                case ITEM_SUBCLASS_WEAPON_CROSSBOW:
                    store = &sItemDamageRangedStore;
                    break;
                default:
                    return;
            }
            break;
        case INVTYPE_WEAPON:
        case INVTYPE_WEAPONMAINHAND:
        case INVTYPE_WEAPONOFFHAND:
            if (GetFlags2() & ITEM_FLAG2_CASTER_WEAPON)
                store = &sItemDamageOneHandCasterStore;
            else
                store = &sItemDamageOneHandStore;
            break;
        default:
            return;
    }

    ASSERT(store);

    ItemDamageEntry const* damageInfo = store->LookupEntry(itemLevel);
    if (!damageInfo)
        return;

    float dps = damageInfo->DPS[quality];
    float avgDamage = dps * GetDelay() * 0.001f;
    minDamage = (GetStatScalingFactor() * -0.5f + 1.0f) * avgDamage;
    maxDamage = floor(float(avgDamage * (GetStatScalingFactor() * 0.5f + 1.0f) + 0.5f));
}
void CMelee::StartAttack()
{
	bool canAttack = CanAttack();

	MeleeDebugLog ("CMelee<%p> StartAttack canAttack=%s", this, canAttack ? "true" : "false");

	if (!canAttack)
		return;

	CActor* pOwner = m_pWeapon->GetOwnerActor();
	CPlayer *ownerPlayer = m_pWeapon->GetOwnerPlayer();

	m_attacking = true;
	m_slideKick = false;
	m_attacked = false;
	m_pWeapon->RequireUpdate(eIUS_FireMode);
	m_pWeapon->ExitZoom();

	bool isClient = pOwner ? pOwner->IsClient() : false;
	bool doingMultiMeleeAttack = true;

	if (!DoSlideMeleeAttack(pOwner))
	{
		const float use_melee_weapon_delay = m_pMeleeParams->meleeparams.use_melee_weapon_delay;
		if( use_melee_weapon_delay >= 0.0f )
		{
			if( !ownerPlayer || ownerPlayer->IsSliding() || ownerPlayer->IsExitingSlide() )
			{
				m_attacking = false;
				return;
			}

			if( use_melee_weapon_delay == 0.0f )
			{
				// instant switch: don't use the weapon's melee, send the event to the WeaponMelee weapon instead!
				if( SwitchToMeleeWeaponAndAttack() )
				{
					m_useMeleeWeaponDelay = -1.0f;
					return;
				}
			}
		}

		if( IsMeleeWeapon() )
		{
			doingMultiMeleeAttack = false;

			GenerateAndQueueMeleeAction();
		}
		else if(!gEnv->bMultiplayer || !g_pGameCVars->pl_melee.mp_melee_system || !ownerPlayer || !StartMultiAnimMeleeAttack(ownerPlayer))
		{
			const ItemString &meleeAction = SelectMeleeAction();

			FragmentID fragmentId = m_pWeapon->GetFragmentID(meleeAction.c_str());
			m_pWeapon->PlayAction(fragmentId, 0, false, CItem::eIPAF_Default);

			doingMultiMeleeAttack = false;
		}

		m_delayTimer = GetDelay();
		m_attackTime = 0.f;

		if (ownerPlayer)
		{
			ownerPlayer->StateMachineHandleEventMovement( PLAYER_EVENT_FORCEEXITSLIDE );
		}
	}
	else
	{
		CRY_ASSERT(pOwner && (pOwner->GetActorClass() == CPlayer::GetActorClassType()));

		doingMultiMeleeAttack = false;
		
		m_hitTypeID = CGameRules::EHitType::Melee;

		// Dispatch the event and the delay timer is magically set!
		ownerPlayer->StateMachineHandleEventMovement( SStateEventSlideKick(this) );

		m_slideKick = true;
	}

	m_pWeapon->SetBusy(true);

	if(!doingMultiMeleeAttack)
	{
		// Set up a timer to disable the melee attack at the end of the first-person animation...
		uint32 durationInMilliseconds = static_cast<uint32>(GetDuration() * 1000.f);
		MeleeDebugLog ("CMelee<%p> Setting a timer to trigger StopAttackingAction (duration=%u)", this, durationInMilliseconds);

		// How much longer we need the animation to be than the damage delay, in seconds...
		const float k_requireAdditionalTime = 0.1f;

		if (durationInMilliseconds < (m_delayTimer + k_requireAdditionalTime) * 1000.0f)
		{
			if (!gEnv->IsDedicated())
			{
				CRY_ASSERT_MESSAGE(false, string().Format("CMelee<%p> Warning! Melee attack timeout (%f seconds) needs to be substantially longer than the damage delay (%f seconds)! Increasing...", this, durationInMilliseconds / 1000.f, m_delayTimer));
			}
			durationInMilliseconds = (uint32) ((m_delayTimer + k_requireAdditionalTime) * 1000.0f + 0.5f);	// Add 0.5f to round up when turning into a uint32
		}
		m_pWeapon->GetScheduler()->TimerAction(durationInMilliseconds, CSchedulerAction<StopAttackingAction>::Create(this), true);
	}
	
	m_pWeapon->OnMelee(m_pWeapon->GetOwnerId());
	m_pWeapon->RequestStartMeleeAttack((m_pWeapon->GetMelee() == this),	false);

	if (isClient)
	{
		s_fNextAttack				= GetDuration() + gEnv->pTimer->GetFrameStartTime().GetSeconds();
		if(s_meleeSnapTargetId = GetNearestTarget())
		{
			IActor* pTargetActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(s_meleeSnapTargetId);
			s_bMeleeSnapTargetCrouched = pTargetActor && static_cast<CPlayer*>(pTargetActor)->GetStance() == STANCE_CROUCH;
		}
		CHANGED_NETWORK_STATE(pOwner, CPlayer::ASPECT_SNAP_TARGET);

		if (ownerPlayer)
		{
			if (ownerPlayer->IsThirdPerson())
			{
				CAudioSignalPlayer::JustPlay(m_pMeleeParams->meleeparams.m_3PSignalId, ownerPlayer->GetEntityId());
			}
			else
			{
				CAudioSignalPlayer::JustPlay(m_pMeleeParams->meleeparams.m_FPSignalId, ownerPlayer->GetEntityId());
			}
		}

		CCCPOINT(Melee_LocalActorMelee);
	}
	else
	{
		CCCPOINT(Melee_NonLocalActorMelee);
	}
}
Exemplo n.º 22
0
		bool Weapon::FrameNext(float dt) {
			SPADES_MARK_FUNCTION();

			bool ownerIsLocalPlayer = owner->IsLocalPlayer();

			bool fired = false;
			bool dryFire = false;
			if (shooting && (!reloading || IsReloadSlow())) {
				// abort slow reload
				reloading = false;

				if (!shootingPreviously) {
					nextShotTime = std::max(nextShotTime, time);
				}

				// Automatic operation of weapon.
				if (time >= nextShotTime && (ammo > 0 || !ownerIsLocalPlayer)) {
					fired = true;

					// Consume an ammo.
					// Ammo count tracking is disabled for remote players because the server doesn't
					// send enough information for us to do that.
					if (ownerIsLocalPlayer) {
						ammo--;
					}

					if (world->GetListener()) {
						world->GetListener()->PlayerFiredWeapon(owner);
					}
					nextShotTime += GetDelay();
				} else if (time >= nextShotTime) {
					dryFire = true;
				}
				shootingPreviously = true;
			} else {
				shootingPreviously = false;
			}
			if (reloading) {
				if (time >= reloadEndTime) {
					// reload done
					reloading = false;
					if (IsReloadSlow()) {
						// for local player, server sends
						// new ammo/stock value
						if (ammo < GetClipSize() && stock > 0 && !ownerIsLocalPlayer) {
							ammo++;
							stock--;
						}
						slowReloadLeftCount--;
						if (slowReloadLeftCount > 0)
							Reload(false);
						else if (world->GetListener())
							world->GetListener()->PlayerReloadedWeapon(owner);
					} else {
						// for local player, server sends
						// new ammo/stock value
						if (!ownerIsLocalPlayer) {
							int newStock;
							newStock = std::max(0, stock - GetClipSize() + ammo);
							ammo += stock - newStock;
							stock = newStock;
						}
						if (world->GetListener())
							world->GetListener()->PlayerReloadedWeapon(owner);
					}
				}
			}
			time += dt;

			if (dryFire && !lastDryFire) {
				if (world->GetListener())
					world->GetListener()->PlayerDryFiredWeapon(owner);
			}
			lastDryFire = dryFire;
			return fired;
		}
Exemplo n.º 23
0
double CAESinkPi::GetCacheTime()
{
  return GetDelay();
}
Exemplo n.º 24
0
bool DelayAtomicSequence::Prepare (const PrepareMode mode) {

    bool b=true;
    double delay = 0.;

    ATTRIBUTE("Delay"    , m_await_time);
    ATTRIBUTE("ADCs"     , m_adc       );
    ATTRIBUTE("PhaseLock", m_phase_lock);
    ATTRIBUTE("StartSeq" , m_start     );
    ATTRIBUTE("StopSeq"  , m_stop      );
    ATTRIBUTE("DelayType", m_delay_type);

    //insert pulse and module-attributes for observation only once
    if (mode == PREP_INIT) {

		//insert empty pulse
        if (GetNumberOfChildren()==0)
			b =InsertChild("EmptyPulse");

		//add attributes to link with durations of other modules
		for (int i=0;i<20;i++) {
			char modules[10];
			sprintf( modules, "Module%02d", i ) ;
			HIDDEN_ATTRIBUTE(modules, m_durations[i] );
		}
    }

    //set delaytype for a quick later check in PREP_UPDATE
    if (mode != PREP_UPDATE) {
		if (m_delay_type == "B2E") m_dt = DELAY_B2E;
		if (m_delay_type == "C2E") m_dt = DELAY_C2E;
		if (m_delay_type == "B2C") m_dt = DELAY_B2C;
		if (m_delay_type == "C2C") m_dt = DELAY_C2C;
    }

    b     = ( SearchStartStopSeq() && b);
    delay = GetDelay(mode);
    //std::cout << b << "+" << delay << "-" << std::endl;
    b     = (delay >= 0.0 && b);

    if (GetNumberOfChildren()>0) {
		((Pulse*) GetChild(0))->SetNADC(m_adc);  //pass my ADCs to the EmptyPulse
		((Pulse*) GetChild(0))->SetPhaseLock(m_phase_lock);
		((Pulse*) GetChild(0))->SetDuration(delay);
		if (mode != PREP_UPDATE)
			((Pulse*) GetChild(0))->SetName("eP_"+GetName());
    }

    b = ( AtomicSequence::Prepare(mode) && b);

    // Hide XML attributes which were set by AtomicSequence::Prepare()
    // delay atoms don't need a rot-matrix.
    if (mode != PREP_UPDATE) {
		HideAttribute("RotAngle",false);
		HideAttribute("Inclination",false);
		HideAttribute("Azimut",false);
    }

    if (!b && mode == PREP_VERBOSE)
		cout << "Preparation of DelayAtomicSequence '" << GetName() << "' not succesful. Delay = " << delay << " ms" << endl;

    return b;

}
Exemplo n.º 25
0
void EnemyMelee::Move()
{

	std::cout << "RUNNING"<< std::endl;
	if(AccumulatedTime > GetDelay())
	{
		AccumulatedTime = 0.0;

		Right = false;

		Left = false;

		Up = false;

		Down = false;


		if(GetDestination_x() - GetPos_x() > 0 && colData[abs(GetPos_y()/32) + 25][GetPos_x()/32 + 1] < 100)
			Right = true;

		if(GetDestination_x() - GetPos_x() < 0 && colData[abs(GetPos_y()/32) + 25][GetPos_x()/32 - 1] < 100)
			Left = true;

		if (GetDestination_y() - GetPos_y() < 0 && colData[abs(GetPos_y()/32) + 26][GetPos_x()/32] < 100)
			Down = true;

		if(GetDestination_y() - GetPos_y() > 0 && colData[abs(GetPos_y()/32) + 24][GetPos_x()/32] < 100)
			Up = true;




		if(GetDestination_x() - GetPos_x() > 0)
		{
			if(Right != true && Up != true && Down != true)
			{
				if(colData[abs(GetPos_y()/32) + 25][GetPos_x()/32 - 1] < 100)
				{
					MoveLeft();
				}

			}
			else if(Right == true && Up != true && Down != true)
			{
				MoveRight();
			}
			else if(Up == true || Down == true)
			{
				if(Right == true)
				{
					if(CalculateDistance_x() > CalculateDistance_y())
					{
						MoveRight();
					}
					else
					{
						if(Up == true)
						{
							MoveUp();
						}
						else if(Down == true)
						{
							MoveDown();
						}
					}
				}
				else
				{
					if(Up == true)
					{
						MoveUp();
					}
					else if(Down == true)
					{
						MoveDown();
					}
				}
			}
		}
		else if(GetDestination_x() - GetPos_x() < 0)
		{
			if(Left != true && Up != true && Down != true)
			{
				if(colData[abs(GetPos_y()/32) + 25][GetPos_x()/32 + 1] < 100)
					MoveRight();

			}
			else if(Left == true && Up != true && Down != true)
			{
				MoveLeft();
			}
			else if(Up == true || Down == true)
			{
				if(Left == true)
				{
					if(CalculateDistance_x() > CalculateDistance_y())
					{
						MoveLeft();
					}
					else
					{
						if(Up == true)
						{
							MoveUp();
						}
						else if(Down == true)
						{
							MoveDown();
						}
					}
				}
				else
				{
					if(Up == true)
					{
						MoveUp();
					}
					else if(Down == true)
					{
						MoveDown();
					}
				}
			}
		}
		else if(GetDestination_x() - GetPos_x() == 0)
		{
			if(Up == true)
			{
				MoveUp();
			}
			else if(Down == true)
			{
				MoveDown();
			}
		}
	}
}
Exemplo n.º 26
0
//------------------------------------------------------------------------------
bool TDRSSTwoWayRange::Evaluate(bool withEvents)
{
   bool retval = false;

   if (!initialized)
      InitializeMeasurement();

   #ifdef DEBUG_RANGE_CALC
      MessageInterface::ShowMessage("Entered TDRSSTwoWayRange::Evaluate()\n");
      MessageInterface::ShowMessage("  ParticipantCount: %d\n",
            participants.size());
   #endif

   if (withEvents == false)
   {
      #ifdef DEBUG_RANGE_CALC
         MessageInterface::ShowMessage("TDRSS 2-Way Range Calculation without "
               "events\n");
      #endif

      #ifdef VIEW_PARTICIPANT_STATES
         DumpParticipantStates("++++++++++++++++++++++++++++++++++++++++++++\n"
               "Evaluating TDRSS 2-Way Range without events");
      #endif

      if (CheckLOS(0, 1, NULL) && CheckLOS(1, 2, NULL))
      {
         // Calculate the range vector between the groundstation and the TDRS
         CalculateRangeVectorInertial(0, 1);
         Rvector3 outState;

         // Set feasibility off of topospheric horizon, set by the Z value in topo
         // coords
         std::string updateAll = "All";
         UpdateRotationMatrix(currentMeasurement.epoch, updateAll);
         outState = R_o_j2k * rangeVecInertial;
         currentMeasurement.feasibilityValue = outState[2];

         #ifdef CHECK_PARTICIPANT_LOCATIONS
            MessageInterface::ShowMessage("Evaluating without events\n");
            MessageInterface::ShowMessage("Calculating TDRSS 2-Way Range at epoch "
                  "%.12lf\n", currentMeasurement.epoch);
            MessageInterface::ShowMessage("   J2K Location of %s, id = '%s':  %s",
                  participants[0]->GetName().c_str(),
                  currentMeasurement.participantIDs[0].c_str(),
                  p1Loc.ToString().c_str());
            MessageInterface::ShowMessage("   J2K Location of %s, id = '%s':  %s",
                  participants[1]->GetName().c_str(),
                  currentMeasurement.participantIDs[1].c_str(),
                  p2Loc.ToString().c_str());
            Rvector3 bfLoc = R_o_j2k * p1Loc;
            MessageInterface::ShowMessage("   BodyFixed Location of %s:  %s",
                  participants[0]->GetName().c_str(),
                  bfLoc.ToString().c_str());
            bfLoc = R_o_j2k * p2Loc;
            MessageInterface::ShowMessage("   BodyFixed Location of %s:  %s\n",
                  participants[1]->GetName().c_str(),
                  bfLoc.ToString().c_str());
         #endif

         if (currentMeasurement.feasibilityValue > 0.0)
         {
            currentMeasurement.isFeasible = true;
            currentMeasurement.value[0] = rangeVecInertial.GetMagnitude();
            currentMeasurement.eventCount = 4;

            retval = true;
         }
      }
      else
      {
         currentMeasurement.isFeasible = false;
         currentMeasurement.value[0] = 0.0;
         currentMeasurement.eventCount = 0;
      }

      #ifdef DEBUG_RANGE_CALC
         MessageInterface::ShowMessage("Calculating Range at epoch %.12lf\n",
               currentMeasurement.epoch);
         MessageInterface::ShowMessage("   Location of %s, id = '%s':  %s",
               participants[0]->GetName().c_str(),
               currentMeasurement.participantIDs[0].c_str(),
               p1Loc.ToString().c_str());
         MessageInterface::ShowMessage("   Location of %s, id = '%s':  %s",
               participants[1]->GetName().c_str(),
               currentMeasurement.participantIDs[1].c_str(),
               p2Loc.ToString().c_str());
         MessageInterface::ShowMessage("   Range Vector (inertial):  %s\n",
               rangeVecInertial.ToString().c_str());
         MessageInterface::ShowMessage("   R(Groundstation) dot RangeVec =  %lf\n",
               currentMeasurement.feasibilityValue);
         MessageInterface::ShowMessage("   Feasibility:  %s\n",
               (currentMeasurement.isFeasible ? "true" : "false"));
         MessageInterface::ShowMessage("   Range is %.12lf\n",
               currentMeasurement.value[0]);
         MessageInterface::ShowMessage("   EventCount is %d\n",
               currentMeasurement.eventCount);
      #endif

      #ifdef SHOW_RANGE_CALC
         MessageInterface::ShowMessage("Range at epoch %.12lf is ",
               currentMeasurement.epoch);
         if (currentMeasurement.isFeasible)
            MessageInterface::ShowMessage("feasible, value = %.12lf\n",
               currentMeasurement.value[0]);
         else
            MessageInterface::ShowMessage("not feasible\n");
      #endif
   }
   else
   {
      // Calculate the corrected range measurement
      #ifdef DEBUG_RANGE_CALC
         MessageInterface::ShowMessage("TDRSS 2-Way Range Calculation:\n");
      #endif

      #ifdef VIEW_PARTICIPANT_STATES
         DumpParticipantStates("********************************************\n"
               "Evaluating TDRSS 2-Way Range with located events");
         MessageInterface::ShowMessage("Calculating TDRSS 2-Way Range at epoch "
               "%.12lf\n", currentMeasurement.epoch);
      #endif

      // Get the range from the downlink
      Rvector3 r1, r2;
      r1 = downlinkLeg.GetPosition(participants[0]);
      r2 = downlinkLeg.GetPosition(participants[1]);
      Rvector3 rVector = r2 - r1;
      Real realRange = rVector.GetMagnitude();

      #ifdef VIEW_PARTICIPANT_STATES
         MessageInterface::ShowMessage("   %s at downlink: %.12lf %.12lf %.12lf\n",
               participants[0]->GetName().c_str(), r1[0], r1[1], r1[2]);
         MessageInterface::ShowMessage("   %s at downlink: %.12lf %.12lf %.12lf\n",
               participants[1]->GetName().c_str(), r2[0], r2[1], r2[2]);
      #endif
      #ifdef DEBUG_RANGE_CALC
         MessageInterface::ShowMessage("   Downlink Range:  %.12lf\n",
               rVector.GetMagnitude());
      #endif

      r1 = backlinkLeg.GetPosition(participants[1]);
      r2 = backlinkLeg.GetPosition(participants[2]);
      if (CheckSat2SatLOS(r1, r2, NULL) == false)
         return false;
      rVector = r2 - r1;
      realRange += rVector.GetMagnitude();
      #ifdef VIEW_PARTICIPANT_STATES
         MessageInterface::ShowMessage("   %s at backlink: %.12lf %.12lf %.12lf\n",
               participants[1]->GetName().c_str(), r1[0], r1[1], r1[2]);
         MessageInterface::ShowMessage("   %s at backlink: %.12lf %.12lf %.12lf\n",
               participants[2]->GetName().c_str(), r2[0], r2[1], r2[2]);
      #endif

      #ifdef DEBUG_RANGE_CALC
         MessageInterface::ShowMessage("   Backlink Range:  %.12lf\n",
                  rVector.GetMagnitude());
      #endif

      // Add the pseudorange from the transponder delay
      targetDelay = GetDelay(2,0);
      #ifdef DEBUG_RANGE_CALC
         MessageInterface::ShowMessage("   TDRSS target delay is %.12lf\n",
               targetDelay);
      #endif
      realRange += GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM / GmatMathConstants::KM_TO_M *
            targetDelay;

      #ifdef DEBUG_RANGE_CALC
         MessageInterface::ShowMessage("   Delay Range (%le sec delay):  "
               "%.12lf\n", targetDelay,
               (GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM/GmatMathConstants::KM_TO_M * targetDelay));
      #endif

      r1 = forwardlinkLeg.GetPosition(participants[2]);
      r2 = forwardlinkLeg.GetPosition(participants[1]);
      if (CheckSat2SatLOS(r1, r2, NULL) == false)
         return false;
      rVector = r2 - r1;
      realRange += rVector.GetMagnitude();

      #ifdef VIEW_PARTICIPANT_STATES
         MessageInterface::ShowMessage("   %s at frwdlink: %.12lf %.12lf %.12lf\n",
               participants[2]->GetName().c_str(), r1[0], r1[1], r1[2]);
         MessageInterface::ShowMessage("   %s at frwdlink: %.12lf %.12lf %.12lf\n",
               participants[1]->GetName().c_str(), r2[0], r2[1], r2[2]);
      #endif
      #ifdef DEBUG_RANGE_CALC
         MessageInterface::ShowMessage("   forwardlink Range:  %.12lf\n",
               rVector.GetMagnitude());
      #endif

      r1 = uplinkLeg.GetPosition(participants[1]);
      r2 = uplinkLeg.GetPosition(participants[0]);
      rVector = r2 - r1;
      realRange += rVector.GetMagnitude();

      #ifdef VIEW_PARTICIPANT_STATES
         MessageInterface::ShowMessage("   %s at frwdlink: %.12lf %.12lf %.12lf\n",
               participants[1]->GetName().c_str(), r1[0], r1[1], r1[2]);
         MessageInterface::ShowMessage("   %s at frwdlink: %.12lf %.12lf %.12lf\n",
               participants[0]->GetName().c_str(), r2[0], r2[1], r2[2]);
      #endif
      #ifdef DEBUG_RANGE_CALC
         MessageInterface::ShowMessage("   Uplink Range:  %.12lf\n",
               rVector.GetMagnitude());
      #endif

      currentMeasurement.value[0] = realRange / 2.0;

      #ifdef DEBUG_RANGE_CALC
         MessageInterface::ShowMessage("   Calculated Range:  %.12lf\n",
               currentMeasurement.value[0]);
      #endif

      retval = true;
   }

   return retval;
}
Exemplo n.º 27
0
Animation *FrameRangeAnimation::Clone (animid_t newId) const {
	return new FrameRangeAnimation(
	 start, end, GetDelay(), GetContinuous(),
	 newId
	);
}
Exemplo n.º 28
0
/*--------------------------------------------------------------------------------*/
void DistanceModel::GetLevelAndDelay(double d, double& level, double& delay, double delayscale) const
{
  level = GetLevel(d);
  delay = GetDelay(d, delayscale);
}
Exemplo n.º 29
0
//------------------------------------------------------------------------------
bool USNTwoWayRange::Evaluate(bool withEvents)
{
   bool retval = false;

   if (!initialized)
      InitializeMeasurement();

   #ifdef DEBUG_RANGE_CALC
      MessageInterface::ShowMessage("Entered USNTwoWayRange::Evaluate()\n");
      MessageInterface::ShowMessage("  ParticipantCount: %d\n",
            participants.size());
   #endif

   if (withEvents == false)
   {
      #ifdef DEBUG_RANGE_CALC
         MessageInterface::ShowMessage("USN 2-Way Range Calculation without "
               "events\n");
      #endif

      #ifdef VIEW_PARTICIPANT_STATES
         DumpParticipantStates("++++++++++++++++++++++++++++++++++++++++++++\n"
               "Evaluating USN 2-Way Range without events");
      #endif

      CalculateRangeVectorInertial();
      Rvector3 outState;

      // Set feasibility off of topocentric horizon, set by the Z value in topo
      // coords
      std::string updateAll = "All";
      UpdateRotationMatrix(currentMeasurement.epoch, updateAll);
      outState = R_o_j2k * rangeVecInertial;
      currentMeasurement.feasibilityValue = outState[2];

      #ifdef CHECK_PARTICIPANT_LOCATIONS
         MessageInterface::ShowMessage("Evaluating without events\n");
         MessageInterface::ShowMessage("Calculating USN 2-Way Range at epoch "
               "%.12lf\n", currentMeasurement.epoch);
         MessageInterface::ShowMessage("   J2K Location of %s, id = '%s':  %s",
               participants[0]->GetName().c_str(),
               currentMeasurement.participantIDs[0].c_str(),
               p1Loc.ToString().c_str());
         MessageInterface::ShowMessage("   J2K Location of %s, id = '%s':  %s",
               participants[1]->GetName().c_str(),
               currentMeasurement.participantIDs[1].c_str(),
               p2Loc.ToString().c_str());
         Rvector3 bfLoc = R_o_j2k * p1Loc;
         MessageInterface::ShowMessage("   BodyFixed Location of %s:  %s",
               participants[0]->GetName().c_str(),
               bfLoc.ToString().c_str());
         bfLoc = R_o_j2k * p2Loc;
         MessageInterface::ShowMessage("   BodyFixed Location of %s:  %s\n",
               participants[1]->GetName().c_str(),
               bfLoc.ToString().c_str());
      #endif

      if (currentMeasurement.feasibilityValue > 0.0)
      {
         currentMeasurement.isFeasible = true;
         currentMeasurement.value[0] = rangeVecInertial.GetMagnitude();
         currentMeasurement.eventCount = 2;

         retval = true;
      }
      else
      {
         currentMeasurement.isFeasible = false;
         currentMeasurement.value[0] = 0.0;
         currentMeasurement.eventCount = 0;
      }

      #ifdef DEBUG_RANGE_CALC
         MessageInterface::ShowMessage("Calculating Range at epoch %.12lf\n",
               currentMeasurement.epoch);
         MessageInterface::ShowMessage("   Location of %s, id = '%s':  %s",
               participants[0]->GetName().c_str(),
               currentMeasurement.participantIDs[0].c_str(),
               p1Loc.ToString().c_str());
         MessageInterface::ShowMessage("   Location of %s, id = '%s':  %s",
               participants[1]->GetName().c_str(),
               currentMeasurement.participantIDs[1].c_str(),
               p2Loc.ToString().c_str());
         MessageInterface::ShowMessage("   Range Vector:  %s\n",
               rangeVecInertial.ToString().c_str());
         MessageInterface::ShowMessage("   R(Groundstation) dot RangeVec =  %lf\n",
               currentMeasurement.feasibilityValue);
         MessageInterface::ShowMessage("   Feasibility:  %s\n",
               (currentMeasurement.isFeasible ? "true" : "false"));
         MessageInterface::ShowMessage("   Range is %.12lf\n",
               currentMeasurement.value[0]);
         MessageInterface::ShowMessage("   EventCount is %d\n",
               currentMeasurement.eventCount);
      #endif

      #ifdef SHOW_RANGE_CALC
         MessageInterface::ShowMessage("Range at epoch %.12lf is ",
               currentMeasurement.epoch);
         if (currentMeasurement.isFeasible)
            MessageInterface::ShowMessage("feasible, value = %.12lf\n",
               currentMeasurement.value[0]);
         else
            MessageInterface::ShowMessage("not feasible\n");
      #endif
   }
   else
   {
      // Calculate the corrected range measurement
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("USN 2-Way Range Calculation:\n");
      #endif

      #ifdef VIEW_PARTICIPANT_STATES_WITH_EVENTS
         DumpParticipantStates("********************************************\n"
               "Evaluating USN 2-Way Range with located events");
      #endif

      // 1. Get the range from the down link
      Rvector3 r1, r2;
      r1 = downlinkLeg.GetPosition(participants[0]);
      r2 = downlinkLeg.GetPosition(participants[1]);
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("r1 = (%f,  %f,  %f)\n", r1.Get(0), r1.Get(1), r1.Get(2));
         MessageInterface::ShowMessage("r2 = (%f,  %f,  %f)\n", r2.Get(0), r2.Get(1), r2.Get(2));
      #endif
      Rvector3 downlinkVector = r2 - r1;		// rVector = r2 - r1;
      downlinkRange = downlinkVector.GetMagnitude();
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("   Downlink Range = r2-r1:  %.12lf km\n",
               downlinkRange);
      #endif

	   // 2. Calculate down link range rate:
      Rvector3 p1V = downlinkLeg.GetVelocity(participants[0]);
      Rvector3 p2V = downlinkLeg.GetVelocity(participants[1]);
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("p1V = (%f,  %f,  %f)\n", p1V.Get(0), p1V.Get(1), p1V.Get(2));
         MessageInterface::ShowMessage("p2V = (%f,  %f,  %f)\n", p2V.Get(0), p2V.Get(1), p2V.Get(2));
      #endif
      // @todo Relative origin velocities need to be subtracted when the origins
      // differ; check and fix that part using r12_j2k_vel here.  It's not yet
      // incorporated because we need to handle the different epochs for the
      // bodies, and we ought to do this part in barycentric coordinates
      Rvector downRRateVec = p2V - p1V /* - r12_j2k_vel*/;
      Rvector3 rangeUnit = downlinkVector.GetUnitVector();
      downlinkRangeRate = downRRateVec * rangeUnit;
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("   Downlink Range Rate:  %.12lf km/s\n",
               downlinkRangeRate);
      #endif

      // 3. Get the transponder delay
      targetDelay = GetDelay(1,0);
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage(
               "    USN Transponder delay for %s = %.12lf s\n",
               participants[1]->GetName().c_str(), targetDelay);
      #endif

      // 4. Get the range from the uplink
      Rvector3 r3, r4;
      r3 = uplinkLeg.GetPosition(participants[0]);
      r4 = uplinkLeg.GetPosition(participants[1]);
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("r3 = (%f,  %f,  %f)\n", r3.Get(0), r3.Get(1), r3.Get(2));
         MessageInterface::ShowMessage("r4 = (%f,  %f,  %f)\n", r4.Get(0), r4.Get(1), r4.Get(2));
      #endif
      Rvector3 uplinkVector = r4 - r3;
      uplinkRange = uplinkVector.GetMagnitude();
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("   Uplink Range = r4-r3:  %.12lf km\n",
               uplinkRange);
      #endif

	   // 5. Calculate up link range rate
      Rvector3 p3V = uplinkLeg.GetVelocity(participants[0]);
      Rvector3 p4V = uplinkLeg.GetVelocity(participants[1]);
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("p3V = (%f,  %f,  %f)\n", p3V.Get(0), p3V.Get(1), p3V.Get(2));
         MessageInterface::ShowMessage("p4V = (%f,  %f,  %f)\n", p4V.Get(0), p4V.Get(1), p4V.Get(2));
      #endif
      // @todo Relative origin velocities need to be subtracted when the origins
      // differ; check and fix that part using r12_j2k_vel here.  It's not yet
      // incorporated because we need to handle the different epochs for the
      // bodies, and we ought to do this part in barycentric coordinates
      Rvector upRRateVec = p4V - p3V /* - r12_j2k_vel*/ ;
      rangeUnit = uplinkVector.GetUnitVector();
      uplinkRangeRate = upRRateVec * rangeUnit;
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("   Uplink Range Rate:  %.12lf km/s\n",
               uplinkRangeRate);
      #endif

      // 5.1. Target range rate: Do we need this as well?
      targetRangeRate = (downlinkRangeRate + uplinkRangeRate) / 2.0;
	   #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("   Target Range Rate:  %.12lf km/s\n",
                targetRangeRate);
		#endif
      

	   // 6. Get sensors used in USN 2-ways range
	   ObjectArray objList1;
	   ObjectArray objList2;
	   ObjectArray objList3;
	   //			objList1 := all transmitters in participantHardware list
	   //			objList2 := all receivers in participantHardware list
	   //			objList3 := all transponders in participantHardware list
	   if (participantHardware.empty()||
	   		((!participantHardware.empty())&&
	   		  participantHardware[0].empty()&&
	   		  participantHardware[1].empty()
	   		)
	   	)
	   {
	   	// DO NOT LEAVE THIS TYPE OF MESSAGE IN THE CODE WITHOUT #ifdef WRAPPERS!!!
         //MessageInterface::ShowMessage("    Ideal measurement (no hardware delay and no media correction involve):\n");
		   Real realRange = (uplinkRange + downlinkRange)/2;
		   #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
				MessageInterface::ShowMessage("   Range = %.12lf km\n", realRange);
			#endif

	   	// Set value for currentMeasurement
		   currentMeasurement.value[0] = realRange;
	      currentMeasurement.isFeasible = true;

	      return true;
	   }

	   for(std::vector<Hardware*>::iterator hw = this->participantHardware[0].begin();
	   		hw != this->participantHardware[0].end(); ++hw)
	   {
	   	if ((*hw) != NULL)
	   	{
	   		if ((*hw)->GetTypeName() == "Transmitter")
	   			objList1.push_back(*hw);
	   		if ((*hw)->GetTypeName() == "Receiver")
	   			objList2.push_back(*hw);
	   	}
	   	else
	   		MessageInterface::ShowMessage(" sensor = NULL\n");
	   }

	   for(std::vector<Hardware*>::iterator hw = this->participantHardware[1].begin();
	   		hw != this->participantHardware[1].end(); ++hw)
	   {
	   	if ((*hw) != NULL)
	   	{
	   		if ((*hw)->GetTypeName() == "Transponder")
	   			objList3.push_back(*hw);
	   	}
	   	else
	   		MessageInterface::ShowMessage(" sensor = NULL\n");
	   }

	   if (objList1.size() != 1)
	   {
	   	MessageInterface::ShowMessage("The first participant does not have only 1 transmitter to send signal.\n");
	      throw new MeasurementException("The first participant does not have only 1 transmitter to send signal.\n");
	   }
	   if (objList2.size() != 1)
	   {
	   	MessageInterface::ShowMessage("The first participant does not have only 1 receiver to receive signal.\n");
	      throw new MeasurementException("The first participant does not have only 1 receiver to receive signal.\n");
	   }
	   if (objList3.size() != 1)
	   {
	   	MessageInterface::ShowMessage("The second participant does not have only 1 transponder to transpond signal.\n");
  			throw new MeasurementException("The second participant does not have only 1 transponder to transpond signal.\n");
	   }

	   Transmitter* 	gsTransmitter 	= (Transmitter*)objList1[0];
	   Receiver* 		gsReceiver 		= (Receiver*)objList2[0];
	   Transponder* 	scTransponder 	= (Transponder*)objList3[0];
	   if (gsTransmitter == NULL)
	   {
	   	MessageInterface::ShowMessage("Transmitter is NULL object.\n");
	   	throw new GmatBaseException("Transmitter is NULL object.\n");
	   }
	   if (gsReceiver == NULL)
	   {
	   	MessageInterface::ShowMessage("Receiver is NULL object.\n");
	   	throw new GmatBaseException("Receiver is NULL object.\n");
	   }
	   if (scTransponder == NULL)
	   {
	   	MessageInterface::ShowMessage("Transponder is NULL object.\n");
	   	throw new GmatBaseException("Transponder is NULL object.\n");
	   }

		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("   List of sensors: %s, %s, %s\n",
					gsTransmitter->GetName().c_str(), gsReceiver->GetName().c_str(),
					scTransponder->GetName().c_str());
		#endif


	   // 7. Get frequency from transmitter of ground station (participants[0])
	   Signal* uplinkSignal = gsTransmitter->GetSignal();
	   Real uplinkFreq = uplinkSignal->GetValue();

		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("   UpLink signal frequency = %.12lf MHz\n", uplinkFreq);
		#endif

	   // 8. Calculate media correction for uplink leg:
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("      Media correction for uplink leg\n");
      #endif
      Real roundTripTime = ((uplinkRange + downlinkRange)*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM)/GmatTimeConstants::SECS_PER_DAY;
      // DO NOT LEAVE THIS TYPE OF MESSAGE IN THE CODE WITHOUT #ifdef WRAPPERS!!!
      //MessageInterface::ShowMessage("Round trip time = %.12lf\n", roundTripTime);
      RealArray uplinkCorrection = CalculateMediaCorrection(uplinkFreq, r1, r2, currentMeasurement.epoch - roundTripTime);
      Real uplinkRangeCorrection = uplinkCorrection[0]/GmatMathConstants::KM_TO_M;
      Real uplinkRealRange = uplinkRange + uplinkRangeCorrection;
		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("      Uplink range correction = %.12lf km\n",uplinkRangeCorrection);
			MessageInterface::ShowMessage("      Uplink real range = %.12lf km\n",uplinkRealRange);
		#endif

		// 9. Doppler shift the frequency from the transmitter using uplinkRangeRate:
	   Real uplinkDSFreq = (1 - uplinkRangeRate*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM)*uplinkFreq;

		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("    Uplink Doppler shift frequency = %.12lf MHz\n", uplinkDSFreq);
		#endif

	   // 10.Set frequency for the input signal of transponder
	   Signal* inputSignal = scTransponder->GetSignal(0);
	   inputSignal->SetValue(uplinkDSFreq);
	   scTransponder->SetSignal(inputSignal, 0);

	   // 11. Check the transponder feasibility to receive the input signal:
	   if (scTransponder->IsFeasible(0) == false)
	   {
	   	 currentMeasurement.isFeasible = false;
	   	 currentMeasurement.value[0] = 0;
	   	 MessageInterface::ShowMessage("The transponder is unfeasible to receive uplink signal.\n");
	   	 throw new GmatBaseException("The transponder is unfeasible to receive uplink signal.\n");
	   }

	   // 12. Get frequency of transponder output signal
	   Signal* outputSignal = scTransponder->GetSignal(1);
	   Real downlinkFreq = outputSignal->GetValue();

		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("    Downlink frequency = %.12lf Mhz\n", downlinkFreq);
		#endif

	   // 13. Doppler shift the transponder output frequency by the downlinkRangeRate:
	   Real downlinkDSFreq = (1 - downlinkRangeRate*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM)*downlinkFreq;

	   #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("    Downlink Doppler shift frequency = %.12lf MHz\n", downlinkDSFreq);
		#endif

	   // 14. Set frequency on receiver
	   Signal* downlinkSignal = gsReceiver->GetSignal();
	   downlinkSignal->SetValue(downlinkDSFreq);

	   // 15. Check the receiver feasibility to receive the downlink signal
	   if (gsReceiver->IsFeasible() == false)
	   {
	   	 currentMeasurement.isFeasible = false;
	   	 currentMeasurement.value[0] = 0;
	   	 throw new MeasurementException("The receiver is unfeasible to receive downlink signal.\n");
	   }

	   // 16. Calculate media correction for downlink leg:
	   #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
	      MessageInterface::ShowMessage("      Media correction for downlink leg\n");
	   #endif
	   RealArray downlinkCorrection = CalculateMediaCorrection(downlinkDSFreq, r3, r4, currentMeasurement.epoch);
	   Real downlinkRangeCorrection = downlinkCorrection[0]/GmatMathConstants::KM_TO_M;
	   Real downlinkRealRange = downlinkRange + downlinkRangeCorrection;
		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("      Downlink range correction = %.12lf km\n",downlinkRangeCorrection);
			MessageInterface::ShowMessage("      Downlink real range = %.12lf km\n",downlinkRealRange);
		#endif


	   // 17. Calculate uplink time and down link time: (Is it needed???)
	   uplinkTime   = uplinkRealRange*GmatMathConstants::KM_TO_M / GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM;
	   downlinkTime = downlinkRealRange*GmatMathConstants::KM_TO_M / GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM;

		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("    Uplink time = %.12lf s\n",uplinkTime);
			MessageInterface::ShowMessage("    Downlink time = %.12lf s\n",downlinkTime);
		#endif

	   // 18. Calculate real range
	   Real realRange = uplinkRealRange + downlinkRealRange +
	   		targetDelay*GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM / GmatMathConstants::KM_TO_M;
	   
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("   Calculated real range = %.12lf km\n", realRange/2);
      #endif

	   // 19. Set value for currentMeasurement
	   currentMeasurement.value[0] = realRange / 2.0;
      currentMeasurement.isFeasible = true;


      #ifdef PRELIMINARY_DERIVATIVE_CHECK
         MessageInterface::ShowMessage("Participants:\n ");
         for (UnsignedInt i = 0; i < participants.size(); ++i)
            MessageInterface::ShowMessage("   %d: %s of type %s\n", i,
                  participants[i]->GetName().c_str(),
                  participants[i]->GetTypeName().c_str());

         Integer id = participants[1]->GetType() * 250 +
               participants[1]->GetParameterID("CartesianX");
         CalculateMeasurementDerivatives(participants[1], id);
      #endif

      retval = true;
   }

   return retval;
}
Exemplo n.º 30
0
//-------------------------------------------------------------------------
//-- Returns true if the Timer is running.
boolean CAutoSave::IsEnabled()
{
	return (GetDelay() > 0);
}