Example #1
0
// traces the entity and calculates the mouse move delta on screen
void VMonitorGUIContext::TestPicking()
{
    m_vTraceDelta.setZero();
    m_bPicked = false;

    hkvVec3 vStart = Vision::Camera.GetCurrentCameraPosition();
#if defined(_VISION_MOBILE) || defined( _VISION_APOLLO ) || defined( _VISION_METRO )       // TODO: Define _VISION_MOBILE on Apollo.
    hkvVec3 vDir(0.0f, 0.0f, 0.0f);
    if(VInputManager::GetTouchScreen().IsActiveTouch(0))
    {
        const float fX = VInputManager::GetTouchScreen().GetTouchPointValue(0, CT_TOUCH_ABS_X, false);
        const float fY = VInputManager::GetTouchScreen().GetTouchPointValue(0, CT_TOUCH_ABS_Y, false);

        VisRenderContext_cl::GetMainRenderContext()->GetTraceDirFromScreenPos(fX, fY, vDir, m_fTraceRange);
    }
    else
    {
        return;
    }

    hkvVec3 vEnd = vStart + vDir;
#else
    hkvVec3 vEnd = vStart + Vision::Camera.GetCurrentCameraDirection()*m_fTraceRange;
#endif
    VisTraceLineInfo_t traceInfo;

    Vision::CollisionToolkit.TraceLine(vStart, vEnd, (ULONG)VIS_TRACE_ALL, VIS_TRACE_NONE, NULL, NULL, &traceInfo,
                                       VIS_TRACESETTINGS_FORCEOBJ_POLYGONACC|VIS_TRACESETTINGS_STOREBASEUV|VIS_TRACESETTINGS_STORESURFACEINFO);

    if (!traceInfo.detected || traceInfo.pSurface!=m_pGUISurface)
        return;

    hkvVec2 vNewPos;
    vNewPos.x = m_ClientRect.m_vMin.x + traceInfo.baseUV.x*m_ClientRect.GetSizeX();
    vNewPos.y = m_ClientRect.m_vMin.y + traceInfo.baseUV.y*m_ClientRect.GetSizeY();

    m_vTraceDelta = vNewPos-m_vMouseTracePos;
    m_vMouseTracePos = vNewPos;
    m_bPicked = true;
}
Example #2
0
float CN3ShapeMgr::GetHeightNearstPos(const __Vector3 &vPos, __Vector3* pvNormal) // °¡Àå °¡±î¿î ³ôÀÌ°ªÀ» µ¹·ÁÁØ´Ù. ¾øÀ¸¸é -FLT_MAX À» µ¹·ÁÁØ´Ù.
{
	__CellSub* pCell = this->SubCell(vPos.x, vPos.z); // ¼­ºê¼¿À» °¡Á®¿Â´Ù..
	if(nullptr == pCell || pCell->nCCPolyCount <= 0) return -FLT_MAX; // ¾øÀ½ ¸»ÀÚ.

	__Vector3 vPosV = vPos; vPosV.y = 5000.0f; // ²À´ë±â¿¡ À§Ä¡¸¦ ÇÏ°í..
	__Vector3 vDir(0,-1, 0); // ¼öÁ÷ ¹æÇâ º¤ÅÍ
	__Vector3 vColTmp(0,0,0); // ÃÖÁ¾ÀûÀ¸·Î °¡Àå °¡±î¿î Ãæµ¹ À§Ä¡..

	int nIndex0, nIndex1, nIndex2;
	float fT, fU, fV;
	float fNearst = FLT_MAX, fMinTmp = 0, fHeight = -FLT_MAX;		// ÀÏ´Ü ÃÖ¼Ò°ªÀ» Å«°ªÀ¸·Î Àâ°í..

	for ( int i = 0; i < pCell->nCCPolyCount; i++ )
	{
		nIndex0 = pCell->pdwCCVertIndices[i*3];
		nIndex1 = pCell->pdwCCVertIndices[i*3+1];
		nIndex2 = pCell->pdwCCVertIndices[i*3+2];

		// Ãæµ¹µÈ Á¡ÀÌ ÀÖÀ¸¸é..
		if(true == ::_IntersectTriangle(vPosV, vDir, m_pvCollisions[nIndex0], m_pvCollisions[nIndex1], m_pvCollisions[nIndex2], fT, fU, fV, &vColTmp))
		{
			fMinTmp = (vColTmp - vPos).Magnitude();
			if(fMinTmp < fNearst) // °¡Àå °¡±î¿î Ãæµ¹ À§Ä¡¸¦ ã±â À§ÇÑ ÄÚµå..
			{
				fNearst = fMinTmp;
				fHeight = vColTmp.y; // ³ôÀÌ°ª.

				if(pvNormal)
				{
					pvNormal->Cross(m_pvCollisions[nIndex1] - m_pvCollisions[nIndex0], m_pvCollisions[nIndex2] - m_pvCollisions[nIndex0]);
					pvNormal->Normalize();
				}
			}
		}
	}

	return fHeight;
}
Example #3
0
float CN3ShapeMgr::GetHeight(float fX, float fZ, __Vector3* pvNormal) // °¡Àå ³ôÀº °÷À» µ¹·ÁÁØ´Ù.. ¾øÀ¸¸é -FLT_MAX°ªÀ» µ¹·ÁÁØ´Ù.
{
	__CellSub* pCell = this->SubCell(fX, fZ); // ¼­ºê¼¿À» °¡Á®¿Â´Ù..
	if(nullptr == pCell || pCell->nCCPolyCount <= 0) return -FLT_MAX; // ¾øÀ½ ¸»ÀÚ.

	__Vector3 vPosV(fX, 5000.0f, fZ); // ²À´ë±â¿¡ À§Ä¡¸¦ ÇÏ°í..
	__Vector3 vDir(0,-1, 0); // ¼öÁ÷ ¹æÇâ º¤ÅÍ
	__Vector3 vColTmp(0,0,0); // ÃÖÁ¾ÀûÀ¸·Î °¡Àå °¡±î¿î Ãæµ¹ À§Ä¡..

	int nIndex0, nIndex1, nIndex2;
	float fT, fU, fV;
	float fMaxTmp = -FLT_MAX;;

	for ( int i = 0; i < pCell->nCCPolyCount; i++ )
	{
		nIndex0 = pCell->pdwCCVertIndices[i*3];
		nIndex1 = pCell->pdwCCVertIndices[i*3+1];
		nIndex2 = pCell->pdwCCVertIndices[i*3+2];

		// Ãæµ¹µÈ Á¡ÀÌ ÀÖÀ¸¸é..
		if(true == ::_IntersectTriangle(vPosV, vDir, m_pvCollisions[nIndex0], m_pvCollisions[nIndex1], m_pvCollisions[nIndex2], fT, fU, fV, &vColTmp))
		{
			if(vColTmp.y > fMaxTmp)
			{
				fMaxTmp = vColTmp.y;
				if(pvNormal)
				{
					pvNormal->Cross(m_pvCollisions[nIndex1] - m_pvCollisions[nIndex0], m_pvCollisions[nIndex2] - m_pvCollisions[nIndex0]);
					pvNormal->Normalize();
				}
			}
		}
	}

	return fMaxTmp;
}
void CLudeCommandPackageBuildNumber::updateBuildNumber(int inc)
{
    QDir vDir(QDir::currentPath());
    vDir.setNameFilters(QStringList()<<"*.pro");
    QStringList one =  vDir.entryList(QDir::Files);
    if(one.size()!=1){
        qDebug() << "No pro file found.";
        return;
    }

    QString name = one[0].replace(".pro","");
    //NOTE changed cludepackage.json to <package_name>.cde
    QString vPath = QDir::toNativeSeparators(QDir::currentPath()+QLatin1String("/")+name+QLatin1String(".cde"));
    QFile vFile(vPath);
    if(!vFile.exists()){
        qDebug() << "PATH: "<<vPath;
        qDebug() << QString("%1.cde file doesn't exists").arg(name).toLocal8Bit().constData();
    }
    else{
        CLudePackage clp;
        qDebug() << vPath.toLocal8Bit().constData();
        if(clp.fromJsonFile(vPath)){
            clp.setUpdated(QDateTime::currentDateTime().toLocalTime());
            clp.setBuild(clp.build()+inc);
            if(clp.toJsonFile(vPath)){
                qDebug() << "build updated to :"<<clp.build();
            }
            else{
                qDebug() << "failed to update build";
            }
        }
        else{
            qDebug() << QString("%1.cde file parsing error").arg(name).toLocal8Bit().constData();
        }
    }
}
bool vHavokAiModule::ComputeAndDrawPath(IVRenderInterface *pRenderer, hkvVec3* startPoint, hkvVec3* endPoint, float radius, float height, float displayOffset, unsigned int color) const
{
	hkaiPathfindingUtil::FindPathInput input(1);
	hkaiPathfindingUtil::FindPathOutput output;
	bool foundPath = _ComputePath(m_aiWorld, startPoint, endPoint, radius, input, output);

	if (input.m_startFaceKey != HKAI_INVALID_PACKED_KEY && input.m_goalFaceKeys[0] != HKAI_INVALID_PACKED_KEY)
	{
		vHavokAiNavMeshDebugDisplayHandler displayHandler;
		hkReal displayOffsetHavokScale = VIS2HK_FLOAT_SCALED(displayOffset);
		hkaiNavMeshDebugUtils::_drawPathWithRadius(input, output, color, hkColor::ORANGE, &displayHandler, 0, displayOffsetHavokScale);
	}

	hkvVec3 vStartPos; vHavokConversionUtils::PhysVecToVisVecWorld(input.m_startPoint,vStartPos); 
	hkvVec3 vEndPos; vHavokConversionUtils::PhysVecToVisVecWorld(input.m_goalPoints[0],vEndPos); 
	hkvVec3 vDir ( 0.f, 0.f, height );
	VSimpleRenderState_t state(VIS_TRANSP_NONE, RENDERSTATEFLAG_FRONTFACE|RENDERSTATEFLAG_WRITETOZBUFFER);	
	int sd = (input.m_startFaceKey != HKAI_INVALID_PACKED_KEY) ? 1 : 2;
	int ed = (input.m_goalFaceKeys[0] != HKAI_INVALID_PACKED_KEY) ? 1 : 2;
	pRenderer->RenderCylinder(vStartPos, vDir, radius, VColorRef(255/sd, 165/sd, 0/sd), state, RENDERSHAPEFLAGS_SOLID|RENDERSHAPEFLAGS_CAP1);
	pRenderer->RenderCylinder(vEndPos, vDir, radius, VColorRef(0/ed, 128/ed, 0/ed), state, RENDERSHAPEFLAGS_SOLID|RENDERSHAPEFLAGS_CAP1);

	return foundPath;
}
Example #6
0
	void SmtPerspCamera::MoveEyeImmediately(float fDis)
	{
		Vector3 vDir(m_vEye-m_vTarget);
		vDir.Normalize();
		m_vEye = vDir*fDis+m_vTarget;
	}
Example #7
0
	void SmtPerspCamera::Yaw(float angle)				//╚кyор
	{
		Vector3 vDir(m_vTarget - m_vEye);
		vDir.Rotate(m_vUp,angle);
		m_vTarget = m_vEye + vDir;
	}
Example #8
0
/// Used to update any time dependent state (such as timeouts)
void CFlowNode_FeatureTest::Update(float deltaTime)
{
	if(m_running)
	{
		m_timeRunning += deltaTime;
		CryWatch("$7[FG FeatureTest]$o Running test '%s'", Name());

		const string &description = GetPortString(&m_actInfo, eInputPorts_Description);

		if(!description.empty())
			CryWatch("$7[FG FeatureTest]$o %s", description.c_str());

		const float maxTime = GetPortFloat(&m_actInfo, eInputPorts_MaxTime);

		IEntity *pFollowEntity = NULL;

		// Firstly, attempt to get the camera entity (index: -1)
		bool bHasEntry = GetEntityAtIndex(-1, pFollowEntity);

		if(!bHasEntry && !pFollowEntity)
		{
			// If there's an entity being tested, force the view camera to follow it (if no camera entity defined)
			// This needs to be implemented in a cleaner way and allow other options for non-entity based tests.
			bHasEntry = GetEntityAtIndex(m_entitySeqIndex, pFollowEntity);

			// If no sequence entity defined
			if(!bHasEntry && !pFollowEntity)
			{
				// Look for another suitable (active) entity to follow
				for(int i = 0; i < SEQ_ENTITY_COUNT; ++i)
				{
					GetEntityAtIndex(i, pFollowEntity);

					if(pFollowEntity && pFollowEntity->IsActive())
					{
						break;
					}
				}
			}
		}

		if(pFollowEntity)
		{
			CCamera &viewCamera = gEnv->pSystem->GetViewCamera();

			Vec3 vPos(0,0,0);
			Vec3 vDir(0,0,0);

			AABB bounds;
			pFollowEntity->GetWorldBounds(bounds);

			Vec3 vTarget;
			vTarget = bounds.GetCenter();

			vPos = vTarget + (pFollowEntity->GetForwardDir().GetNormalizedSafe() * -2.5f) + Vec3(0.0f, 0.0f, 1.0f);
			vDir = (vTarget - vPos).GetNormalizedSafe();

			float	fRoll(0.0f);

			viewCamera.SetMatrix(CCamera::CreateOrientationYPR(CCamera::CreateAnglesYPR(vDir, fRoll)));
			viewCamera.SetPosition(vPos);
		}

		// If a valid max time has been set
		if(maxTime > 0.0f)
		{
			// If test has exceeded max time
			if(m_timeRunning >= maxTime)
			{
				OnTestResult(false, string().Format("Test failed: Test exceeded maximum time (%f).", maxTime).c_str());
			}
		}
	}
}
void CWndChangeSex::OnDraw( C2DRender* p2DRender ) 
{ 
	if( g_pPlayer == NULL  )
		return;

	LPDIRECT3DDEVICE9 pd3dDevice = p2DRender->m_pd3dDevice;

	pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE );
	pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );
	pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW );
	pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE );
	pd3dDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID );
	pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_SELECTARG1 );

	pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
	pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_SELECTARG1 );
	pd3dDevice->SetSamplerState ( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
	pd3dDevice->SetSamplerState ( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );

	pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_SELECTARG1 );

	pd3dDevice->SetRenderState( D3DRS_AMBIENT,  D3DCOLOR_ARGB( 255, 255,255,255) );
	
	CRect rect = GetClientRect();

	// 뷰포트 세팅 
	D3DVIEWPORT9 viewport;

	// 월드 
	D3DXMATRIXA16 matWorld;
	D3DXMATRIXA16 matScale;
	D3DXMATRIXA16 matRot;
	D3DXMATRIXA16 matTrans;

	// 카메라 
	D3DXMATRIX  matView;
	D3DXVECTOR3 vecLookAt( 0.0f, 0.0f, 3.0f );
	D3DXVECTOR3 vecPos(  0.0f, 0.7f, -3.5f );
	
	D3DXMatrixLookAtLH( &matView, &vecPos, &vecLookAt, &D3DXVECTOR3(0.0f,1.0f,0.0f) );
	
	pd3dDevice->SetTransform( D3DTS_VIEW, &matView );
	
	// 왼쪽 원본 모델 랜더링
	{
		LPWNDCTRL lpFace = GetWndCtrl( WIDC_STATIC1 );

		viewport.X      = p2DRender->m_ptOrigin.x + lpFace->rect.left;//2;
		viewport.X     -= 6;
		viewport.Y      = p2DRender->m_ptOrigin.y + lpFace->rect.top;//5;
		viewport.Width  = lpFace->rect.Width();//p2DRender->m_clipRect.Width();
		viewport.Height = lpFace->rect.Height();// - 10;//p2DRender->m_clipRect.Height();

		viewport.MinZ   = 0.0f;
		viewport.MaxZ   = 1.0f;
		pd3dDevice->SetViewport(&viewport);
		pd3dDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, 0xffa08080, 1.0f, 0 ) ;

		D3DXMATRIX matProj;
		D3DXMatrixIdentity( &matProj );
		FLOAT fAspect = ((FLOAT)viewport.Width) / (FLOAT)viewport.Height;
/*		
		D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4.0f, fAspect, CWorld::m_fNearPlane - 0.01f, CWorld::m_fFarPlane );
		pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );
*/		
		FLOAT fov = D3DX_PI/4.0f;//796.0f;
		FLOAT h = cos(fov/2) / sin(fov/2);
		FLOAT w = h * fAspect;
		D3DXMatrixOrthoLH( &matProj, w, h, CWorld::m_fNearPlane - 0.01f, CWorld::m_fFarPlane );
		pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );
		
	    D3DXMatrixIdentity(&matScale);
		D3DXMatrixIdentity(&matTrans);
		D3DXMatrixIdentity(&matWorld);
		
		D3DXMatrixScaling(&matScale, 4.5f, 4.5f, 4.5f);
		
		if( g_pPlayer->GetSex() == SEX_MALE )
			D3DXMatrixTranslation(&matTrans,0.0f,-5.6f,0.0f);
		else
			D3DXMatrixTranslation(&matTrans,0.0f,-5.8f,0.0f);

		D3DXMatrixMultiply(&matWorld,&matWorld,&matScale);
		D3DXMatrixMultiply(&matWorld, &matWorld, &matTrans );
		pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );

		// 랜더링 
		pd3dDevice->SetRenderState( D3DRS_FOGENABLE, FALSE );
		pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );//m_bViewLight );
		
		::SetLight( FALSE );
		::SetFog( FALSE );
		SetDiffuse( 1.0f, 1.0f, 1.0f );
		SetAmbient( 1.0f, 1.0f, 1.0f );
/*
		m_pModel->GetObject3D(PARTS_HAIR)->m_fAmbient[0] = 0.5f;
		m_pModel->GetObject3D(PARTS_HAIR)->m_fAmbient[1] = 0.5f;
		m_pModel->GetObject3D(PARTS_HAIR)->m_fAmbient[2] = 0.5f;
*/		
		D3DXVECTOR4 vConst( 1.0f, 1.0f, 1.0f, 1.0f );
#ifdef __YENV
		D3DXVECTOR3 vDir( 0.0f, 0.0f, 1.0f );
		SetLightVec( vDir );
		
		g_Neuz.m_pEffect->SetVector( g_Neuz.m_hvFog, &vConst );
#else //__YENV						
		pd3dDevice->SetVertexShaderConstantF( 95, (float*)&vConst, 1 );
#endif //__YENV
		::SetTransformView( matView );
		::SetTransformProj( matProj );
				
		m_pModel->Render( p2DRender->m_pd3dDevice, &matWorld );
	}
} 
Example #10
0
void VisMouseCamera_cl::TickFunction(float fTimeDiff)
{
  hkvVec3 vMove = hkvVec3::ZeroVector();
  BOOL bUpDownMode = FALSE;

  float dx = m_pInputMap->GetTrigger(API_CAMERA_HORIZONTAL_LOOK);
  float dy = m_pInputMap->GetTrigger(API_CAMERA_VERTICAL_LOOK);

  if (m_pInputMap->GetTrigger(API_CAMERA_ACTION_1) && m_pInputMap->GetTrigger(API_CAMERA_ACTION_2))
    bUpDownMode = TRUE;
  else if (m_pInputMap->GetTrigger(API_CAMERA_ACTION_2))
    m_SpeedMode = 1;
  else if (m_pInputMap->GetTrigger(API_CAMERA_ACTION_3))
    m_SpeedMode = 2;
  else
    m_SpeedMode = 0;

  // handle keyboard status
#if !defined(_VISION_MOBILE) && !defined(_VISION_WINRT)
  if (m_pInputMap->GetTrigger(API_CAMERA_ANY_ACTION))
#endif
  {
    hkvVec3 vDir(hkvNoInitialization), vRight(hkvNoInitialization), vUp(hkvNoInitialization);
    vUp.set(0.f,0.f,1.f);
    if (GetPhysicsObject())
    {
      // local space
      vDir.set(1.f,0.f,0.f);
      vRight.set(0.f,1.f,0.f);
    } 
    else
    {
      hkvMat3 mat(hkvNoInitialization);
      GetRotationMatrix(mat);
      vDir = mat.getAxis(0);
      vRight = mat.getAxis(1);
    }

    float fMaxSpeed = m_fMoveSpeed;
    if (m_SpeedMode == 1)
      fMaxSpeed *= 3.0f;
    else if (m_SpeedMode == 2)
      fMaxSpeed *= 9.0f;

    // Accumulate move directions (multiply in order to take analog input into account).
    vMove += vDir * m_pInputMap->GetTrigger(API_CAMERA_MOVE_FORWARD);
    vMove -= vDir * m_pInputMap->GetTrigger(API_CAMERA_MOVE_BACKWARD);
    vMove -= vRight * m_pInputMap->GetTrigger(API_CAMERA_MOVE_RIGHT);
    vMove += vRight * m_pInputMap->GetTrigger(API_CAMERA_MOVE_LEFT);
    vMove += vUp *  m_pInputMap->GetTrigger(API_CAMERA_MOVE_UP);
    vMove -= vUp * m_pInputMap->GetTrigger(API_CAMERA_MOVE_DOWN);
    vMove *= fMaxSpeed;
   
    // Clamp movement, so that moving diagonally is not faster than moving straight 
    // when using digital input.
    const float fSpeed = vMove.getLength();
    if (fSpeed > fMaxSpeed)
      vMove.setLength(fMaxSpeed);
    vMove *= fTimeDiff;
  }

  if (m_pInputMap->GetTrigger(API_CAMERA_LOOK_CHANGED))
  {
    if (bUpDownMode)
    {
      IncOrientation(-dx * m_fSensitivity, 0, 0);
      vMove.z -= dy * m_fUpDownSpeed;
    }
    else
    {
      IncOrientation(-dx * m_fSensitivity, dy * m_fSensitivity, 0);                   
    }
  }

  switch(m_walkMode)
  {
  case WALK:
    // constrain vMove to the ground
    float len = vMove.getLength();
    vMove.z = 0.f;
    vMove.setLength(len);
    break;
  }

  if (GetPhysicsObject())
  {
    IncMotionDeltaLocalSpace(vMove);
  }
  else
  {
    IncPosition( vMove );
  }
}
LTBOOL CFireFX::Update()
{
	CSFXMgr* psfxMgr = g_pGameClientShell->GetSFXMgr();
    if (!psfxMgr || !m_pClientDE || !m_hServerObject) return LTFALSE;

    LTFLOAT fTime = m_pClientDE->GetTime();

	// Check to see if we should go away...

	if (m_bWantRemove)
	{
        return LTFALSE;
	}


	// Update FX...

	if (m_cs.bCreateSmoke)
	{
		m_Smoke1.Update();
	}

	if (m_cs.bCreateLight)
	{
		m_Light.Update();
	}

	m_Fire1.Update();
	m_Fire2.Update();


	// Hide/show the fire if necessary...

	if (m_hServerObject)
	{
        uint32 dwUserFlags;
		m_pClientDE->GetObjectUserFlags(m_hServerObject, &dwUserFlags);

		if (!(dwUserFlags & USRFLG_VISIBLE))
		{
			if (m_hSound)
			{
                g_pLTClient->KillSound(m_hSound);
                m_hSound = LTNULL;
			}

            return LTTRUE;
		}
		else
		{
			if (m_cs.bCreateSound && !m_hSound)
			{
				CString str = g_pClientButeMgr->GetSpecialFXAttributeString("FireSnd");

				m_hSound = g_pClientSoundMgr->PlaySoundFromPos(m_cs.vPos, (char*)(LPCSTR)str,
					m_cs.fSoundRadius, SOUNDPRIORITY_MISC_MEDIUM, PLAYSOUND_GETHANDLE | PLAYSOUND_LOOP);
			}
		}
	}

	// Create the random spark particles...

	if (m_cs.bCreateSparks && GetRandom(1, 10) == 1)
	{
		CSFXMgr* psfxMgr = g_pGameClientShell->GetSFXMgr();
        if (!psfxMgr) return LTFALSE;

		RANDOMSPARKSCREATESTRUCT sparks;
		sparks.hServerObj = m_hServerObject;

        LTFLOAT fVel = m_fSizeAdjust * GetRandom(50.0f, 70.0f);
		fVel = (fVel < 30.0f ? 30.0f : (fVel > 100.0f ? 100.0f : fVel));

        LTVector vDir(0.0, 1.0, 0.0);
		sparks.vMinVelAdjust.Init(1, 3, 1);
		sparks.vMaxVelAdjust.Init(1, 6, 1);
		sparks.vDir	= vDir * fVel;
		sparks.nSparks = GetRandom(1, 5);
		sparks.fDuration = m_fSizeAdjust * GetRandom(1.0f, 2.0f);
        sparks.bRelToCameraPos = LTTRUE;
		sparks.fInnerCamRadius = FFX_INNER_CAM_RADIUS;
		sparks.fOuterCamRadius = FFX_INNER_CAM_RADIUS + (FFX_CAM_FALLOFF_RANGE * m_fSizeAdjust);
		sparks.fRadius = 300.0f * m_fSizeAdjust;
		sparks.fRadius = sparks.fRadius < 100.0f ? 100.0f : (sparks.fRadius > 500.0f ? 500.0f : sparks.fRadius);

		psfxMgr->CreateSFX(SFX_RANDOMSPARKS_ID, &sparks);
	}

    return LTTRUE;
}
Example #12
0
bool CAIWeaponAbstract::DefaultThrow(CAI* pAI)
{
	// Make sure the basic pointers are valid.
	ASSERT(m_pWeapon);
	ASSERT(pAI);
	if (!pAI || !m_pWeapon || !m_pAIWeaponRecord)
	{
		return false;
	}

	// Don't fire if AI has no target.

	if( !pAI->HasTarget( kTarget_Character | kTarget_Object ) )
	{
		return false;
	}

	HOBJECT hTarget = pAI->GetAIBlackBoard()->GetBBTargetObject();

	// Throw at the last known position.

	LTVector vTargetPos;
	CAIWMFact factTargetQuery;
	factTargetQuery.SetFactType( kFact_Character );
	factTargetQuery.SetTargetObject( hTarget );
	CAIWMFact* pFact = pAI->GetAIWorkingMemory()->FindWMFact( factTargetQuery );
	if( pFact )
	{
		vTargetPos = pFact->GetPos();
	}
	else {
		g_pLTServer->GetObjectPos(hTarget, &vTargetPos);
	}


	// Offset the target pos a little so projectile lands in front of the target.

	LTVector vOffsetDir;
	vOffsetDir = pAI->GetPosition() - vTargetPos;
	vOffsetDir.y = 0.f;
	vOffsetDir.Normalize();
	vTargetPos += vOffsetDir * 384.f; 

	// Get our fire position

	LTVector vFirePos = GetFirePosition(pAI);

	// Velocity Vo

	LTVector vGravity;
	g_pPhysicsLT->GetGlobalForce( vGravity );

	// Vo = (S - R - 1/2*G*t^2) / t         
	// Vo = initial velocity
	// S = destination
	// R = origin
	// G = gravity
	// t = hangtime

	float fHangtime = 0.5f;
	LTVector vVelocity = ( vTargetPos - vFirePos - vGravity * .5f * fHangtime * fHangtime ) / fHangtime;
	float fVelocity = vVelocity.Mag();
	LTVector vDir( vVelocity / fVelocity );

	// Now fire the weapon

	WeaponFireInfo weaponFireInfo;
	static uint8 s_nCount = GetRandom( 0, 255 );
	s_nCount++;

	weaponFireInfo.hFiredFrom = pAI->GetHOBJECT();
	weaponFireInfo.vPath = vDir;
	weaponFireInfo.bOverrideVelocity = LTTRUE;
	weaponFireInfo.fOverrideVelocity = fVelocity;
	weaponFireInfo.vFirePos	= vFirePos;
	weaponFireInfo.vFlashPos = vFirePos;
	weaponFireInfo.hTestObj	= hTarget;
	weaponFireInfo.fPerturb = 1.0f * (1.0f - pAI->GetAccuracy() );
	weaponFireInfo.nSeed = (uint8)GetRandom( 2, 255 );
	weaponFireInfo.nPerturbCount = s_nCount;
	weaponFireInfo.nFireTimestamp = g_pLTServer->GetRealTimeMS( );

	m_pWeapon->ReloadClip( LTFALSE );

	if (m_pAIWeaponRecord->bAllowAmmoGeneration)
	{
		m_pWeapon->GetArsenal()->AddAmmo( m_pWeapon->GetAmmoRecord(), 999999 );
	}

	m_pWeapon->UpdateWeapon( weaponFireInfo, LTTRUE );

	return true;
}
Example #13
0
/*
 * Agrega todos los directorios y imagenes al arbol imgTree
 * Agrega agrega todas las imagenes al imgFile
 */
tVecStr ImageManager::AddDirectory(const char* dirPath)
{
	tVecStr ans;
	tVecStr fileList=FileSystem::GetFiles(dirPath,All);
	
	if(fileList.size()==0)
		throw eNotExist(EMPTY);

	string strdir(dirPath);
	StrToken::FormatPath(strdir);
	string dirPathStr = strdir;

	KeyStr kDirDir(strdir);

	//Si el directorio existe no lo agrego.
	if (!dirTree.empty())
		if (dirTree.exists(kDirDir))
			throw eNotExist(WRONG_MSG_ADD_DIRECTORY);


	ans.push_back(strdir);
	strdir=strdir+END_DIRECTORY;
	KeyStr kDir(strdir);
	ValueInt vDir(0);
	ValueNull vNull;
	dirTree.insert(kDirDir,vNull);
	imgTree.insert(kDir,vDir);
	std::cout << std::endl;

	for(size_t i=0; i<fileList.size();i++)
	{
		string fullPath= dirPathStr + fileList[i];
		std::cout << ADDING_FILE << fullPath << std::endl;
		AddImage(fullPath.c_str());
	}

	tVecStr dirList=FileSystem::GetFiles(dirPath,Dir);

	for(size_t j=0; j<dirList.size();j++)
	{
		string strDir= dirPathStr + dirList[j];
		string strNewSubDir = strDir;
		strDir= strDir+"/";
		KeyStr kSubDirTreeDir(strDir);
		strDir= strDir+END_DIRECTORY;

		KeyStr kSubDir(strDir);
		ValueInt vSubDir(0);
		if(!imgTree.exists(kSubDir))
		{
			imgTree.insert(kSubDir,vSubDir);
		}
		if(!dirTree.exists(kSubDirTreeDir))
		{
			ans.push_back(strNewSubDir);
			ValueNull vNull;
			dirTree.insert(kSubDirTreeDir,vNull);
		}
	}
	return ans;
}
Example #14
0
void C_Hairball::ClientThink()
{
	// Do some AI-type stuff.. move the entity around.
	//C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
	//m_vecAngles = SetAbsAngles( pPlayer->GetAbsAngles() ); // copy player angles.

	Assert( !GetMoveParent() );

	// Sophisticated AI.
	m_flCurSpinTime += gpGlobals->frametime;
	if ( m_flCurSpinTime < m_flSpinDuration )
	{
		float div = m_flCurSpinTime / m_flSpinDuration;

		QAngle angles = GetLocalAngles();

		angles.x += m_flSpinRateX * SmoothCurve( div );
		angles.y += m_flSpinRateY * SmoothCurve( div );

		SetLocalAngles( angles );
	}
	else
	{
		// Flip between stopped and starting.
		if ( fabs( m_flSpinRateX ) > 0.01f )
		{
			m_flSpinRateX = m_flSpinRateY = 0;

			m_flSpinDuration = RandomFloat( 1, 2 );
		}
		else
		{
			static float flXSpeed = 3;
			static float flYSpeed = flXSpeed * 0.1f;
			m_flSpinRateX = RandomFloat( -M_PI*flXSpeed, M_PI*flXSpeed );
			m_flSpinRateY = RandomFloat( -M_PI*flYSpeed, M_PI*flYSpeed );

			m_flSpinDuration = RandomFloat( 1, 4 );
		}

		m_flCurSpinTime = 0;
	}

	
	if ( m_flSitStillTime > 0 )
	{
		m_flSitStillTime -= gpGlobals->frametime;

		if ( m_flSitStillTime <= 0 )
		{
			// Shoot out some random lines and find the longest one.
			m_vMoveDir.Init( 1, 0, 0 );
			float flLongestFraction = 0;
			for ( int i=0; i < 15; i++ )
			{
				Vector vDir( RandomFloat( -1, 1 ), RandomFloat( -1, 1 ), RandomFloat( -1, 1 ) );
				VectorNormalize( vDir );

				trace_t trace;
				UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() + vDir * 10000, MASK_SOLID, NULL, COLLISION_GROUP_NONE, &trace );

				if ( trace.fraction != 1.0 )
				{
					if ( trace.fraction > flLongestFraction )
					{
						flLongestFraction = trace.fraction;
						m_vMoveDir = vDir;
					}
				}
			}

			m_vMoveDir *= 650; // set speed.
			m_flSitStillTime = -1; // Move in this direction..
		}
	}
	else
	{
		// Move in the specified direction.
		Vector vEnd = GetAbsOrigin() + m_vMoveDir * gpGlobals->frametime;

		trace_t trace;
		UTIL_TraceLine( GetAbsOrigin(), vEnd, MASK_SOLID, NULL, COLLISION_GROUP_NONE, &trace );

		if ( trace.fraction < 1 )
		{
			// Ok, stop moving.
			m_flSitStillTime = RandomFloat( 1, 3 );
		}
		else
		{
			SetLocalOrigin( GetLocalOrigin() + m_vMoveDir * gpGlobals->frametime );
		}
	}

	
	// Transform the base hair positions so we can lock them down.
	VMatrix mTransform;
	mTransform.SetupMatrixOrgAngles( GetLocalOrigin(), GetLocalAngles() );

	for ( int i=0; i < m_HairPositions.Count(); i++ )
	{
		Vector3DMultiplyPosition( mTransform, m_HairPositions[i], m_TransformedHairPositions[i] );
	}

	if ( m_bFirstThink )
	{
		m_bFirstThink = false;
		for ( int i=0; i < m_HairPositions.Count(); i++ )
		{
			for ( int j=0; j < m_nNodesPerHair; j++ )
			{
				m_Nodes[i*m_nNodesPerHair+j].Init( m_TransformedHairPositions[i] );
			}
		}
	}

	// Simulate the physics and apply constraints.
	m_Physics.Simulate( m_Nodes.Base(), m_Nodes.Count(), &m_Delegate, gpGlobals->frametime, 0.98 );
}
Example #15
0
BabylonLight::BabylonLight(BabylonNode & babnode) :
	diffuse(1, 1, 1),
	specular(1, 1, 1)
{
	auto node = babnode.fbxNode();
	std::string ansiName = node->GetName();
	name = std::wstring(ansiName.begin(), ansiName.end());
	id = getNodeId(node);
	auto parent = node->GetParent();
	if (parent) {
		parentId = getNodeId(parent);
	}
	auto localTransform = babnode.GetLocal();
	position = localTransform.translation();
	auto light = node->GetLight();
	switch (light->LightType)
	{
	case FbxLight::ePoint:
		type = type_omni;
		break;
	case FbxLight::eDirectional:
		type = type_direct;
		{
			FbxDouble3 vDir(0, -1, 0);
			FbxAMatrix rotM;
			rotM.SetIdentity();

			rotM.SetQ(localTransform.fbxrot());
			auto transDir = rotM.MultT(vDir);
			direction = transDir;

		}
		break;
	case FbxLight::eSpot:
		type = type_Spot;
		{
			FbxDouble3 vDir(0, -1, 0);
			FbxAMatrix rotM;
			rotM.SetIdentity();
			rotM.SetQ(localTransform.fbxrot());
			auto transDir = rotM.MultT(vDir);
			direction = transDir;
			exponent = 1;
			angle = static_cast<float>(light->OuterAngle*Euler2Rad);

		}
		break;
	default:
		break;
	}
	diffuse = light->Color.Get();
	intensity = static_cast<float>(light->Intensity.Get() / 100.0);
	if (light->EnableFarAttenuation.Get()) {
		range = static_cast<float>(light->FarAttenuationEnd.Get());
	}
	auto hasAnimStack = node->GetScene()->GetSrcObjectCount<FbxAnimStack>() > 0;
	if (!hasAnimStack) {
		return;
	}
	castShadows = light->CastShadows.Get();
	if (castShadows) {
		shadowGenerator = std::make_shared<BabylonShadowGenerator>(node);
	}
	auto animStack = node->GetScene()->GetSrcObject<FbxAnimStack>(0);
	FbxString animStackName = animStack->GetName();
	FbxTakeInfo* takeInfo = node->GetScene()->GetTakeInfo(animStackName);
	auto animTimeMode = GlobalSettings::Current().AnimationsTimeMode;
	auto animFrameRate = GlobalSettings::Current().AnimationsFrameRate();
	auto startFrame = takeInfo->mLocalTimeSpan.GetStart().GetFrameCount(animTimeMode);
	auto endFrame = takeInfo->mLocalTimeSpan.GetStop().GetFrameCount(animTimeMode);
	auto animLengthInFrame = endFrame - startFrame + 1;
	auto posAnimName = getNodeId(node);
	auto dirAnimName = getNodeId(node);
	posAnimName.append(L"_position");
	dirAnimName.append(L"_direction");
	auto posAnim = std::make_shared<BabylonAnimation<babylon_vector3>>(BabylonAnimationBase::loopBehavior_Cycle, static_cast<int>(animFrameRate), posAnimName, L"position", true, 0, static_cast<int>(animLengthInFrame), true);
	auto dirAnim = std::make_shared<BabylonAnimation<babylon_vector3>>(BabylonAnimationBase::loopBehavior_Cycle, static_cast<int>(animFrameRate), dirAnimName, L"direction", true, 0, static_cast<int>(animLengthInFrame), true);
	if (node->LclRotation.GetCurveNode() || node->LclTranslation.GetCurveNode()) {
		for (auto ix = 0; ix < animLengthInFrame; ix++) {
			babylon_animation_key<babylon_vector3> key;
			key.frame = ix;
			FbxTime currTime;
			currTime.SetFrame(startFrame + ix, animTimeMode);
			auto currTransform = babnode.GetLocal(currTime);
			key.values = currTransform.translation();
			posAnim->appendKey(key);

			if (type == type_direct || type == type_Spot) {
				babylon_animation_key<babylon_vector3> dirkey;
				dirkey.frame = ix;
				FbxDouble3 vDir(0, -1, 0);
				FbxAMatrix rotM;
				rotM.SetIdentity();
				rotM.SetQ(currTransform.fbxrot());
				auto transDir = rotM.MultT(vDir);
				dirkey.values = transDir;
				dirAnim->appendKey(dirkey);
			}
		}
	}
	if (!posAnim->isConstant()) {
		animations.push_back(posAnim);
	}
	if (!dirAnim->isConstant()) {
		animations.push_back(dirAnim);
	}
}
Example #16
0
//====================================================================
// DebugDrawRangePolygon
//====================================================================
void CAIDebugRenderer::DrawRangePolygon(const Vec3 polygon[], int nVertices, float fWidth,
													 const ColorB& colorFill, const ColorB& colorOutline, bool bDrawOutline)
{
	static std::vector<Vec3>		verts;
	static std::vector<vtx_idx>	tris;
	static std::vector<Vec3>		outline;

	if (nVertices < 3) return;

	Vec3	prevDir(polygon[0] - polygon[nVertices - 1]);
	prevDir.NormalizeSafe();
	Vec3	prevNorm(-prevDir.y, prevDir.x, 0.0f);
	prevNorm.NormalizeSafe();
	Vec3	prevPos(polygon[nVertices - 1]);

	verts.clear();
	outline.clear();

	const Vec3* li, * linext;
	const Vec3* liend = polygon + nVertices;
	for (li = polygon; li != liend ; ++li)
	{
		linext = li;
		++linext;
		if (linext == liend)
			linext = polygon;

		const Vec3&	curPos(*li);
		const Vec3&	nextPos(*linext);
		Vec3	vDir(nextPos - curPos);
		Vec3	norm(-vDir.y, vDir.x, 0.0f);
		norm.NormalizeSafe();

		Vec3	mid((prevNorm + norm) * 0.5f);
		float	dmr2 = sqr(mid.x) + sqr(mid.y);
		if (dmr2 > 0.00001f)
			mid *= 1.0f / dmr2;

		float	cross = prevDir.x * vDir.y - vDir.x * prevDir.y;

		outline.push_back(curPos);

		if (cross < 0.0f)
		{
			if (dmr2 * sqr(2.5f) < 1.0f)
			{
				// bevel
				verts.push_back(curPos);
				verts.push_back(curPos + prevNorm * fWidth);
				verts.push_back(curPos);
				verts.push_back(curPos + norm * fWidth);
			}
			else
			{
				verts.push_back(curPos);
				verts.push_back(curPos + mid * fWidth);
			}
		}
		else
		{
			verts.push_back(curPos);
			verts.push_back(curPos + mid * fWidth);
		}

		prevDir = vDir;
		prevNorm = norm;
		prevPos = curPos;
	}

	tris.clear();
	size_t	n = verts.size()/2;
	for (size_t i = 0; i < n; ++i)
	{
		size_t	j = (i + 1) % n;
		tris.push_back(i*2);
		tris.push_back(j*2);
		tris.push_back(j*2+1);

		tris.push_back(i*2);
		tris.push_back(j*2+1);
		tris.push_back(i*2+1);
	}

	m_pRenderer->GetIRenderAuxGeom()->DrawTriangles(&verts[0], verts.size(), &tris[0], tris.size(), colorFill);
	if (bDrawOutline)
		DrawPolyline(&outline[0], outline.size(), true, colorOutline);
}
Example #17
0
EntryPointInSim* OnboardSeatInSim::GetIntersectionNodeWithSeatGroupPolygon()
{
	if (m_pSeatGroupInSim == NULL)
		return NULL;
	const CPollygon2008& polygon = m_pSeatGroupInSim->GetPolygon();

	EntryPointInSim* pEntryPointInSim = NULL;
	ARCVector3 entryPt;
	GetFrontPosition(entryPt);
	CPoint2008 seatPt(entryPt.n[VX],entryPt.n[VY],0.0);
	CPoint2008 locationPt;
	GetLocation(locationPt);
	locationPt.setZ(0.0);
	
	CPoint2008 vDir(locationPt,seatPt);
	vDir.Normalize();
	
	CPoint2008 cellPt(GRID_WIDTH,GRID_HEIGHT,0.0);
	double dDist = PAXRADIUS/2 + GRID_WIDTH;//cellPt.length()*0.5 + 20;//offset make be able to next cell
	//rotate 90
	double dRayLeft = (std::numeric_limits<double>::max)();
	CPoint2008 ptRayLeft;
	CPoint2008 vDirLeft(vDir);
	vDirLeft.rotate(90.0);
	vDirLeft.Normalize();
	CRayIntersectPath2D rayPathLeft(seatPt,vDirLeft,polygon);
	if (rayPathLeft.Get())
	{
		ptRayLeft = polygon.GetIndexPoint((float)rayPathLeft.m_Out.begin()->m_indexInpath);
		CPoint2008 rayDirLeft(seatPt,ptRayLeft);
		rayDirLeft.Normalize();
		OnboardCellInSim* pLeftCellInSim = GetGround()->getCell(ptRayLeft);
		CPoint2008 leftCellPt = pLeftCellInSim->getLocation();
		leftCellPt += rayDirLeft * dDist;
		OnboardCellInSim* pLeftEntryCellInSim = GetGround()->GetPointCell(leftCellPt);
		if (pLeftEntryCellInSim)
		{
			pLeftEntryCellInSim->SetState(OnboardCellInSim::Idle);
			GetGround()->getLogicMap().setTileAsBarrier(pLeftEntryCellInSim->getTileIndex(), false);
			dRayLeft = rayPathLeft.m_Out.front().m_dist;
			pEntryPointInSim = new EntryPointInSim(pLeftEntryCellInSim,m_pFlightInSim);
			pEntryPointInSim->SetWalkType(EntryPointInSim::TurnDirection_Walk);
			pEntryPointInSim->SetCreateSeat(this);
		}
	}
	//rotate -90
	double dRayRight = (std::numeric_limits<double>::max)();
	CPoint2008 ptRayRight;
	CPoint2008 vDirRight(vDir);
	vDirRight.rotate(-90.0);
	vDirRight.Normalize();
	CRayIntersectPath2D rayPathRight(seatPt,vDirRight,polygon);
	if (rayPathRight.Get())
	{
		ptRayRight = polygon.GetIndexPoint((float)rayPathRight.m_Out.begin()->m_indexInpath);
		OnboardCellInSim* pRightCellInSim = GetGround()->getCell(ptRayRight);
		CPoint2008 rayDirRight(seatPt,ptRayRight);
		rayDirRight.Normalize();
		CPoint2008 rightCellPt = pRightCellInSim->getLocation();
		rightCellPt += rayDirRight * dDist;
		OnboardCellInSim* pRightEntryCellInSim = GetGround()->GetPointCell(rightCellPt);

		if (pRightEntryCellInSim)
		{
			pRightEntryCellInSim->SetState(OnboardCellInSim::Idle);
			GetGround()->getLogicMap().setTileAsBarrier(pRightEntryCellInSim->getTileIndex(), false);
			dRayRight = rayPathRight.m_Out.front().m_dist;
			if (dRayRight < dRayLeft)
			{
				if (pEntryPointInSim)
				{
					delete pEntryPointInSim;
					pEntryPointInSim = NULL;
				}
				pEntryPointInSim = new EntryPointInSim(pRightEntryCellInSim,m_pFlightInSim);
				pEntryPointInSim->SetWalkType(EntryPointInSim::TurnDirection_Walk);
				pEntryPointInSim->SetCreateSeat(this);
			}
		}
		
	}

	return pEntryPointInSim;
}
Example #18
0
void CGameEng::Tick(const D3DCOLOR* crDiffuses,			// Diffuse 라이트 색깔.. 3 개 쓴다.
					const D3DCOLOR* crAmbients,			// Ambient 라이트 색깔.. 3 개 쓴다.
					const D3DCOLOR crFog,				// 안개 색깔..
					const __Vector3& vPosPlayer,		// 플레이어 위치
					const __Quaternion& qtPlayer,		// 회전 쿼터니언
					float fHeightPlayer,				// 키를 인수로 넣으면 카메라와 라이트 처리..
					float fSunRadianZ)					// 해의 Z 각도..
{
	if(NULL == m_pActiveCam) return;

	float fRadius = fHeightPlayer * 2.0f;
	float fYaw = 0;
	__Quaternion qtRot = qtPlayer;
	__Vector3 vAxis(0,1,0);
	qtRot.AxisAngle(vAxis, fYaw);
	
	if(vAxis.y < 0) // 회전축이 음수이면.
	{
		vAxis.y *= -1.0f;
		fYaw *= -1.0f;
	}

	switch(m_eViewPoint)
	{
		case VP_BACKWARD:
		{
			::D3DXQuaternionRotationYawPitchRoll(&qtRot, fYaw, m_fRotPitchBackward, 0);
			__Matrix44 mtxRot = qtRot;

			m_vEyeToReach.Set(0, 0, -(fRadius / s_CameraData.fFOV) * m_fZoomBackwardOrFoward);
			m_vAtToReach = vPosPlayer; m_vAtToReach.y += fHeightPlayer * 0.8f;
			m_vEyeToReach = m_vAtToReach + (m_vEyeToReach * mtxRot);
		}
		break;
		case VP_FIRST_PERSON:
		{
			::D3DXQuaternionRotationYawPitchRoll(&qtRot, fYaw, m_fRotPitchFirstPerson, 0);
			__Matrix44 mtxRot = qtRot;

			m_vEyeToReach = vPosPlayer; m_vEyeToReach.y += fHeightPlayer - 0.1f;
			m_vAtToReach.Set(0,0,1);
			m_vAtToReach = m_vEyeToReach + (m_vAtToReach * mtxRot);
		}
		break;
		case VP_FOWARD:
		{
			::D3DXQuaternionRotationYawPitchRoll(&qtRot, fYaw, -m_fRotPitchFoward, 0);
			__Matrix44 mtxRot = qtRot;

			m_vEyeToReach.Set(0, 0, fRadius * m_fZoomBackwardOrFoward);
			m_vAtToReach = vPosPlayer; m_vAtToReach.y += fHeightPlayer * 0.8f;
			m_vEyeToReach = m_vAtToReach + (m_vEyeToReach * mtxRot);
		}
		break;
		case VP_THIRD_PERSON:
		{
			::D3DXQuaternionRotationYawPitchRoll(&qtRot, m_fRotYawVPGod, m_fRotPitchThirdFirson, 0);
			__Matrix44 mtxRot = qtRot;

			m_vAtToReach = vPosPlayer; m_vAtToReach.y += fHeightPlayer * 0.8f;
			m_vEyeToReach.Set(0,0,-m_fOffsetVPGod);
			m_vEyeToReach = m_vAtToReach + (m_vEyeToReach * mtxRot);
		}
		break;
	}

	////////////////////////////////////////////////////////////////////////////////////
	// 카메라 충돌 체크...
	if(VP_FIRST_PERSON == m_eViewPoint) // 일인칭때는 충돌체크 안한다.
	{
		m_pActiveCam->LookAt(m_vEyeToReach, m_vAtToReach, __Vector3(0,1,0)); // 처다본다..
	}
	else
	{
		__Vector3 vEyeResult = m_vEyeToReach;
		float fNP = m_pActiveCam->m_Data.fNP;
		CGameBase::ACT_WORLD->CheckCollisionCameraWithTerrain(vEyeResult, m_vAtToReach, fNP); // 지형과 충돌체크
		CGameBase::ACT_WORLD->CheckCollisionCameraWithShape(vEyeResult, m_vAtToReach, fNP); // 오브젝트와 충돌체크..
		m_pActiveCam->LookAt(vEyeResult, m_vAtToReach, __Vector3(0,1,0)); // 처다본다..
	}
	// 카메라 충돌 체크...
	////////////////////////////////////////////////////////////////////////////////////


	// 파 플레인 값을 조정..
	// ApplyCameraAndLight 에서 실제로 안개등의 값을 조절한다.
	if(m_fFPDeltaCur != m_fFPDeltaToReach)
	{
		float fFPChange = (m_fFPDeltaToReach - m_fFPDeltaCur) * s_fSecPerFrm / 5.0f; // 5초동안 변하게 한다.
		m_fFPDeltaCur += fFPChange;

		if(fFPChange < 0 && m_fFPDeltaCur < m_fFPDeltaToReach) m_fFPDeltaCur = m_fFPDeltaToReach;
		if(fFPChange > 0 && m_fFPDeltaCur > m_fFPDeltaToReach) m_fFPDeltaCur = m_fFPDeltaToReach;
	}
	float fFPToRestore = m_pActiveCam->m_Data.fFP;
	m_pActiveCam->m_Data.fFP = s_Options.iViewDist * m_fFPDeltaCur;
	
	m_pActiveCam->m_FogColor = crFog; // 안개색을 맞춘다..
	m_pActiveCam->Tick(); // 적용및 사면체등등의 값들을 계산..

	__Matrix44 mtxRotSun;
	mtxRotSun.RotationZ(fSunRadianZ); // 해의 각도에 맞춘다..

	/*
	it_Light itLgt = m_Lights.begin();
	int iSize = m_Lights.size();
	for(int i = 0; i < iSize; i++, itLgt++)
	{
		CN3Light* pLight = *itLgt;
		__ASSERT(pLight, "Light pointer is NULL!!!");
		
		if(0 == pLight->m_Data.nNumber) // 기본 디렉셔널 라이트
		{
			// View Matrix 각도와 방향을 맞춘다..
//			__Vector3 vDir(0.0f,-1.5f,1.0f);
//			vDir.Normalize();
//			__Matrix44 mtxVI = s_CameraData.mtxViewInverse;
//			mtxVI.PosSet(0,0,0);
//			pLight->m_Data.Direction = vDir * mtxVI;

			// 해와 방향을 맞춘다..
			__Matrix44 mtxRot; mtxRot.RotationZ(fSunRadianZ);
			__Vector3 vDir(-1,0,1);
			vDir *= mtxRot;
			vDir.Normalize();
			pLight->m_Data.Direction = vDir;
			
			// 라이트 컬러 적용..
			pLight->m_Data.Diffuse = ::_D3DCOLOR_To_D3DCOLORVALUE(crDiffuses[0]);
			pLight->m_Data.Ambient = ::_D3DCOLOR_To_D3DCOLORVALUE(crAmbients[0]);
		}
		else if(1 == pLight->m_Data.nNumber)
		{
			__Vector3 vDir(2,-3, 2); // 위에서 아래로 ...
			vDir.Normalize();
			pLight->m_Data.Direction = vDir;
			
			// 라이트 컬러 적용..
			pLight->m_Data.Diffuse = ::_D3DCOLOR_To_D3DCOLORVALUE(crDiffuses[1]);
			pLight->m_Data.Ambient = ::_D3DCOLOR_To_D3DCOLORVALUE(crAmbients[1]);
		}
		else if(2 == pLight->m_Data.nNumber)
		{
			__Vector3 vPos = s_CameraData.vEye;
			vPos.y += 16.0f;
			pLight->PosSet(vPos); // 카메라 위에 가게 한다..
			
			// 라이트 컬러 적용..
			pLight->m_Data.Diffuse = ::_D3DCOLOR_To_D3DCOLORVALUE(crDiffuses[2]);
			pLight->m_Data.Ambient = ::_D3DCOLOR_To_D3DCOLORVALUE(crAmbients[2]);
		}


		// 번개 처리..
		if(m_fLightningTimeRemain > 0)
		{
			float fLightningDelta = 0;

			if(m_fLightningTimeRemain > LIGHTNING_DURATION * 0.8f)
				fLightningDelta = (m_fLightningTimeRemain - LIGHTNING_DURATION * 0.8f) / (LIGHTNING_DURATION * 0.2f);
			else
				fLightningDelta = m_fLightningTimeRemain / (LIGHTNING_DURATION * 0.8f);

			pLight->m_Data.Diffuse.r += (1.0f - pLight->m_Data.Diffuse.r) * fLightningDelta * 0.4f;
			pLight->m_Data.Diffuse.g += (1.0f - pLight->m_Data.Diffuse.g) * fLightningDelta * 0.5f;
			pLight->m_Data.Diffuse.b += (1.0f - pLight->m_Data.Diffuse.b) * fLightningDelta;

			m_fLightningTimeRemain -= CN3Base::s_fSecPerFrm;
			if(m_fLightningTimeRemain < 0) m_fLightningTimeRemain = 0;
		}

		pLight->Tick();
	}
	*/
	if(m_pRefLightSun)
	{
		// 해와 방향을 맞춘다..
		__Matrix44 mtxRot; mtxRot.RotationZ(fSunRadianZ);
		__Vector3 vDir(-1,0,1);
		vDir *= mtxRot;
		vDir.Normalize();
		m_pRefLightSun->m_Data.Direction = vDir;
		
		// 라이트 컬러 적용..
		m_pRefLightSun->m_Data.Diffuse = ::_D3DCOLOR_To_D3DCOLORVALUE(crDiffuses[0]);
		m_pRefLightSun->m_Data.Ambient = ::_D3DCOLOR_To_D3DCOLORVALUE(crAmbients[0]);

		// 번개 처리..
		if(m_fLightningTimeRemain > 0)
		{
			float fLightningDelta = 0;

			if(m_fLightningTimeRemain > LIGHTNING_DURATION * 0.8f)
				fLightningDelta = (m_fLightningTimeRemain - LIGHTNING_DURATION * 0.8f) / (LIGHTNING_DURATION * 0.2f);
			else
				fLightningDelta = m_fLightningTimeRemain / (LIGHTNING_DURATION * 0.8f);

			m_pRefLightSun->m_Data.Diffuse.r += (1.0f - m_pRefLightSun->m_Data.Diffuse.r) * fLightningDelta * 0.4f;
			m_pRefLightSun->m_Data.Diffuse.g += (1.0f - m_pRefLightSun->m_Data.Diffuse.g) * fLightningDelta * 0.5f;
			m_pRefLightSun->m_Data.Diffuse.b += (1.0f - m_pRefLightSun->m_Data.Diffuse.b) * fLightningDelta;

			m_fLightningTimeRemain -= CN3Base::s_fSecPerFrm;
			if(m_fLightningTimeRemain < 0) m_fLightningTimeRemain = 0;
		}
	}
	if(m_pRefLightSupport)
	{
		__Vector3 vDir(2,-3, 2); // 위에서 아래로 ...
		vDir.Normalize();
		m_pRefLightSupport->m_Data.Direction = vDir;
		
		// 라이트 컬러 적용..
		m_pRefLightSupport->m_Data.Diffuse = ::_D3DCOLOR_To_D3DCOLORVALUE(crDiffuses[1]);
		m_pRefLightSupport->m_Data.Ambient = ::_D3DCOLOR_To_D3DCOLORVALUE(crAmbients[1]);

		// 번개 처리..
		if(m_fLightningTimeRemain > 0)
		{
			float fLightningDelta = 0;

			if(m_fLightningTimeRemain > LIGHTNING_DURATION * 0.8f)
				fLightningDelta = (m_fLightningTimeRemain - LIGHTNING_DURATION * 0.8f) / (LIGHTNING_DURATION * 0.2f);
			else
				fLightningDelta = m_fLightningTimeRemain / (LIGHTNING_DURATION * 0.8f);

			m_pRefLightSupport->m_Data.Diffuse.r += (1.0f - m_pRefLightSupport->m_Data.Diffuse.r) * fLightningDelta * 0.4f;
			m_pRefLightSupport->m_Data.Diffuse.g += (1.0f - m_pRefLightSupport->m_Data.Diffuse.g) * fLightningDelta * 0.5f;
			m_pRefLightSupport->m_Data.Diffuse.b += (1.0f - m_pRefLightSupport->m_Data.Diffuse.b) * fLightningDelta;

			m_fLightningTimeRemain -= CN3Base::s_fSecPerFrm;
			if(m_fLightningTimeRemain < 0) m_fLightningTimeRemain = 0;
		}
	}
	if(m_pRefLightCam)
	{
		__Vector3 vPos = s_CameraData.vEye;
		vPos.y += 16.0f;
		m_pRefLightCam->PosSet(vPos); // 카메라 위에 가게 한다..
		
		// 라이트 컬러 적용..
		m_pRefLightCam->m_Data.Diffuse = ::_D3DCOLOR_To_D3DCOLORVALUE(crDiffuses[2]);
		m_pRefLightCam->m_Data.Ambient = ::_D3DCOLOR_To_D3DCOLORVALUE(crAmbients[2]);

		// 번개 처리..
		if(m_fLightningTimeRemain > 0)
		{
			float fLightningDelta = 0;

			if(m_fLightningTimeRemain > LIGHTNING_DURATION * 0.8f)
				fLightningDelta = (m_fLightningTimeRemain - LIGHTNING_DURATION * 0.8f) / (LIGHTNING_DURATION * 0.2f);
			else
				fLightningDelta = m_fLightningTimeRemain / (LIGHTNING_DURATION * 0.8f);

			m_pRefLightCam->m_Data.Diffuse.r += (1.0f - m_pRefLightCam->m_Data.Diffuse.r) * fLightningDelta * 0.4f;
			m_pRefLightCam->m_Data.Diffuse.g += (1.0f - m_pRefLightCam->m_Data.Diffuse.g) * fLightningDelta * 0.5f;
			m_pRefLightCam->m_Data.Diffuse.b += (1.0f - m_pRefLightCam->m_Data.Diffuse.b) * fLightningDelta;

			m_fLightningTimeRemain -= CN3Base::s_fSecPerFrm;
			if(m_fLightningTimeRemain < 0) m_fLightningTimeRemain = 0;
		}
	}
}
Example #19
0
bool CPlayerMySelf::CheckCollision()
{
	float fSpeed = m_fMoveSpeedPerSec * CN3Base::s_fSecPerFrm; // 현재 움직이는 속도..프레임에 따라 계산되어 나오는 속도이다. 
	if(0 == fSpeed) return false; // 움직이지 않으면 충돌체크 하지 않는다.

	__Vector3 vPos = this->Position();

	__Vector3 vDir(0,0,1); // 회전값을 구하고..
	__Matrix44 mtxRot = this->Rotation(); 
	vDir *= mtxRot; // 회전에 따른 방향을 구하고.
	if(fSpeed < 0)
	{
		fSpeed *= -1.0f;
		vDir *= -1.0f;
	}
	__Vector3 vPosNext = vPos + (vDir * fSpeed); // 다음 위치 계산..
	if ( false == ACT_WORLD->IsInTerrainWithTerrain(vPosNext.x, vPosNext.z, vPos) )
		return true; // 경계 안에 있지 않으면..


	//////////////////////////////////
	// 다른 플레이어와 체크..
	CPlayerOther* pUPC = NULL;
	float fHeightSum, fMag;
	it_UPC it = s_pOPMgr->m_UPCs.begin(), itEnd = s_pOPMgr->m_UPCs.end();
	for(; it != itEnd; it++)
	{
		pUPC = it->second;

		if(pUPC->IsDead()) continue; //죽어 있는 상태의 캐릭터는 충돌체크를 하지 않는다.
		if(m_InfoBase.eNation == pUPC->m_InfoBase.eNation) continue; // 같은 국가...

		//-------------------------------------------------------------------------
		/*
		// TODO(srmeier): need to use ZoneAbilityType here
		// NOTE(srmeier): using zoneability information to determine if target is colliable
		if (!ACT_WORLD->canAttackSameNation() && (pUPC->m_InfoBase.eNation == m_InfoBase.eNation))
			continue;
		if (!ACT_WORLD->canAttackOtherNation() && (m_InfoBase.eNation == NATION_ELMORAD && pUPC->m_InfoBase.eNation == NATION_KARUS))
			continue;
		if (!ACT_WORLD->canAttackOtherNation() && (m_InfoBase.eNation == NATION_KARUS && pUPC->m_InfoBase.eNation == NATION_ELMORAD))
			continue;
		*/
		//-------------------------------------------------------------------------
		
		fMag = (pUPC->Position() - vPos).Magnitude();
		if(fMag < 32.0f)
		{
			fHeightSum = (pUPC->Height() + m_Chr.Height()) / 2.5f;
			if(fMag < fHeightSum) // 거리가 키의 합보다 작으면..
			{
				float fMag2 = (pUPC->Position() - vPosNext).Magnitude(); // 다음위치가 더 가까우면.
				if(fMag2 < fMag)
					return true;
			}
		}
	}
	// 다른 플레이어와 체크..
	//////////////////////////////////

//	__TABLE_ZONE* pZoneInfo = s_pTbl_Zones->Find(m_InfoExt.iZoneCur);
//	if(pZoneInfo && pZoneInfo->bNPCCollisionCheck) //this_zone

	//적국 엔피씨는 충돌 체크를 한다.
	CPlayerNPC* pNPC = NULL;
	it_NPC it_N = s_pOPMgr->m_NPCs.begin(),	it_NEnd	= s_pOPMgr->m_NPCs.end();
	for(; it_N != it_NEnd; it_N++)
	{
		pNPC = it_N->second;

		if(pNPC->m_pShapeExtraRef) continue; // 성문등의 형태이면 충돌체크를 하지 않는다..

		if(m_InfoBase.eNation == pNPC->m_InfoBase.eNation) continue; // 같은 국가...
		// NOTE(srmeier): I believe these are for passing through monsters and such
		if(m_InfoBase.eNation == NATION_KARUS && pNPC->m_InfoBase.eNation != NATION_ELMORAD) continue; // 적국 엔피씨는 충돌 체크를 한다.
		if(m_InfoBase.eNation == NATION_ELMORAD && pNPC->m_InfoBase.eNation != NATION_KARUS) continue; // 

		//-------------------------------------------------------------------------
		/*
		// TODO(srmeier): need to use ZoneAbilityType here
		// NOTE(srmeier): using zoneability information to determine if target is colliable
		if (!ACT_WORLD->canAttackSameNation() && (pNPC->m_InfoBase.eNation == m_InfoBase.eNation))
			continue;
		if (!ACT_WORLD->canAttackOtherNation() && (m_InfoBase.eNation == NATION_ELMORAD && pNPC->m_InfoBase.eNation == NATION_KARUS))
			continue;
		if (!ACT_WORLD->canAttackOtherNation() && (m_InfoBase.eNation == NATION_KARUS && pNPC->m_InfoBase.eNation == NATION_ELMORAD))
			continue;
		*/
		//-------------------------------------------------------------------------

		fMag = (pNPC->Position() - vPos).Magnitude();
		if(fMag < 32.0f)
		{
			fHeightSum = (pNPC->Height() + m_Chr.Height()) / 2.5f;
			if(fMag < fHeightSum) // 거리가 키의 합보다 작으면..
			{
				float fMag2 = (pNPC->Position() - vPosNext).Magnitude(); // 다음위치가 더 가까우면.
				if(fMag2 < fMag)
					return true;
			}
		}
	}//for(


	// 오브젝트와 충돌체크..
	__Vector3 vPos2 = vPos, vCol, vNormal;
	if (!s_pWorldMgr->IsIndoor())
		vPos2.y += 0.5f; // 캐릭터 발높이에서 0.5 미터 높이 위에서 충돌체크한다.
	else
		vPos2.y += 0.6f; // 캐릭터 발높이에서 0.6 미터 높이 위에서 충돌체크한다.	이 함수 내에서 쓰는 0.6은 PvsMgr의 m_fVolumeOffs.. ^^
	bool bColShape = ACT_WORLD->CheckCollisionWithShape(vPos2, vDir, fSpeed, &vCol, &vNormal);
	if( bColShape) return true; // 오브젝트와 충돌값이 있으면 

	////////////////////////////////////////////////////////////////////////////////
	// 지면과 오브젝트의 높이값 구하기..
	float fYTerrain = ACT_WORLD->GetHeightWithTerrain(vPosNext.x, vPosNext.z);		// 지면의 높이값..
	float fYClimb = ACT_WORLD->GetHeightNearstPosWithShape(vPosNext, CN3Base::s_fSecPerFrm * 30.0f, &vNormal); // 충돌 체크 오브젝트의 높이값..
	vNormal.y = 0; // 이래야 정상적인 경사를 얻을수 있다..
	
	if (!s_pWorldMgr->IsIndoor())
	{
		if(fYClimb > fYTerrain && fYClimb < vPosNext.y + ((30.0f/CN3Base::s_fFrmPerSec) * 0.5f)) // 충돌 체크 오브젝트 높이값이 있고 지형보다 높을 경우만 높이값 적용
		{
			if(vNormal.Magnitude() > MAX_INCLINE_CLIMB && vNormal.Dot(vDir) <= 0.0f) // 경사 체크..
			{
				return true;
			}
			m_fYNext = fYClimb;
		}
		else
		{
			// 지형의 경사가 45 도 이하인지 체크
			if(true == ACT_WORLD->CheckInclineWithTerrain(vPosNext, vDir, MAX_INCLINE_CLIMB))
			{
				return true;
			}
			m_fYNext = fYTerrain; // 다음 위치를 맞추고..
		}
	}
	else	// 일단..
	{
		if ((fYClimb > fYTerrain) && (fYClimb < vPosNext.y + 0.6f))
			m_fYNext = fYClimb;
		else
			m_fYNext = fYTerrain; // 다음 위치를 맞추고..

		if ((m_fYNext > vPos.y + 0.6f) || (m_fYNext < vPos.y - 0.6f*2.0f))
		{
			m_fYNext = vPos.y;
			return true;
		}
	}

//	else // 올라갈수 없는 곳이면 지형과의 기울기 체크..
//	{
//		// 방향을 구해서.. 기울기에 따라 다른 속도를 적용
//		s_pTerrain->GetNormal(vPos.x, vPos.z, vNormal);
//		vNormal.Normalize();
//		vNormal.y	= 0.0f;
//		float fM = vNormal.Magnitude();
//		float fD = vNormal.Dot(vDir);
//		if(fSpeed < 0) fD *= -1.0f;
//		if(fD < 0) fSpeed *= 1.0f - (fM / 0.7071f); // 기울기에 따른 팩터 적용
//
//		vPosNext = vPos + (vDir * fSpeed); // 다음 위치 계산..
//		m_fYNext = s_pTerrain->GetHeight(vPosNext.x, vPosNext.z);
//	}

	this->PositionSet(vPosNext, false);

	///////////////////////////////////////////////////////////////
	// 캐릭터 충돌 체크..
//	int iSize = s_pOPMgr->m_OPCs.size();
//	it_UPC it = s_pOPMgr->m_OPCs.begin();
//	for( int i = 0; i < iSize; i++, it++ )
//	{
//		if ( ((*it)->Position() - vPosAfter).Magnitude() < 1.2f )
//			return vPosBefore;
//	}

	return false;
}
Example #20
0
void VFmodManager::RunTick(float fTimeDelta)
{
  if (!IsInitialized())
    return;

  VISION_PROFILE_FUNCTION(PROFILING_FMOD_OVERALL);

  // profiling scope
  {
    VISION_PROFILE_FUNCTION(PROFILING_FMOD_PUREUPDATE);

    VASSERT(m_pEventSystem!=NULL);
    
    // update Fmod listener attributes
    VisObject3D_cl *pListener = m_pListenerObject ? m_pListenerObject : Vision::Camera.GetMainCamera();
    if (!pListener)
      return;

    hkvVec3 vCamPos = pListener->GetPosition();
    hkvVec3 vDir(pListener->GetObjDir()),
            vRight(pListener->GetObjDir_Right()),
            vUp(pListener->GetObjDir_Up());

    vUp = -vUp; // compensate for coordinate system
    m_pEventSystem->set3DListenerAttributes(0, (FMOD_VECTOR *)&vCamPos, NULL, (FMOD_VECTOR *)&vDir, (FMOD_VECTOR *)&vUp); // no speed (yet)
    
    
    // update all sound objects 
    SoundInstances().Update();

    // update all events 
    Events().Update();

    // update Fmod event system
    m_fTimeLeftOver += fTimeDelta;
    if (m_fTimeLeftOver > m_config.fTimeStep)
    { 
      m_pEventSystem->update();
#ifdef VFMOD_SUPPORTS_NETWORK
      if (m_config.bUseNetworkSystem)
        FMOD::NetEventSystem_Update();
#endif
      m_fTimeLeftOver = hkvMath::mod (m_fTimeLeftOver, m_config.fTimeStep);
    }
  } 
  
  // do not purge sounds/ events in vForge, in order to allow toggling playback via hotspot button
  if (Vision::Editor.IsInEditor())
    return;  

  if (m_bAnyStopped)
  {
    VISION_PROFILE_FUNCTION(PROFILING_FMOD_PURGE);

    // all sounds/ events that have finished playing are removed from handling
    SoundInstances().PurgeNotPlaying();
    Events().PurgeNotPlaying();

    m_bAnyStopped = false; // reset any stopped flag
  }
}
int CScriptBind_Physics::RayWorldIntersection(IFunctionHandler *pH)
{
	assert(pH->GetParamCount()>=3 && pH->GetParamCount()<=7);

	Vec3 vPos(0,0,0);
	Vec3 vDir(0,0,0);
	ScriptHandle skipId1;
	ScriptHandle skipId2;
	IEntity	*skipEnt1 = 0;
	IEntity	*skipEnt2 = 0;

	int nMaxHits,iEntTypes=ent_all;

	SmartScriptTable hitTable(m_pSS);

	if (!pH->GetParams(vPos,vDir,nMaxHits,iEntTypes))
		return pH->EndFunction();

	int nParams = pH->GetParamCount();
	if (nParams >= 5 && pH->GetParamType(5) != svtNull && pH->GetParam(5, skipId1))
		skipEnt1 = gEnv->pEntitySystem->GetEntity((EntityId)skipId1.n);
	if (nParams >= 6 && pH->GetParamType(6) != svtNull && pH->GetParam(6, skipId2))
		skipEnt2 = gEnv->pEntitySystem->GetEntity((EntityId)skipId2.n);
	
	bool bHitTablePassed = (nParams >= 7 );

	if(bHitTablePassed)
		pH->GetParam(7, hitTable);

	if (nMaxHits>10)
		nMaxHits=10;

	ray_hit RayHit[10];

	//filippo: added support for skip certain entities.
	int skipIdCount = 0;

	IPhysicalEntity	*skipPhys[2] = {0,0};

	if (skipEnt1)
	{
		++skipIdCount;
		skipPhys[0] = skipEnt1->GetPhysics();
	}
	if (skipEnt2)
	{
		++skipIdCount;
		skipPhys[1] = skipEnt2->GetPhysics();
	}

	Vec3 src = vPos;
	Vec3 dir = vDir;

	int nHits= m_pSystem->GetIPhysicalWorld()->RayWorldIntersection(src, dir, iEntTypes,
		geom_colltype0<<rwi_colltype_bit | rwi_stop_at_pierceable, RayHit, nMaxHits,skipPhys,skipIdCount);


	for (int i=0;i<nHits;i++)
	{
		SmartScriptTable pHitObj(m_pSS);
		ray_hit &Hit=RayHit[i];
		pHitObj->SetValue("pos",Hit.pt);
		pHitObj->SetValue("normal",Hit.n);
		pHitObj->SetValue("dist", Hit.dist);
		pHitObj->SetValue("surface", Hit.surface_idx);
		IEntity * pEntity = (IEntity*) Hit.pCollider->GetForeignData(PHYS_FOREIGN_ID_ENTITY);
		if (pEntity)
			pHitObj->SetValue("entity", pEntity->GetScriptTable());
		else
		{
			if(Hit.pCollider->GetiForeignData()==PHYS_FOREIGN_ID_STATIC)
			{
				IRenderNode * pRN = (IRenderNode*)Hit.pCollider->GetForeignData(PHYS_FOREIGN_ID_STATIC);
				if (pRN)
					pHitObj->SetValue("renderNode", ScriptHandle(pRN));
			}
			else if(Hit.pCollider->GetiForeignData()==PHYS_FOREIGN_ID_FOLIAGE)
			{
				IRenderNode * pRN = ((IFoliage*)Hit.pCollider->GetForeignData(PHYS_FOREIGN_ID_FOLIAGE))->GetIRenderNode();
				if (pRN)
					pHitObj->SetValue("renderNode", ScriptHandle(pRN));
			}
		}
		hitTable->SetAt(i+1, pHitObj);
	}

	if (bHitTablePassed )
		return pH->EndFunction(nHits);

	return pH->EndFunction(*hitTable);
}
Example #22
0
void VFmodManager::RunTick(float fTimeDelta)
{
  VISION_PROFILE_FUNCTION(PROFILING_FMOD_OVERALL);

  if (!IsInitialized())
  {
    if (!IsOutputDevicePresent())
      InitDevice();

    return; 
  }

  // profiling scope
  {
    VISION_PROFILE_FUNCTION(PROFILING_FMOD_PUREUPDATE);

    VASSERT(m_pEventSystem!=NULL);

    // update Fmod listener attributes
    VisObject3D_cl *pListener = m_pListenerObject;
    if (pListener == NULL)
    {
      // The listener is the main camera. Check for teleportation since the last Fmod update, in
      // which case we won't use the position difference to calculate the listener speed.
      VisContextCamera_cl* pCamera = Vision::Camera.GetMainCamera();
      VisRenderContext_cl* pContext = VisRenderContext_cl::GetMainRenderContext();
      if (pCamera != NULL && pContext != NULL)
      {
        if (m_bLastListenerPositionValid && pCamera->GetLastTeleported() > m_iFrameOfLastUpdate)
          m_bLastListenerPositionValid = false;

        m_iFrameOfLastUpdate = pContext->GetLastRenderedFrame();
        pListener = pCamera;
      }
    }

    if (!pListener)
      return;

    hkvVec3 vCamPos = pListener->GetPosition();
    hkvVec3 vDir(pListener->GetObjDir()),
            vRight(pListener->GetObjDir_Right()),
            vUp(pListener->GetObjDir_Up());

    // Determine the camera velocity based on the previous known position
    hkvVec3 vCamVel(m_bLastListenerPositionValid && (fTimeDelta > 0.f) ? (vCamPos - m_vLastListenerPosition) * (1.f / fTimeDelta) : hkvVec3::ZeroVector());
    m_vLastListenerPosition = vCamPos;
    m_bLastListenerPositionValid = true;

    vUp = -vUp; // compensate for coordinate system
    m_pEventSystem->set3DListenerAttributes(0, (FMOD_VECTOR *)&vCamPos, (FMOD_VECTOR *)&vCamVel, (FMOD_VECTOR *)&vDir, (FMOD_VECTOR *)&vUp);

    // update all sound objects 
    SoundInstances().Update(fTimeDelta);

    // update all events 
    Events().Update(fTimeDelta);

    // update Fmod event system
    m_fTimeLeftOver += fTimeDelta;
    if (m_fTimeLeftOver > m_config.fTimeStep)
    { 
      m_pEventSystem->update();

#ifdef VFMOD_SUPPORTS_NETWORK
      if (m_config.bUseNetworkSystem)
        FMOD::NetEventSystem_Update();
#endif
      m_fTimeLeftOver = hkvMath::mod (m_fTimeLeftOver, m_config.fTimeStep);
    }
  }

  // do not purge sounds/ events in vForge, in order to allow toggling playback via hotspot button
  if (Vision::Editor.IsInEditor())
    return;  

  if (m_bAnyStopped)
  {
    VISION_PROFILE_FUNCTION(PROFILING_FMOD_PURGE);

    // all sounds/ events that have finished playing are removed from handling
    SoundInstances().PurgeNotPlaying();
    Events().PurgeNotPlaying();

    m_bAnyStopped = false; // reset any stopped flag
  }
}