Пример #1
0
void SetArrowColor(TwBar* bar, const char* varName, Float3 color)
{
    int32 rgb[3] = { int32(Saturate(color.x) * 255.0f),
                     int32(Saturate(color.y) * 255.0f),
                     int32(Saturate(color.z) * 255.0f) };
    TwCall(TwSetParam(bar, varName, "arrowcolor", TW_PARAM_INT32, 3, rgb));
}
Пример #2
0
float SampleHeightField(HeightField& field,float u, float v) {

  int pixelX = Saturate(u)*(field.xDim-1);
  int pixelY = Saturate(v)*(field.zDim-1);

  return field.values[pixelX][pixelY];
}
Пример #3
0
void UArm::ValidateCurrentPose() {
  arm_rotation_ = Saturate(arm_rotation_, ARM_ROTATION_MIN, ARM_ROTATION_MAX);
  arm_stretch_ = Saturate(arm_stretch_, ARM_STRETCH_MIN, ARM_STRETCH_MAX);
  arm_height_ = Saturate(arm_height_, ARM_HEIGHT_MIN, ARM_HEIGHT_MAX);
  hand_rotation_ = Saturate(hand_rotation_, HAND_ROTATION_MIN,
                            HAND_ROTATION_MAX);
}
Пример #4
0
void SetColor(TwBar* bar, Float3 color)
{
    int32 rgb[3] = { int32(Saturate(color.x) * 255.0f),
                     int32(Saturate(color.y) * 255.0f),
                     int32(Saturate(color.z) * 255.0f) };
    TwCall(TwSetParam(bar, nullptr, "color", TW_PARAM_INT32, 3, rgb));
}
Пример #5
0
// From Real-Time Collision Detection, pp. 149-151
// This is commonly implemented to find both nearest points,
// as there is one case where both need to be solved for
// either one to be correct. So if I need that functionality,
// I can just adjust the interface to return the second point.
// Likewise, I can easily return the distance between them.
Vector Segment::NearestPointTo( const Segment& Other, float* pTValue /*= NULL*/ ) const
{
	Vector d1 = m_Point2 - m_Point1;
	Vector d2 = Other.m_Point2 - Other.m_Point1;
	Vector r = m_Point1 - Other.m_Point1;

	float a = d1.LengthSquared();
	float e = d2.LengthSquared();
	float f = d2.Dot( r );

	float s = 0.0f;

	// NOTE: Both segments degenerate test goes here, clipped
	// for my implementation because it's redundant.

	if( a >= SMALLER_EPSILON )	// Make sure first segment isn't degenerate
	{
		float c = d1.Dot( r );
		if( e < SMALLER_EPSILON )
		{
			// Second segment is degenerate
			s = Saturate( -c / a );
		}
		else
		{
			// General non-degenerate case
			float b = d1.Dot( d2 );
			float Denom = ( a * e ) - ( b * b );

			// If segments are not parallel, compute closest point on this line to other
			// line and clamp to this segment. Else pick arbitrary place on line for now,
			// which we'll do by leaving s at 0.
			if( Denom != 0.0f )
			{
				s = Saturate( ( ( b * f ) - ( c * e ) ) / Denom );
			}

			// Now compute point on other line closest to this segment.
			float tnom = ( b * s ) + f;
			if( tnom < 0.0f )
			{
				s = Saturate( -c / a );
			}
			else if( tnom > e )
			{
				s = Saturate( ( b - c ) / a );
			}
			// Else the s we computed above is still valid
		}
	}

	// Return the t-value if user needs it
	if( pTValue )
	{
		*pTValue = s;
	}

	return m_Point1 + ( d1 * s );
}
Пример #6
0
// Assumes RGBA order, mainly because Vector is RGB
uint Vector4::ToColor() const
{
	float R = Saturate( x );
	float G = Saturate( y );
	float B = Saturate( z );
	float A = Saturate( w );

	return ARGB_TO_COLOR( (byte)( A * 255.0f ), (byte)( R * 255.0f ), (byte)( G * 255.0f ), (byte)( B * 255.0f ) );
}
Пример #7
0
static void DrawPointer(uint16_t* aOut, uint32_t aPitchInPix)
{
   if(FramesWithPointer-- < 0)
      return;

   TouchX = Saturate(0, (GPU_LR_FRAMEBUFFER_NATIVE_WIDTH-1), TouchX);
   TouchY = Saturate(0, (GPU_LR_FRAMEBUFFER_NATIVE_HEIGHT-1), TouchY);

   if(TouchX >   (5 * scale)) DrawPointerLine(&aOut[TouchY * aPitchInPix + TouchX - (5 * scale) ], 1);
   if(TouchX < (GPU_LR_FRAMEBUFFER_NATIVE_WIDTH - (5 * scale) )) DrawPointerLine(&aOut[TouchY * aPitchInPix + TouchX + 1], 1);
   if(TouchY >   (5 * scale)) DrawPointerLine(&aOut[(TouchY - (5 * scale) ) * aPitchInPix + TouchX], aPitchInPix);
   if(TouchY < (GPU_LR_FRAMEBUFFER_NATIVE_HEIGHT-(5 * scale) )) DrawPointerLine(&aOut[(TouchY + 1) * aPitchInPix + TouchX], aPitchInPix);
}
Пример #8
0
void Cf3MapObjectBanana::OnDrawAll(CDIB32 *lp)
{
	int sx, sy, ex, ey;
	sx = sy = 0;
	m_pParent->GetViewPos(sx,sy);
	sx = (-sx)>>5; sy = (-sy)>>5;
	ex = sx+320/32; ey = sy+224/32;
	Saturate(sx,ex,m_pParent->GetWidth()-1);
	Saturate(sy,ey,m_pParent->GetHeight()-1);
	for (Cf3MapObjectBase**it=m_pParent->GetMapObjects(sx, sy, ex, ey, MOT_BANANA); (*it)!=NULL; it++) {
		if ((*it)->IsValid()) (*it)->OnDraw(lp);
	}
}
	void update()
	{
		const double progressRate = Saturate(1.0*m_state.m_timer / (1.0*m_state.m_stateLimit));

		const Vec2 focusPos = Vec2(3904, 4082);

		switch (m_state.m_state)
		{
		case 0:
			D2Camera::I()->m_pos = EaseInOut(m_startPos, focusPos, Easing::Cubic, progressRate);

			m_state.checkTimerAndGoNextState(150);
			break;
		case 1:
			D2Camera::I()->m_pos = focusPos;

			m_state.checkTimerAndGoNextState(60);
			break;
		case 2:
			D2Camera::I()->m_pos = EaseInOut(focusPos, m_startPos, Easing::Cubic, progressRate);

			m_state.checkTimerAndGoNextState(60);
			break;
		case 3:
			break;
		}

		m_state.update();

	}
Пример #10
0
VertexShaderOutput VsFixedFunctionAltUv::Main( const Vertex& vertex )
{
	VertexShaderOutput output;

	// clip space position
	output.position = worldViewProjMatrix.Transform(vertex.position);

	// StarCraft 2 uses a strange UV coordinate system
	output.texCoord.x = vertex.texCoord.x * 2.0f;
	output.texCoord.y = 1.0f - vertex.texCoord.y;

	// lighting
	Vector4& objSpaceLightPos = inverseWorldMatrix.Transform(lightPosition);

	Vector3 objSpaceLightDir;
	objSpaceLightDir.x = objSpaceLightPos.x;
	objSpaceLightDir.y = objSpaceLightPos.y;
	objSpaceLightDir.z = objSpaceLightPos.z;
	objSpaceLightDir = objSpaceLightDir - vertex.position;
	objSpaceLightDir.Normalize();

	float angle = vertex.normal.Dot(objSpaceLightDir);
	Saturate(angle);

	output.attribute0 = diffuseColor * angle + ambientColor;

	return output;
}
Пример #11
0
// Computes shadow depth bounds on the CPU using the mesh vertex positions
void MeshRenderer::ComputeShadowDepthBoundsCPU(const Camera& camera)
{
    Float4x4 viewMatrix = camera.ViewMatrix();
    const float nearClip = camera.NearClip();
    const float farClip = camera.FarClip();
    const float clipDist = farClip - nearClip;

    float minDepth = 1.0f;
    float maxDepth = 0.0f;
	for (int i = 0; i < _scene->getNumModels(); i++)
	{
		Model *model = _scene->getModel(i);
		const uint64 numMeshes = model->Meshes().size();
		for (uint64 meshIdx = 0; meshIdx < numMeshes; ++meshIdx)
		{
			const Mesh& mesh = model->Meshes()[meshIdx];
			const uint64 numVerts = mesh.NumVertices();
			const uint64 stride = mesh.VertexStride();
			const uint8* vertices = mesh.Vertices();
			for (uint64 i = 0; i < numVerts; ++i)
			{
				const Float3& position = *reinterpret_cast<const Float3*>(vertices);
				float viewSpaceZ = Float3::Transform(position, viewMatrix).z;
				float depth = Saturate((viewSpaceZ - nearClip) / clipDist);
				minDepth = std::min(minDepth, depth);
				maxDepth = std::max(maxDepth, depth);
				vertices += stride;
			}
		}
	}
    
    _shadowDepthBounds = Float2(minDepth, maxDepth);
}
EdgeMask::EdgeMask(PClip _child, unsigned int thY1, unsigned int thY2,
				   unsigned int thC1, unsigned int thC2, const char *string, 
                   int _X, int _Y, int _w, int _h, int y, int u, int v,
                   bool _mmx, bool _isse, IScriptEnvironment* env) :
BaseFilter(_child, _X, _Y, _w, _h, y, u, v, _mmx, _isse, env, "EdgeMask"), Yth1(thY1), Yth2(thY2), Cth1(thC1), Cth2(thC2)
{
   CheckColorSpace(vi, env);
	
	Yth1 = Saturate(Yth1, 0, 255);
   Yth2 = Saturate(Yth2, Yth1, 255);
   Cth1 = Saturate(Cth1, 0, 255);
   Cth2 = Saturate(Cth2, Cth1, 255);

	/* Check mode and if width is MOD8 */
	if (!lstrcmpi(string,"line"))
	{
      BuildMaskY = CheckMMXOptimizations(env, CHK_MOD_8, CHK_MOD_1) ? Line_C : Line_C;
      BuildMaskUV = CheckMMXOptimizations(env, CHK_MOD_16, CHK_MOD_1) ? Line_C : Line_C;
	}
	else if (!lstrcmpi(string,"roberts"))
	{
      BuildMaskY = CheckMMXOptimizations(env, CHK_MOD_8, CHK_MOD_1) ? Roberts_MMX : Roberts_C;
      BuildMaskUV = CheckMMXOptimizations(env, CHK_MOD_16, CHK_MOD_1) ? Roberts_MMX : Roberts_C;
	}
	else if (!lstrcmpi(string,"sobel"))
	{
      BuildMaskY = CheckMMXOptimizations(env, CHK_MOD_8, CHK_MOD_1) ? Sobel_MMX : Sobel_C;
      BuildMaskUV = CheckMMXOptimizations(env, CHK_MOD_16, CHK_MOD_1) ? Sobel_MMX : Sobel_C;
	}
	else if (!lstrcmpi(string,"special"))
	{
      BuildMaskY = CheckMMXOptimizations(env, CHK_MOD_8, CHK_MOD_1) ? Special_MMX : Special_C;
      BuildMaskUV = CheckMMXOptimizations(env, CHK_MOD_16, CHK_MOD_1) ? Special_MMX : Special_C;
	}
	else if (!lstrcmpi(string,"cartoon"))
	{
      BuildMaskY = CheckMMXOptimizations(env, CHK_MOD_8, CHK_MOD_1) ? Cartoon_C : Cartoon_C;
      BuildMaskUV = CheckMMXOptimizations(env, CHK_MOD_16, CHK_MOD_1) ? Cartoon_C : Cartoon_C;
	}
	else if (!lstrcmpi(string,"laplace"))
	{
      BuildMaskY = CheckMMXOptimizations(env, CHK_MOD_8, CHK_MOD_1) ? Laplace_C : Laplace_C;
      BuildMaskUV = CheckMMXOptimizations(env, CHK_MOD_16, CHK_MOD_1) ? Laplace_C : Laplace_C;
	}
   else env->ThrowError("EdgeMask: unvalid edge detector : 'type' must be either 'line', 'roberts', 'sobel', 'special', 'cartoon' or 'laplace'");
}
Пример #13
0
void Firnplayer::Player::DrawTracks()
{
  TrackView.DrawFrame();
  auto ArtistLock = ArtistsQueue.Lock();
  int TotalHeight = TrackView.GetHeight();
  int ActiveLine = 0;

  if(!TotalHeight)
    return;

  { double TopBottomBuffer = Options["Layout Settings"]["TopBottomBuffer"].asDouble();
    Saturate(PositionInTracks, (unsigned int)(TotalHeight * TopBottomBuffer) + 1,
                               (unsigned int)(TotalHeight * (1 - TopBottomBuffer)));
  }

  if(!TracksForShowPrintable.size())
    return;

  std::vector<std::string> StringsToPrint;
  
  // First, get the lines from the top of the screen to the current selection.
  // This is done reversely.
  int CurString = TracksActualPos;
  for(; CurString  >= 0 && PositionInTracks > StringsToPrint.size(); CurString--)
  {
    StringsToPrint.insert(StringsToPrint.begin(), TracksForShowPrintable[CurString]);
  }
  ActiveLine = StringsToPrint.size() - 1;
  
  auto TopMostPosition = CurString;

  CurString = TracksActualPos + 1;

  if((StringsToPrint.size() < TotalHeight) && CurString < TracksForShowPrintable.size())
  {
    do
    {
      StringsToPrint.push_back(TracksForShowPrintable[CurString++]);
    } while(StringsToPrint.size() < TotalHeight && CurString < TracksForShowPrintable.size());
  }

  while(StringsToPrint.size() < TotalHeight && TopMostPosition >= 0)
  {
    StringsToPrint.insert(StringsToPrint.begin(), TracksForShowPrintable[TopMostPosition--]);
    ActiveLine++;
  }

  int CurrentString = 0;
  for(; CurrentString < StringsToPrint.size(); CurrentString++)
  {
    TrackView.Write(0, CurrentString, -1, A_NORMAL,
                     (CurrentString == ActiveLine && ActiveViewPort == ACTIVE_TRACKS) ? COLPAIR_LISTLINE:
                     (CurrentString == ActiveLine) ? COLPAIR_ACTLINE : COLPAIR_NORMAL,
                      StringsToPrint[CurrentString].c_str());
  }
  for(; CurrentString < TotalHeight; CurrentString++)
    TrackView.Write(0, CurrentString, -1, A_NORMAL, 2, "");
}
Пример #14
0
float3 QuaternionToEulerZXY(const quatf& q)
{
    float d[] = {
        q.x*q.x, q.x*q.y, q.x*q.z, q.x*q.w,
        q.y*q.y, q.y*q.z, q.y*q.w,
        q.z*q.z, q.z*q.w,
        q.w*q.w
    };

    float v0 = d[5] - d[3];
    float v1 = 2.0f*(d[1] + d[8]);
    float v2 = d[4] - d[7] - d[0] + d[9];
    float v3 = -1.0f;
    float v4 = 2.0f * v0;

    const float SINGULARITY_CUTOFF = 0.499999f;
    if (std::abs(v0) < SINGULARITY_CUTOFF)
    {
        float v5 = 2.0f * (d[2] + d[6]);
        float v6 = d[7] - d[0] - d[4] + d[9];

        return{
            v3 * std::asin(Saturate(v4)),
            std::atan2(v5, v6),
            std::atan2(v1, v2)
        };
    }
    else //x == yzy z == 0
    {
        float a = d[1] + d[8];
        float b =-d[5] + d[3];
        float c = d[1] - d[8];
        float e = d[5] + d[3];

        float v5 = a*e + b*c;
        float v6 = b*e - a*c;

        return{
            v3 * std::asin(Saturate(v4)),
            std::atan2(v5, v6),
            0.0f
        };
    }
}
Пример #15
0
 uint8_t DesaturateChannel(uint8_t channel, float amount)
 {
     amount = Saturate(amount); // performs clamping
     const float precColor = static_cast<float>(channel);
     const float gray = 127.0f;
     float result = (amount * gray) + ((1.0f - amount) * precColor);
     result = std::min<float>(result, 255.0f);
     result = std::max<float>(result, 0.0f);
     return static_cast<uint8_t>(result);
 }
Пример #16
0
T SmoothStep(const T& min, const T& max, const T& amount)
{
    static_assert(std::is_floating_point<T>::value ||
        Detail::IsTaggedFloatingPoint<T>::value,
        "T is floaing point number");
    //POMDOG_ASSERT(amount >= 0);
    //POMDOG_ASSERT(amount <= 1);
    auto x = Saturate(amount);
    auto scale = x * x * (T{3} - T{2} * x);
    return min + scale * (max - min);
}
Пример #17
0
bool mi::Work(float *psamples, int numsamples, int const mode)
{
    float const threshold = (float)(Vals[0]) / float(0x8000);
    float const negthreshold = -(float)(Vals[5]) / float(0x8000);

    float const wet = (float)Vals[1] * 0.00390625f;

    float const pre_gain = (float)Vals[4] * 0.00390625f;

    for (int i = 0; i < numsamples; i++) {
        psamples[i] = psamples[i] * pre_gain;
    }

    if (Vals[3] == 0) {
        if (Vals[2] == 0) {
            // Clip, No Phase inversion
            for (int i = 0; i < numsamples; i++) {
                Clip(&psamples[i], threshold, negthreshold, wet);
            }
        } else {
            // Clip, Phase inversion
            for (int i = 0; i < numsamples; i++) {
                Clip(&psamples[i], threshold, negthreshold, wet);
            }
        }
    } else {
        if (Vals[2] == 0) {
            // Saturate, No Phase inversion
            for (int i = 0; i < numsamples; i++) {
                Saturate(&psamples[i], threshold, negthreshold, wet);
            }
        } else {
            // Saturate, Phase inversion
            for (int i = 0; i < numsamples; i++) {
                Saturate(&psamples[i], threshold, negthreshold, wet);
            }
        }
    }
    return true;
}
Пример #18
0
// Blend over time to discrete volume values (as opposed to interpolating
// between eight near volumes, which would be a lot of calculations and would
// dilute extreme values).
void Mesh::BlendIrradianceVolume(
    const IrradianceVolumes& Volumes, float DeltaTime, const Vector& Location,
    const Vector4& ConstantTerm /*= Vector4( 0.0f, 0.0f, 0.0f, 0.0f )*/) {
  STATICHASH(IrradianceVolumeBlendRate);
  const SIrradianceVolume& TargetVolume = Volumes.GetNearestVolume(Location);
  float BlendT = Saturate(
      DeltaTime * ConfigManager::GetFloat(sIrradianceVolumeBlendRate, 1.0f));
  for (uint i = 0; i < 6; ++i) {
    m_IrradianceVolume.m_Light[i] =
        (m_IrradianceVolume.m_Light[i] * (1.0f - BlendT)) +
        ((ConstantTerm + TargetVolume.m_Light[i]) * BlendT);
  }
}
Пример #19
0
bool OM_DomeScreen::xyTo3D(float x, float y, float *xyz)
{
#ifdef notdef
	OmniVec3 bl= OmniVec3(x,y,0.0);
	bl.z =  sqrt(Saturate(1.0-bl.x*bl.x - bl.y*bl.y));
	xyz[0] = bl.x;
	xyz[1] = bl.y;
	xyz[2] = bl.z;
	xyz[3] = 0.0;

	OmniVec3 bl2;
	bl2.x = bl.x;
	bl2.y = bl.y;

	OmniVec3 gl_Position;

		//vec4 VertexPosition_projectorSpace_Goal = ftransform();

		// F-Theta Warping Code
		float Z = bl.z;
		//float D = length(VertexPosition_projectorSpace_Goal.xyz);
		float D = bl.length();


		float MyPI = 3.14159265;  
		float R = (2.0/MyPI) * acos(Z/D);  // Ftheta.

		// if(usebangtheta)
		R =  0.2798*R *R *R *R *R *R  - 0.6875*R *R *R *R *R  + 0.7351*R *R *R *R  - 0.3472*R *R *R  + 0.0977*R *R  + 0.9221*R ;  
 
	
		float l =1.0/ (bl2.length()+.0000000000000000000000000000000000001);// bug fix  1
		float thetavec[2] = { bl.x*l, bl.y*l};
		
		gl_Position.x = thetavec[0] * R * 2.0;
		gl_Position.y = thetavec[1] * R * 2.0;
#endif	
		OmniVec3 gl_Position;	
		gl_Position.x = x;
		gl_Position.y = y;
		float xy2_2 = ((x*x)+(y*y))-1.0;
		gl_Position.z = -sqrtf(fabs(xy2_2));
		if (gl_Position.z > this->Radius)
			return false;
		xyz[0] = gl_Position.x;
		xyz[1] = gl_Position.y;
		xyz[2] = gl_Position.z;
		xyz[3] = 0.0;
		return(true);
}
Пример #20
0
/*virtual*/ void SoundInstanceCommon::Tick3D() {
  DEBUGASSERT(GetSound()->GetIs3D());

  const Sound3DListener* const pListener = Get3DListener();
  DEVASSERT(pListener);

  Vector DirectionToSound;
  float DistanceToSound;
  float OneOverDistanceToSound;

  const Vector SoundLocation = GetLocation();
  const Vector OffsetToSound = SoundLocation - pListener->GetLocation();
  OffsetToSound.GetNormalized(DirectionToSound, DistanceToSound,
                              OneOverDistanceToSound);

  const float FalloffRadius = m_Sound->GetFalloffDistance();
  const float MinimumAttenuation = m_Sound->GetMinimumAttenuation();
  DEVASSERT(FalloffRadius > 0.0f);

  // Set pan based on distance and direction.
  const float PanBias = m_Sound->GetBiasedPan(DistanceToSound);
  const float PanCosTheta = pListener->GetRight().Dot(DirectionToSound);

  // This is a little bit of fakery; further attenuate sounds behind the
  // listener.
  const float Surround = pListener->GetForward().Dot(DirectionToSound);
  float RearAttenuation = Saturate((-Surround * PanBias));
  RearAttenuation = 1.0f - (RearAttenuation * m_Sound->GetRearAttenuation());

  // Set attenuation based on distance and rear attenuation
  m_Attenuation = FalloffRadius / (FalloffRadius + DistanceToSound);
  m_Attenuation *= RearAttenuation;

  if (m_Attenuation >= MinimumAttenuation) {
    pListener->ModifyAttenuation(this, m_Attenuation);
  }

  if (m_Attenuation < MinimumAttenuation) {
    m_Attenuation = 0.0f;
  } else {
    // Don't bother setting the pan unless we'll hear it!
    const float PanPow = SignedPow(PanCosTheta, m_Sound->GetPanPower());
    const float Pan = PanPow * PanBias;
    SetPan(Pan);
  }
}
Пример #21
0
bool CMachine::Work(float *pin,int numSamples,int const Mode) {

	if(Mode == WM_READWRITE) {
		double t = fEnv * DetectLevel(pin,numSamples); if(t>1.0) t=1.0;
		Filter(pin,numSamples,(t-gLastT)*gInertiaSamples_inv);
		Saturate(pin,numSamples);
		return true;
	}
	else if(Mode == WM_READ) {
		double t = fEnv * DetectLevel(pin,numSamples); if(t>1.0) t=1.0;
		gLastT += numSamples * (t-gLastT)*gInertiaSamples_inv;
	}
	else {
		gLastT += numSamples * (0.00001-gLastT)*gInertiaSamples_inv;
	}
	return false;
}
Пример #22
0
	bool Execute(const VS_Output* input, PS_Output* output, float* pDepthIO)
	{
		DefineVaryingInput(float3, iPosW, 0);
		DefineVaryingInput(float3, iNormal, 1);
		DefineVaryingInput(float2, iTex, 2);
		DefineVaryingInput(float4, iColor, 3);

		float3 L = Normalize(LightPos - iPosW);
		float3 N = Normalize(iNormal);

		float NdotL = Dot(N, L);

		output->Color[0] = Saturate(ColorRGBA((float*)&iColor) * NdotL);

		//ColorRGBA diffuse = Sample(DiffuseTex, LinearSampler, iTex.X(), iTex.Y());
		//output->Color[0] = ColorRGBA(diffuse.R, diffuse.G, diffuse.B, 1.0f);

		return true;
	}
Пример #23
0
void WBCompEldMesh::UpdateIrradiance(const float DeltaTime) {
  ASSERT(m_Mesh);

  // If needed for optimization, only do this on certain events (loaded, moved,
  // etc.)

  WBCompEldTransform* pTransform =
      GetEntity()->GetTransformComponent<WBCompEldTransform>();
  DEVASSERT(pTransform);  // Makes no sense to have a mesh and no transform

  const Vector EntityLocation = pTransform->GetLocation();

  EldritchWorld* const pWorld = GetWorld();
  const Vector IrradianceOffset = Vector(0.0f, 0.0f, m_IrradianceOffsetZ);

  SVoxelIrradiance CurrentIrradiance;
  if (m_UseTwoPointIrradiance) {
    const Vector LocationA = EntityLocation + IrradianceOffset;
    const Vector LocationB = LocationA + m_TwoPointIrradianceOffset;
    CurrentIrradiance = pWorld->BlendIrradiances(LocationA, LocationB);
  } else {
    CurrentIrradiance =
        pWorld->GetIrradianceAt(EntityLocation + IrradianceOffset);
  }

  for (auto & DirLight : CurrentIrradiance.m_Light) {
    
    DirLight += m_CurrentHighlight;
    DirLight += m_ConstantIrradiance;
  }

  if (m_UseBlendedIrradiance) {
    const float BlendTime = Saturate(DeltaTime * m_BlendRate);
    m_BlendedIrradiance = SVoxelIrradiance::Lerp(m_BlendedIrradiance,
                                                 CurrentIrradiance, BlendTime);
    m_Mesh->SetIrradianceCube(m_BlendedIrradiance);
  } else {
    m_Mesh->SetIrradianceCube(CurrentIrradiance);
  }
}
Пример #24
0
void SetAlpha(TwBar* bar, float alpha)
{
    int32 a = int32(Saturate(alpha));
    TwCall(TwSetParam(bar, nullptr, "alpha", TW_PARAM_INT32, 1, &a));
}
Пример #25
0
/*virtual*/ void UIScreenEldMirror::InitializeFromDefinition( const SimpleString& DefinitionName )
{
	UIScreen::InitializeFromDefinition( DefinitionName );

	MAKEHASH( DefinitionName );

	STATICHASH( MirrorRigMesh );
	const SimpleString MirrorRigMesh = ConfigManager::GetString( sMirrorRigMesh, "", sDefinitionName );
	SetRigMesh( MirrorRigMesh );

	STATICHASH( MirrorAnimation );
	m_MirrorAnimation = ConfigManager::GetHash( sMirrorAnimation, HashedString::NullString, sDefinitionName );

	STATICHASH( MirrorRTWidth );
	m_MirrorRTWidth = ConfigManager::GetInt( sMirrorRTWidth, 0, sDefinitionName );

	STATICHASH( MirrorRTHeight );
	m_MirrorRTHeight = ConfigManager::GetInt( sMirrorRTHeight, 0, sDefinitionName );

	STATICHASH( MirrorYaw );
	m_MirrorYaw = DEGREES_TO_RADIANS( ConfigManager::GetFloat( sMirrorYaw, 0.0f, sDefinitionName ) );

	STATICHASH( MirrorViewFOV );
	m_MirrorViewFOV = ConfigManager::GetFloat( sMirrorViewFOV, 0.0f, sDefinitionName );

	STATICHASH( MirrorViewDistance );
	m_MirrorViewDistance = ConfigManager::GetFloat( sMirrorViewDistance, 0.0f, sDefinitionName );

	STATICHASH( MirrorViewHeight );
	m_MirrorViewHeight = ConfigManager::GetFloat( sMirrorViewHeight, 0.0f, sDefinitionName );

	STATICHASH( MirrorViewNearClip );
	m_MirrorViewNearClip = ConfigManager::GetFloat( sMirrorViewNearClip, 0.0f, sDefinitionName );

	STATICHASH( MirrorViewFarClip );
	m_MirrorViewFarClip = ConfigManager::GetFloat( sMirrorViewFarClip, 0.0f, sDefinitionName );

	STATICHASH( MirrorBackdropTile );
	m_MirrorBackdropTile = ConfigManager::GetInt( sMirrorBackdropTile, 0, sDefinitionName );

	STATICHASH( MirrorBackdropR );
	m_MirrorBackdropColor.r = ConfigManager::GetFloat( sMirrorBackdropR, 0.0f, sDefinitionName );

	STATICHASH( MirrorBackdropG );
	m_MirrorBackdropColor.g = ConfigManager::GetFloat( sMirrorBackdropG, 0.0f, sDefinitionName );

	STATICHASH( MirrorBackdropB );
	m_MirrorBackdropColor.b = ConfigManager::GetFloat( sMirrorBackdropB, 0.0f, sDefinitionName );

	m_MirrorBackdropColor.a = 1.0f;

	STATICHASH( MirrorBackdropDist );
	m_MirrorBackdropDistance = ConfigManager::GetFloat( sMirrorBackdropDist, 0.0f, sDefinitionName );

	STATICHASH( MirrorBackdropSize );
	m_MirrorBackdropExtents = 0.5f * ConfigManager::GetFloat( sMirrorBackdropSize, 0.0f, sDefinitionName );

	STATICHASH( MirrorLightR );
	const float MirrorLightR = ConfigManager::GetFloat( sMirrorLightR, 0.0f, sDefinitionName );

	STATICHASH( MirrorLightG );
	const float MirrorLightG = ConfigManager::GetFloat( sMirrorLightG, 0.0f, sDefinitionName );

	STATICHASH( MirrorLightB );
	const float MirrorLightB = ConfigManager::GetFloat( sMirrorLightB, 0.0f, sDefinitionName );

	STATICHASH( MirrorLightX );
	const float MirrorLightX = ConfigManager::GetFloat( sMirrorLightX, 0.0f, sDefinitionName );

	STATICHASH( MirrorLightY );
	const float MirrorLightY = ConfigManager::GetFloat( sMirrorLightY, 0.0f, sDefinitionName );

	STATICHASH( MirrorLightZ );
	const float MirrorLightZ = ConfigManager::GetFloat( sMirrorLightZ, 0.0f, sDefinitionName );

	const Vector4	MirrorLightColor	= Vector4( MirrorLightR, MirrorLightG, MirrorLightB, 1.0f );
	const Vector	MirrorLightDir		= Vector( MirrorLightX, MirrorLightY, MirrorLightZ ).GetNormalized();

	m_MirrorIrradiance.m_Light[ IRRDIR_Right ]	= MirrorLightColor * Saturate( MirrorLightDir.Dot( Vector( -1.0f, 0.0f, 0.0f ) ) );
	m_MirrorIrradiance.m_Light[ IRRDIR_Left ]	= MirrorLightColor * Saturate( MirrorLightDir.Dot( Vector( 1.0f, 0.0f, 0.0f ) ) );
	m_MirrorIrradiance.m_Light[ IRRDIR_Front ]	= MirrorLightColor * Saturate( MirrorLightDir.Dot( Vector( 0.0f, -1.0f, 0.0f ) ) );
	m_MirrorIrradiance.m_Light[ IRRDIR_Back ]	= MirrorLightColor * Saturate( MirrorLightDir.Dot( Vector( 0.0f, 1.0f, 0.0f ) ) );
	m_MirrorIrradiance.m_Light[ IRRDIR_Up ]		= MirrorLightColor * Saturate( MirrorLightDir.Dot( Vector( 0.0f, 0.0f, -1.0f ) ) );
	m_MirrorIrradiance.m_Light[ IRRDIR_Down ]	= MirrorLightColor * Saturate( MirrorLightDir.Dot( Vector( 0.0f, 0.0f, 1.0f ) ) );
}
Пример #26
0
    Float3 SunLuminance(bool& cached)
    {
        Float3 sunDirection = AppSettings::SunDirection;
        sunDirection.y = Saturate(sunDirection.y);
        sunDirection = Float3::Normalize(sunDirection);
        const float turbidity = Clamp(AppSettings::Turbidity.Value(), 1.0f, 32.0f);
        const float intensityScale = AppSettings::SunIntensityScale;
        const Float3 tintColor = AppSettings::SunTintColor;
        const bool32 normalizeIntensity = AppSettings::NormalizeSunIntensity;
        const float sunSize = AppSettings::SunSize;

        static float turbidityCache = 2.0f;
        static Float3 sunDirectionCache = Float3(-0.579149902f, 0.754439294f, -0.308879942f);
        static Float3 luminanceCache = Float3(1.61212531e+009f, 1.36822630e+009f, 1.07235315e+009f);
        static Float3 sunTintCache = Float3(1.0f, 1.0f, 1.0f);
        static float sunIntensityCache = 1.0f;
        static bool32 normalizeCache = false;
        static float sunSizeCache = AppSettings::BaseSunSize;

        if(turbidityCache == turbidity && sunDirection == sunDirectionCache
            && intensityScale == sunIntensityCache && tintColor == sunTintCache
            && normalizeCache == normalizeIntensity && sunSize == sunSizeCache)
        {
            cached = true;
            return luminanceCache;
        }

        cached = false;

        float thetaS = std::acos(1.0f - sunDirection.y);
        float elevation = Pi_2 - thetaS;

        // Get the sun's luminance, then apply tint and scale factors
        Float3 sunLuminance;

        // For now, we'll compute an average luminance value from Hosek solar radiance model, even though
        // we could compute illuminance directly while we're sampling the disk
        SampledSpectrum groundAlbedoSpectrum = SampledSpectrum::FromRGB(GroundAlbedo);
        SampledSpectrum solarRadiance;

        const uint64 NumDiscSamples = 4;
        for(uint64 x = 0; x < NumDiscSamples; ++x)
        {
            for(uint64 y = 0; y < NumDiscSamples; ++y)
            {
                float u = (x + 0.5f) / NumDiscSamples;
                float v = (y + 0.5f) / NumDiscSamples;
                Float2 discSamplePos = SquareToConcentricDiskMapping(u, v);

                float theta = elevation + discSamplePos.y * DegToRad(AppSettings::BaseSunSize);
                float gamma = discSamplePos.x * DegToRad(AppSettings::BaseSunSize);

                for(int32 i = 0; i < NumSpectralSamples; ++i)
                {
                    ArHosekSkyModelState* skyState = arhosekskymodelstate_alloc_init(elevation, turbidity, groundAlbedoSpectrum[i]);
                    float wavelength = Lerp(float(SampledLambdaStart), float(SampledLambdaEnd), i / float(NumSpectralSamples));

                    solarRadiance[i] = float(arhosekskymodel_solar_radiance(skyState, theta, gamma, wavelength));

                    arhosekskymodelstate_free(skyState);
                    skyState = nullptr;
                }

                Float3 sampleRadiance = solarRadiance.ToRGB();
                sunLuminance += sampleRadiance;
            }
        }

        // Account for luminous efficiency, coordinate system scaling, and sample averaging
        sunLuminance *= 683.0f * 100.0f * (1.0f / NumDiscSamples) * (1.0f / NumDiscSamples);

        sunLuminance = sunLuminance * tintColor;
        sunLuminance = sunLuminance * intensityScale;

        if(normalizeIntensity)
        {
            // Normalize so that the intensity stays the same even when the sun is bigger or smaller
            const float baseIntegral = IlluminanceIntegral(DegToRad(AppSettings::BaseSunSize));
            const float currIntegral = IlluminanceIntegral(DegToRad(AppSettings::SunSize));
            sunLuminance *= (baseIntegral / currIntegral);
        }

        turbidityCache = turbidity;
        sunDirectionCache = sunDirection;
        luminanceCache = sunLuminance;
        sunIntensityCache = intensityScale;
        sunTintCache = tintColor;
        normalizeCache = normalizeIntensity;
        sunSizeCache = sunSize;

        return sunLuminance;
    }
Пример #27
0
int main(int argc, char* argv[])
{
   int              retval = NO_ERROR;
   CLState_p        state;
   ProofState_p     proofstate;
   ProofControl_p   proofcontrol;
   Clause_p         success = NULL, 
                    filter_success;
   bool             out_of_clauses;
   char             *finals_state = "exists",
                    *sat_status = "Derivation";
   long             raw_clause_no,
                    preproc_removed=0, 
                    neg_conjectures,
                    parsed_ax_no,
                    relevancy_pruned = 0;
   double           preproc_time;

   assert(argv[0]);

   pid = getpid();
   InitIO(NAME);
#ifdef STACK_SIZE
   IncreaseMaxStackSize(argv, STACK_SIZE);
#endif
   ESignalSetup(SIGXCPU);

   h_parms = HeuristicParmsAlloc();
   fvi_parms = FVIndexParmsAlloc();   
   wfcb_definitions = PStackAlloc();
   hcb_definitions = PStackAlloc();

   state = process_options(argc, argv);
  
   OpenGlobalOut(outname);
   print_info();


   if(state->argc ==  0)
   {
      CLStateInsertArg(state, "-");
   }

   proofstate = parse_spec(state, parse_format, 
                           error_on_empty, free_symb_prop,
                           &parsed_ax_no);  


   relevancy_pruned += ProofStateSinE(proofstate, sine);
   relevancy_pruned += ProofStatePreprocess(proofstate, relevance_prune_level);

   if(strategy_scheduling)
   {
      ExecuteSchedule(StratSchedule, h_parms, print_rusage);
   }

   FormulaSetDocInital(GlobalOut, OutputLevel, proofstate->f_axioms);
   ClauseSetDocInital(GlobalOut, OutputLevel, proofstate->axioms);

   if(prune_only)
   {
      fprintf(GlobalOut, "\n# Pruning successful!\n");	    
      TSTPOUT(GlobalOut, "Unknown");
      goto cleanup1;
   }

   if(relevancy_pruned || incomplete)
   {
      proofstate->state_is_complete = false;
   }
   if(BuildProofObject)
   {
      FormulaSetArchive(proofstate->f_axioms, proofstate->f_ax_archive);
   }   
   if((neg_conjectures =
       FormulaSetPreprocConjectures(proofstate->f_axioms, 
                                    proofstate->f_ax_archive,
                                    answer_limit>0, 
                                    conjectures_are_questions)))
   {
      VERBOUT("Negated conjectures.\n");
   }
   if(FormulaSetCNF(proofstate->f_axioms,
                    proofstate->f_ax_archive,
                    proofstate->axioms, 
                    proofstate->original_terms, 
                    proofstate->freshvars,
                    proofstate->gc_original_terms))
   {
      VERBOUT("CNFization done\n");
   }
   ProofStateInitWatchlist(proofstate, watchlist_filename, parse_format);
   raw_clause_no = proofstate->axioms->members;   
   if(!no_preproc)
   {
      if(BuildProofObject)
      {
         ClauseSetArchive(proofstate->ax_archive, proofstate->axioms);
         if(proofstate->watchlist)
         {
            ClauseSetArchive(proofstate->ax_archive, proofstate->watchlist);
         }
      }
      preproc_removed = ClauseSetPreprocess(proofstate->axioms,
					    proofstate->watchlist,
                                            proofstate->archive,
					    proofstate->tmp_terms,
					    eqdef_incrlimit, 
                                            eqdef_maxclauses);
   }

   proofcontrol = ProofControlAlloc();
   ProofControlInit(proofstate, proofcontrol, h_parms, 
                    fvi_parms, wfcb_definitions, hcb_definitions);
   PCLFullTerms = pcl_full_terms; /* Preprocessing always uses full
				     terms, so we set the flag for
				     the main proof search only now! */
   ProofStateInit(proofstate, proofcontrol);

   VERBOUT2("Prover state initialized\n");   
   preproc_time = GetTotalCPUTime();
   if(print_rusage)
   {
      fprintf(GlobalOut, "# Preprocessing time       : %.3f s\n", preproc_time);
   }
   if(proofcontrol->heuristic_parms.presat_interreduction)
   {
      LiteralSelectionFun sel_strat = 
         proofcontrol->heuristic_parms.selection_strategy;

      proofcontrol->heuristic_parms.selection_strategy = SelectNoGeneration;
      success = Saturate(proofstate, proofcontrol, LONG_MAX,
                         LONG_MAX, LONG_MAX, LONG_MAX, LONG_MAX);
      fprintf(GlobalOut, "# Presaturation interreduction done\n");
      proofcontrol->heuristic_parms.selection_strategy = sel_strat;
      if(!success)
      {
         ProofStateResetProcessed(proofstate, proofcontrol);
      }
   }
   PERF_CTR_ENTRY(SatTimer);
   
   if(!success)
   {      
      success = Saturate(proofstate, proofcontrol, step_limit,
                         proc_limit, unproc_limit, total_limit, answer_limit);
   }
   PERF_CTR_EXIT(SatTimer);
   
   out_of_clauses = ClauseSetEmpty(proofstate->unprocessed);
   if(filter_sat)
   {
      filter_success = ProofStateFilterUnprocessed(proofstate,
						   proofcontrol,
						   filterdesc);
      if(filter_success)
      {
	 success = filter_success;
         PStackPushP(proofstate->extract_roots, success);
      }
   }
   
   if(success||proofstate->answer_count)
   {
      assert(!PStackEmpty(proofstate->extract_roots));
      if(success)
      {
         DocClauseQuoteDefault(2, success, "proof");
      }      
      fprintf(GlobalOut, "\n# Proof found!\n");
      if(!proofstate->status_reported)
      {
         TSTPOUT(GlobalOut, neg_conjectures?"Theorem":"Unsatisfiable");
         proofstate->status_reported = true;
         retval = PROOF_FOUND;
      }      
      if(BuildProofObject)
      {
         DerivationComputeAndPrint(GlobalOut,
                                   proofstate->extract_roots,
                                   proofstate->signature,
                                   proof_graph);
      }
   }
   else if(proofstate->watchlist && ClauseSetEmpty(proofstate->watchlist))
   {      
      ProofStatePropDocQuote(GlobalOut, OutputLevel, 
			     CPSubsumesWatch, proofstate, 
			     "final_subsumes_wl");
      fprintf(GlobalOut, "\n# Watchlist is empty!\n");
      TSTPOUT(GlobalOut, "ResourceOut"); 
      retval = RESOURCE_OUT;
   }
   else
   {
      if(out_of_clauses&&
	 proofstate->state_is_complete&&
	 (inf_sys_complete || assume_inf_sys_complete))
      {
	 finals_state = "final";
      }
      ProofStatePropDocQuote(GlobalOut, OutputLevel, CPIgnoreProps,
			     proofstate, finals_state);

      if(cnf_only)
      {
         fprintf(GlobalOut, "\n# CNFization successful!\n");	    
         TSTPOUT(GlobalOut, "Unknown");
      }
      else if(out_of_clauses)
      {
	 if(!(inf_sys_complete || assume_inf_sys_complete))
	 {
	    fprintf(GlobalOut, 
		    "\n# Clause set closed under "
		    "restricted calculus!\n");
            if(!SilentTimeOut)
            {
               TSTPOUT(GlobalOut, "GaveUp");
            }
            retval = INCOMPLETE_PROOFSTATE;
	 }
	 else if(proofstate->state_is_complete && inf_sys_complete)
	 {
	    fprintf(GlobalOut, "\n# No proof found!\n");
	    TSTPOUT(GlobalOut, neg_conjectures?"CounterSatisfiable":"Satisfiable");
            sat_status = "Saturation";
            retval = SATISFIABLE;
	 }
	 else
	 {
	    fprintf(GlobalOut, "\n# Failure: Out of unprocessed clauses!\n");	    
            if(!SilentTimeOut)
            {           
               TSTPOUT(GlobalOut, "GaveUp");	    
            }
            retval = INCOMPLETE_PROOFSTATE;
	 }
      }
      else 
      {
	 fprintf(GlobalOut, "\n# Failure: User resource limit exceeded!\n");
         if(!SilentTimeOut)
         {
            TSTPOUT(GlobalOut, "ResourceOut");
         }
         retval = RESOURCE_OUT;
      }
      if(BuildProofObject && 
         (retval!=INCOMPLETE_PROOFSTATE)&&
         (retval!=RESOURCE_OUT))
      {
         ClauseSetPushClauses(proofstate->extract_roots, 
                              proofstate->processed_pos_rules);
         ClauseSetPushClauses(proofstate->extract_roots,
                              proofstate->processed_pos_eqns);
         ClauseSetPushClauses(proofstate->extract_roots,
                              proofstate->processed_neg_units);
         ClauseSetPushClauses(proofstate->extract_roots,
                              proofstate->processed_non_units);
         if(cnf_only)
         {
            ClauseSetPushClauses(proofstate->extract_roots, 
                                 proofstate->unprocessed);
            print_sat = false;
         }
         DerivationComputeAndPrint(GlobalOut,
                                   proofstate->extract_roots,
                                   proofstate->signature,
                                   proof_graph);
      }

   }
   /* ClauseSetDerivationStackStatistics(proofstate->unprocessed); */
   if(print_sat)
   {
      if(proofstate->non_redundant_deleted)
      {
	 fprintf(GlobalOut, "\n# Saturated system is incomplete!\n");
      }
      if(success)
      {
	 fprintf(GlobalOut, "# Saturated system contains the empty clause:\n");
	 ClausePrint(GlobalOut, success, true);
	 fputc('\n',GlobalOut);	 
	 fputc('\n',GlobalOut);	 
      }
      ProofStatePrintSelective(GlobalOut, proofstate, outdesc,
			       outinfo);
      fprintf(GlobalOut, "\n");
   }	 
   
   if(success)
   {
      ClauseFree(success);
   }
   fflush(GlobalOut);

   print_proof_stats(proofstate,
                     parsed_ax_no, 
                     relevancy_pruned, 
                     raw_clause_no, 
                     preproc_removed);
#ifndef FAST_EXIT
#ifdef FULL_MEM_STATS
   fprintf(GlobalOut,
	   "# sizeof TermCell     : %ld\n"
	   "# sizeof EqnCell      : %ld\n"
	   "# sizeof ClauseCell   : %ld\n"
	   "# sizeof PTreeCell    : %ld\n"
	   "# sizeof PDTNodeCell  : %ld\n"
	   "# sizeof EvalCell     : %ld\n"
	   "# sizeof ClausePosCell: %ld\n"
	   "# sizeof PDArrayCell  : %ld\n",
	   sizeof(TermCell),
	   sizeof(EqnCell),
	   sizeof(ClauseCell),
	   sizeof(PTreeCell),
	   sizeof(PDTNodeCell),
	   sizeof(EvalCell),
	   sizeof(ClausePosCell),
	   sizeof(PDArrayCell));	
   fprintf(GlobalOut, "# Estimated memory usage: %ld\n",
	   ProofStateStorage(proofstate));
   MemFreeListPrint(GlobalOut);
#endif
   ProofControlFree(proofcontrol);
#endif
cleanup1:
#ifndef FAST_EXIT
   ProofStateFree(proofstate);
   CLStateFree(state);
   PStackFree(hcb_definitions);
   PStackFree(wfcb_definitions);
   FVIndexParmsFree(fvi_parms);
   HeuristicParmsFree(h_parms);
#ifdef FULL_MEM_STATS
   MemFreeListPrint(GlobalOut);
#endif
#endif
   if(print_rusage && !SilentTimeOut)
   {
      PrintRusage(GlobalOut);
   }
#ifdef CLB_MEMORY_DEBUG
   RegMemCleanUp();
   MemFlushFreeList();
   MemDebugPrintStats(stdout);
#endif
   OutClose(GlobalOut);
   return retval;
}
void CThirdPlayerActorSkinned::UpdateAnim(void)
{
	float ifps = Game::get()->getIFps()* 4.0f;

	enum
	{
		STATE_FORWARD = 0,
		STATE_BACKWARD,
		STATE_MOVE_LEFT,
		STATE_MOVE_RIGHT,
		STATE_TURN_UP,
		STATE_TURN_DOWN,
		STATE_TURN_LEFT,
		STATE_TURN_RIGHT,
		STATE_CROUCH,
		STATE_JUMP,
		STATE_RUN,
		STATE_USE,
		STATE_FIRE,
		NUM_STATES,
	};

	//jump
	if (m_playerActor->getState(STATE_JUMP))
	{
		m_jump += ifps;
	}
	else
	{
		m_jump -= ifps;
	}
	m_jump = Saturate(m_jump);
	//run & walk
	if (m_playerActor->getState(STATE_RUN))
	{
		INCREASE(m_run);
		DECREASE(m_walk);
	}
	else
	{
		DECREASE(m_run);
		INCREASE(m_walk);
	}
	m_run = Saturate(m_run);
	m_walk = Saturate(m_walk);

	//turn
	ADJUST_PARAM(m_turnLeft, m_turnRight, STATE_TURN_LEFT, STATE_TURN_RIGHT);
	//walk straight
	ADJUST_PARAM(m_moveForward, m_moveBackward, STATE_FORWARD, STATE_BACKWARD);
	//walk side
	ADJUST_PARAM(m_moveLeft, m_moveRight, STATE_MOVE_LEFT, STATE_MOVE_RIGHT);

	//decide playerActor's state
	int jumpState = 0;
	int turnState = 0;
	int walkFBState = 0;
	int walkLRState = 0;

	if (m_jump > 0)
	{
		jumpState = 1;
	}

	if (m_turnLeft > m_turnRight)
	{
		turnState = 1;
	}
	else if (m_turnLeft < m_turnRight)
	{
		turnState = 2;
	}

	if (m_moveForward > m_moveBackward)
	{
		walkFBState = 1;
	}
	else if (m_moveForward < m_moveBackward)
	{
		walkFBState = 2;
	}

	if (m_moveLeft > m_moveRight)
	{
		walkLRState = 1;
	}
	else if (m_moveLeft < m_moveRight)
	{
		walkLRState = 2;
	}

	//calculate state weight
	float idleWeight = 1;
	float jumpWeight = 0;
	float frontWeight = 0;
	float sideWeight = 0;

	jumpWeight = m_jump;
	frontWeight = (1.0 - jumpWeight)*((walkFBState == 1) ? m_moveForward : ((walkFBState == 2) ? m_moveBackward : 0));
	sideWeight = (1.0 - jumpWeight)*((walkLRState == 1) ? m_moveLeft : ((walkLRState == 2) ? m_moveRight : 0));
	frontWeight = Saturate(frontWeight - sideWeight);
	idleWeight = (1.0 - jumpWeight)*Saturate(idleWeight - frontWeight - sideWeight);

	//play animation on 7 layers according to the states and values
	float time = Game::get()->getTime();

	m_meshPlayer->setLayer(0, 1, m_jump);
	
	if (m_meshPlayer->getLayerWeight(0) > EPSILON)
	{
		SetFrame(m_meshPlayer, 0, STATE_WALK_JUMP, STATE_JUMP);
	}

	m_meshPlayer->setLayer(1, 1, m_walk*frontWeight);
	if (m_meshPlayer->getLayerWeight(1) > EPSILON)
	{
		if (walkFBState == 1)
		{
			SetFrame(m_meshPlayer, 1, STATE_WALK_FORWARD, STATE_FORWARD);
		}
		else if (walkFBState == 2)
		{
			SetFrame(m_meshPlayer, 1, STATE_WALK_BACKWARD, STATE_BACKWARD);
		}
	}

	m_meshPlayer->setLayer(2, 1, idleWeight);
	if (m_meshPlayer->getLayerWeight(2) > EPSILON)
	{
		m_meshPlayer->setAnimation(2, (animations[STATE_WALK_IDLE - STATE_WALK_IDLE]).c_str());
		m_meshPlayer->setFrame(2, time*fps[STATE_WALK_IDLE]);
	}

	m_meshPlayer->setLayer(3, 1, m_walk*sideWeight);
	if (m_meshPlayer->getLayerWeight(3) > EPSILON)
	{
		if (walkLRState == 1)
		{
			SetFrame(m_meshPlayer, 3, STATE_WALK_MOVE_LEFT, STATE_MOVE_LEFT);			
		}
		else if (walkLRState == 2)
		{
			SetFrame(m_meshPlayer, 3, STATE_WALK_MOVE_RIGHT, STATE_MOVE_RIGHT);			
		}
	}

	m_meshPlayer->setLayer(5, 1, m_run*frontWeight);
	if (m_meshPlayer->getLayerWeight(5) > EPSILON)
	{
		if (walkFBState == 1)
		{
			SetFrame(m_meshPlayer, 5, STATE_RUN_FORWARD, STATE_FORWARD);			
		}
		else if (walkFBState == 2)
		{
			SetFrame(m_meshPlayer, 5, STATE_RUN_BACKWARD, STATE_BACKWARD);			
		}
	}

	m_meshPlayer->setLayer(6, 1, m_run*sideWeight);
	if (m_meshPlayer->getLayerWeight(6) > EPSILON)
	{
		if (walkLRState == 1)
		{
			SetFrame(m_meshPlayer, 6, STATE_RUN_MOVE_LEFT, STATE_MOVE_LEFT);			
		}
		else if (walkLRState == 2)
		{
			SetFrame(m_meshPlayer, 6, STATE_RUN_MOVE_RIGHT, STATE_MOVE_RIGHT);			
		}
	}
}
Пример #29
0
void retro_run (void)
{
   struct LayoutData layout;
   bool updated                  = false;
   bool have_touch               = false;

   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated)
   {
      check_variables(false);
      struct retro_system_av_info new_av_info;
      retro_get_system_av_info(&new_av_info);

      environ_cb(RETRO_ENVIRONMENT_SET_GEOMETRY, &new_av_info);
   }

   poll_cb();
   get_layout_params(current_layout, screen_buf, &layout);

   if(pointer_device != 0)
   {
      int16_t analogX = 0;
      int16_t analogY = 0;

      float final_acceleration = analog_stick_acceleration * (1.0 + (float)analog_stick_acceleration_modifier / 100.0);

      if(pointer_device == 1)
      {
         analogX = input_cb(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_X) / final_acceleration;
         analogY = input_cb(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_Y) / final_acceleration;
      } 
      else if(pointer_device == 2)
      {
         analogX = input_cb(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_X) / final_acceleration;
         analogY = input_cb(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_Y) / final_acceleration;
      }
      else
      {
         analogX = 0;
         analogY = 0;
      }


      // Convert cartesian coordinate analog stick to polar coordinates
      double radius = sqrt(analogX * analogX + analogY * analogY);
      double angle = atan2(analogY, analogX);
      double max = (float)0x8000/analog_stick_acceleration;

      //log_cb(RETRO_LOG_DEBUG, "%d %d.\n", analogX,analogY);
      //log_cb(RETRO_LOG_DEBUG, "%d %d.\n", radius,analog_stick_deadzone);
      if (radius > (float)analog_stick_deadzone*max/100)
      {
         // Re-scale analog stick range to negate deadzone (makes slow movements possible)
         radius = (radius - (float)analog_stick_deadzone*max/100)*((float)max/(max - (float)analog_stick_deadzone*max/100));

         // Convert back to cartesian coordinates
         analogX = (int32_t)round(radius * cos(angle));
         analogY = (int32_t)round(radius * sin(angle));
      }
      else
      {
         analogX = 0;
         analogY = 0;
      }
      //log_cb(RETRO_LOG_DEBUG, "%d %d.\n", GPU_LR_FRAMEBUFFER_NATIVE_WIDTH,GPU_LR_FRAMEBUFFER_NATIVE_HEIGHT);
      //log_cb(RETRO_LOG_DEBUG, "%d %d.\n", analogX,analogY);

      have_touch = have_touch || input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R2); 

      TouchX = Saturate(0, (GPU_LR_FRAMEBUFFER_NATIVE_WIDTH-1), TouchX + analogX);
      TouchY = Saturate(0, (GPU_LR_FRAMEBUFFER_NATIVE_HEIGHT-1), TouchY + analogY);

      FramesWithPointer = (analogX || analogY) ? FramesWithPointerBase : FramesWithPointer;

   }

   if(mouse_enable)
   {
      // TOUCH: Mouse
      if(!touchEnabled)
      {
         const int16_t mouseX = input_cb(1, RETRO_DEVICE_MOUSE, 0, RETRO_DEVICE_ID_MOUSE_X);
         const int16_t mouseY = input_cb(1, RETRO_DEVICE_MOUSE, 0, RETRO_DEVICE_ID_MOUSE_Y);
         have_touch           = have_touch || input_cb(1, RETRO_DEVICE_MOUSE, 0, RETRO_DEVICE_ID_MOUSE_LEFT);

         TouchX = Saturate(0, (GPU_LR_FRAMEBUFFER_NATIVE_WIDTH-1), TouchX + mouseX);
         TouchY = Saturate(0, (GPU_LR_FRAMEBUFFER_NATIVE_HEIGHT-1), TouchY + mouseY);
         FramesWithPointer = (mouseX || mouseY) ? FramesWithPointerBase : FramesWithPointer;
      }
      // TOUCH: Pointer
      else if(input_cb(0, RETRO_DEVICE_POINTER, 0, RETRO_DEVICE_ID_POINTER_PRESSED))
      {
         const float X_FACTOR = ((float)layout.width / 65536.0f);
         const float Y_FACTOR = ((float)layout.height / 65536.0f);

         float x = (input_cb(0, RETRO_DEVICE_POINTER, 0, RETRO_DEVICE_ID_POINTER_X) + 32768.0f) * X_FACTOR;
         float y = (input_cb(0, RETRO_DEVICE_POINTER, 0, RETRO_DEVICE_ID_POINTER_Y) + 32768.0f) * Y_FACTOR;

         if ((x >= layout.touch_x) && (x < layout.touch_x + GPU_LR_FRAMEBUFFER_NATIVE_WIDTH) &&
               (y >= layout.touch_y) && (y < layout.touch_y + GPU_LR_FRAMEBUFFER_NATIVE_HEIGHT))
         {
            have_touch = true;

            TouchX = x - layout.touch_x;
            TouchY = y - layout.touch_y;
         }
      }
   }

   if(have_touch)
      NDS_setTouchPos(TouchX, TouchY, scale);
   else
      NDS_releaseTouch();

   // BUTTONS
   //NDS_beginProcessingInput();

   NDS_setPad(
         input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT),
         input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT),
         input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN),
         input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP),
         input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT),
         input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START),
         input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B),
         input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A),
         input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y),
         input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X),
         input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L),
         input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R),
         0, // debug
         input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L2) //Lid
         );

   if (!microphone_force_enable)
   {
      if(input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3))
         NDS_setMic(true);
      else if(!input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3))
         NDS_setMic(false);
   }
   else
      NDS_setMic(true);


   if(input_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3) && quick_switch_enable && delay_timer == 0)
   {
      switch (current_layout)
      {
         case LAYOUT_TOP_ONLY:
            current_layout = LAYOUT_BOTTOM_ONLY;
            break;
         case LAYOUT_BOTTOM_ONLY:
            current_layout = LAYOUT_TOP_ONLY;
            break;
      }
      delay_timer++;
   }

   if(delay_timer != 0)
   {
      delay_timer++;
      if(delay_timer == 30)
         delay_timer = 0;
   }

   NDS_endProcessingInput();

   // RUN
   frameIndex ++;
   bool skipped = frameIndex <= frameSkip;

   if (skipped)
      NDS_SkipNextFrame();

   NDS_exec();
   SPU_Emulate_user();

   if (!skipped)
   {
      u16 *screen = GPU->GetCustomFramebuffer();
      if (layout.draw_screen1)
         SwapScreen (layout.dst,  screen, layout.pitch);
      if (layout.draw_screen2)
      {
         screen = GPU->GetCustomFramebuffer() + GPU_LR_FRAMEBUFFER_NATIVE_WIDTH * GPU_LR_FRAMEBUFFER_NATIVE_HEIGHT;
         SwapScreen (layout.dst2, screen, layout.pitch);
         DrawPointer(layout.dst2, layout.pitch);
      }
   }

   video_cb(skipped ? 0 : screen_buf, layout.width, layout.height, layout.pitch * 2);

   frameIndex = skipped ? frameIndex : 0;
}
Пример #30
0
void Firnplayer::Player::DrawArtists()
{
  ArtistView.DrawFrame();
  int TotalHeight = ArtistView.GetHeight();
  int ActiveLine = 0;

  if(!TotalHeight)
    return;

  { double TopBottomBuffer = Options["Layout Settings"]["TopBottomBuffer"].asDouble();
    Saturate(PositionInArtists, (unsigned int)(TotalHeight * TopBottomBuffer + 1),
                               (unsigned int)(TotalHeight * (1 - TopBottomBuffer)));
  }

  AccessQueue::QueueToken ArtistsToken = ArtistsQueue.Lock(false, 50);

  std::pair<std::string, std::string> ListPosition = Artists.GetCurrentPosition();
  std::vector<std::string> StringsToPrint;
  if(ListPosition.first.size())
  {
    // First, get the lines from the top of the screen to the current selection.
    // This is done reversely.
    do
    {
      StringsToPrint.insert(StringsToPrint.begin(), Artists.PosToString(ListPosition));
    } while((StringsToPrint.size() < PositionInArtists) && Artists.MoveUp(ListPosition));
    ActiveLine = StringsToPrint.size() - 1;

    // Remember the topmost position in case we need it later (We will).
    auto TopMostPosition = ListPosition;
    
    ListPosition = Artists.GetCurrentPosition();
    if((StringsToPrint.size() < TotalHeight) && Artists.MoveDown(ListPosition))
    {
      // Get the lines below the current line.
      do
      {
        StringsToPrint.push_back(Artists.PosToString(ListPosition));
      } while((StringsToPrint.size() <= TotalHeight - 1) && Artists.MoveDown(ListPosition));
    }
    // Now that we have these strings, make sure that we are filling all the way to the bottom.  If we are not,
    // we want to move things down until we are.
    while(StringsToPrint.size() < TotalHeight && Artists.MoveUp(TopMostPosition))
    {
      StringsToPrint.insert(StringsToPrint.begin(), Artists.PosToString(TopMostPosition));
      ActiveLine++;
    }
      
    int CurrentString = 0;
    for(; CurrentString < StringsToPrint.size(); CurrentString++)
    {
      ArtistView.Write(0, CurrentString, -1, A_NORMAL,
                       (CurrentString == ActiveLine && ActiveViewPort == ACTIVE_ARTISTS) ? COLPAIR_LISTLINE:
                       (CurrentString == ActiveLine) ? COLPAIR_ACTLINE : COLPAIR_NORMAL,
                        StringsToPrint[CurrentString].c_str());
    }
    for(; CurrentString < TotalHeight; CurrentString++)
      ArtistView.Write(0, CurrentString, -1, A_NORMAL, 2, "");
  }
  else
    return;
}