Exemple #1
1
    Hit intersect(const Ray& ray)
    {
        float3 diff = ray.origin - center;
        double a = ray.dir.dot(ray.dir);
        double b = diff.dot(ray.dir) * 2.0;
        double c = diff.dot(diff) - radius * radius;
 
        double discr = b * b - 4.0 * a * c;
        if ( discr < 0 ) 
            return Hit();
        double sqrt_discr = sqrt( discr );
        double t1 = (-b + sqrt_discr)/2.0/a;
        double t2 = (-b - sqrt_discr)/2.0/a;
 
		float t = (t1<t2)?t1:t2;
		if(t < 0)
			t = (t1<t2)?t2:t1;
		if (t < 0)
            return Hit();

		Hit h;
		h.t = t;
		h.material = material;
		h.position = ray.origin + ray.dir * t;
		h.normal = h.position - center;
		h.normal.normalize();

		return h;

    }
Hit RayTracer::rayIntersectTriangles(const Vec3f& orig, const Vec3f& dir, int startPrim, int endPrim) const
{
	float umin = 0.0f, vmin = 0.0f, tmin = 1.0f;
	int imin = -1;

	// naive loop over all triangles
	for ( int i = startPrim; i <= endPrim; ++i )
	{
		float t = std::numeric_limits<float>::max(), u, v;
		if ( intersect_triangle1( &orig.x,
								  &dir.x,
								  &(*m_triangles)[i].m_vertices[0]->x,
								  &(*m_triangles)[i].m_vertices[1]->x,
								  &(*m_triangles)[i].m_vertices[2]->x,
								  t, u, v ) )
		{
			if ( t > 0.0f && t < tmin )
			{
				imin = i;
				tmin = t;
				umin = u;
				vmin = v;
			}
		}
	}

	if ( imin != -1 )
		return Hit(&(*m_triangles)[imin], orig + tmin*dir, tmin, umin, vmin);
	else
		return Hit(NULL);
}
// Main function that executes the blackjack game with a new player
void CBlackJack::StartGameWithNewPlayer()
{
  bool playAgain = true;
  PrintHandBeginsMessage(Player.GetName(), Player.GetChips());

  while(playAgain)
    {
      // Ask player for a wager. It returns true if valid wager is returned
      if(GetSetPlayerWager())
	{
	  // Hit the player twice 
	  Hit(Player);
	  Hit(Player);
	  DEBUG_LOG (4, "Hit Player twice");
	  if(Player.IsBlackjack())
	    PrintResult(PLAYER_BLACKJACK, Player.GetName(), 0);

	  // Hit dealer twice
	  Hit(Dealer);
	  Hit(Dealer);
	  DEBUG_LOG (4, "Hit Dealer twice");
	  if(Dealer.IsBlackjack())
	    PrintResult(DEALER_BLACKJACK, Dealer.GetName(), 0);

	  // If dealer or player got blackjack or busted, then game can end here. 
	  // Else, continue playing
	
	  if(!Player.IsBlackjack() && !Player.IsBusted()
	     && !Dealer.IsBlackjack() && !Dealer.IsBusted())
	    {
	      // Display scores
	      Player.PrintScore();
	      Dealer.PrintScore();

	      // Give playing options to player and play
	      PlayerOptionsAndPlay();
	      // Unless player is busted, continue hitting the dealer
	      if(!Player.IsBusted())
		DealerOptionsAndPlay();				
	    }
			
	  // At the end, check for winner, and calculate payout
	  CheckWinnerCalculatePayout();
	}

      // Ask player for another game
      playAgain = EndOption();

    } // end while playAgain

  // Add player's score to high scores
  DEBUG_LOG(1, "Remaining chips " << Player.GetChips());
  HighScoreHandler.AddNewScore(Player.GetName(), Player.GetChips());

  // Reset remaining chips with player
  Player.Reset();

  PrintHandQuitMessage();
}
Exemple #4
0
Hit RenderDevice::rayTraceNode(const Ray &ray, u32 nodeIndex)
{
    // Handle Leaf
    if(nodes[nodeIndex].isLeaf())
    {
        f32 hit;
        f32 closestHit = MAXFLOAT;
        u32 triangleIndex=0;
        vec3 hitBaryCoords;
        vec3 baryCoords;

        for(u32 i=nodes[nodeIndex].getIndex(); i < nodes[nodeIndex].getIndex()+nodes[nodeIndex].getSize(); ++i)
        {
            if(i != ray.originID) {
                hit = rayVsTriangle(ray,faces[i],hitBaryCoords);
                if(hit > 0.0 && hit < closestHit)
                {
                    closestHit = hit;
                    triangleIndex = i;
                    baryCoords = hitBaryCoords;
                }
            }
        }
        if(closestHit < MAXFLOAT)
        {
            return Hit(closestHit, triangleIndex, baryCoords);
        }
    }
    else
    {
        Hit leaf_left_hit(MAXFLOAT,0);
        Hit leaf_right_hit(MAXFLOAT,0);

		if(rayVsAABB(ray,nodes[nodes[nodeIndex].getLeft()].aabb) < MAXFLOAT) {
            leaf_left_hit = rayTraceNode(ray,nodes[nodeIndex].getLeft());
		}
		if(rayVsAABB(ray,nodes[nodes[nodeIndex].getRight()].aabb) < MAXFLOAT) {
            leaf_right_hit = rayTraceNode(ray,nodes[nodeIndex].getRight());
		}

		if(leaf_left_hit < leaf_right_hit) {
			return leaf_left_hit;
		} else if (leaf_right_hit.distance < MAXFLOAT) {
			return leaf_right_hit;
		}
    }
    return Hit(MAXFLOAT,0);
}
//-----------------------------------------------------------------------------
// Animation event handlers
//-----------------------------------------------------------------------------
void CWeaponZMFists::HandleAnimEventMeleeHit( CBaseCombatCharacter *pOperator )
{
	//do the trace stuff here so we can pass it to the Hit() function
	trace_t traceHit;

	// Try a ray
	CBasePlayer *pOwner = ToBasePlayer(pOperator);
	if ( !pOwner )
		return;

	Vector swingStart = pOwner->Weapon_ShootPosition( );
	Vector forward;

	pOwner->EyeVectors( &forward, NULL, NULL );

	Vector swingEnd = swingStart + forward * GetRange();

#ifndef CLIENT_DLL
	CHL2MP_Player *pPlayer = ToHL2MPPlayer( GetPlayerOwner() );
	// Move other players back to history positions based on local player's lag
	lagcompensation->StartLagCompensation( pPlayer, pPlayer->GetCurrentCommand() );
#endif
	UTIL_TraceLine( swingStart, swingEnd, MASK_SHOT_HULL, pOwner, COLLISION_GROUP_NONE, &traceHit );
	Hit( traceHit, ACT_VM_HITCENTER);
#ifndef CLIENT_DLL
	// Move other players back to history positions based on local player's lag
	lagcompensation->FinishLagCompensation( pPlayer );
#endif
}
AActor* USCarryObjectComponent::GetActorInView()
{
	APawn* PawnOwner = Cast<APawn>(GetOwner());
	AController* Controller = PawnOwner->Controller;
	if (Controller == nullptr)
	{
		return nullptr;
	}

	FVector CamLoc;
	FRotator CamRot;
	Controller->GetPlayerViewPoint(CamLoc, CamRot);

	const FVector TraceStart = CamLoc;
	const FVector Direction = CamRot.Vector();
	const FVector TraceEnd = TraceStart + (Direction * MaxPickupDistance);

	FCollisionQueryParams TraceParams(TEXT("TraceActor"), true, PawnOwner);
	TraceParams.bTraceAsyncScene = true;
	TraceParams.bReturnPhysicalMaterial = false;
	TraceParams.bTraceComplex = false;

	FHitResult Hit(ForceInit);
	GetWorld()->LineTraceSingle(Hit, TraceStart, TraceEnd, ECC_Visibility, TraceParams);

	//DrawDebugLine(GetWorld(), TraceStart, TraceEnd, FColor::Red, false, 1.0f);

	return Hit.GetActor();
}
Hit Plane::intersect(const Ray &ray)
{
	double denom, t, denomAbs;
	Point pos;
	Vector N, vec10 = position0 - position1, vec12 = position2 - position1;
	// calculate normal of plane
	N = vec10.cross(vec12);
	N.normalize();
	
	// calculate denominator and calculate the absolute value
	denom = N.dot(ray.D);
	if (denom < 0){
		denomAbs = denom * -1;
	} else{
		denomAbs = denom;
	}
	// if the absolute value < epsilon, no hit
	if (denomAbs > 1e-6) {
		// calculate distance to possible intersection
		t = (position0-ray.O).dot(N)/denom;
		// point of intersection
		pos = ray.O + ray.D*t;
		
		// if t is negative, no intersection
		if (t<0 )  return Hit::NO_HIT();
		// if the plane is set to finite, the intersection is compared to min and max coordinates. If it is too big or small, not hit
		#ifdef FINITE
		if(!(pos.x >= minX && pos.x <= maxX) || !(pos.y >= minY && pos.y <= maxY) || !(pos.z >= minZ && pos.z <= maxZ)) return Hit::NO_HIT();
		#endif
	}else{
		return Hit::NO_HIT();
	}
    return Hit(t,N);
}
void Player::HandleCollision(Sprite* sprite, Level* level) {
    ActionType hitAction;
    
    if (currAction == STAND) {
        hitAction = prevAction;
    } else {
        hitAction = currAction;
    }
    
    if (attacking) {
        sound.setBuffer(hit);
        sprite->Hit(hitAction, level);
    }
    else {
        if (dynamic_cast<Princess*>(sprite)) {
            sound.setBuffer(kiss);
            level->SetStatus(Level::COMPLETE);
        } else {
            sound.setBuffer(no);
            Hit(sprite->GetAction(), level);
        }
    }
    
    sound.play();
}
AInventoryItem* APlayerCharacter::GetUsableItemInView()
{
	FVector camLoc;
	FRotator camRot;

	if (Controller == NULL)
		return NULL;

	Controller->GetPlayerViewPoint(camLoc, camRot);
	const FVector start_trace = camLoc;
	const FVector direction = camRot.Vector();
	const FVector end_trace = start_trace + (direction * MaxUseDist);

	FCollisionQueryParams TraceParams(FName(TEXT("")), true, this);
	TraceParams.bTraceAsyncScene = true;
	TraceParams.bReturnPhysicalMaterial = false;
	TraceParams.bTraceComplex = true;

	FHitResult Hit(ForceInit);
	GetWorld()->LineTraceSingleByChannel(Hit, start_trace, end_trace, ECollisionChannel::ECC_EngineTraceChannel1, TraceParams);

	//DrawDebugLine(GetWorld(), start_trace, end_trace, FColor(255, 0, 0), false, -1, 0, 12.333);

	return Cast<AInventoryItem>(Hit.GetActor());
}
AUsableActor* AXtremeJanitorCharacter::GetUsableInView()
{
	FVector CamLoc;
	FRotator CamRot;

	if (Controller == NULL)
		return NULL;

	Controller->GetPlayerViewPoint(CamLoc, CamRot);
	const FVector TraceStart = CamLoc;
	const FVector Direction = CamRot.Vector();
	const FVector TraceEnd = TraceStart + (Direction * MaxUseDistance);

	FCollisionQueryParams TraceParams(FName(TEXT("TraceUsableActor")), true, this);
	TraceParams.bTraceAsyncScene = true;
	TraceParams.bReturnPhysicalMaterial = false;
	TraceParams.bTraceComplex = true;

	FHitResult Hit(ForceInit);
	GetWorld()->LineTraceSingleByChannel(Hit, TraceStart, TraceEnd, ECC_Visibility, TraceParams);

	// Cette ligne sera en commentaire plus tard
	DrawDebugLine(GetWorld(), TraceStart, TraceEnd, FColor::Red, false, 1.0f);

	return Cast<AUsableActor>(Hit.GetActor());
}
void Fire::Process()
{
    auto enm = GetMap()->GetEnemyHolder()->GetNearest(this->pixel_x(), this->pixel_y(), 7, 
                                                     [this](Enemy* e) 
        /*I AM KING OF SPACES*/                      {
                                                         return !e->IsRocketFriend()
                                                                && e != this;
                                                     });

    ++length_;

    if (enm != nullptr)
    {
        ProcessSpeed(enm->pixel_x(), enm->pixel_y(), 1);
        if ((abs(enm->pixel_x() - pixel_x()) + abs(enm->pixel_y() - pixel_y())) < 48)
        {
            enm->Hit(1);
        }
    }
    ProcessMove();

    state_w_ = (length_ / 5) % 6;

    if (length_ > 30)
        GetMap()->GetEnemyHolder()->AddToDelete(this);
}
Exemple #12
0
const HitList & QueryConnector::evaluateHits(HitList & hl) const
{
    if (evaluate()) {
        hl.push_back(Hit(1, 0, 0, 1));
    }
    return hl;
}
void ATP_TwinStickPawn::Tick(float DeltaSeconds)
{
	// Find movement direction
	const float ForwardValue = GetInputAxisValue(MoveForwardBinding);
	const float RightValue = GetInputAxisValue(MoveRightBinding);

	// Clamp max size so that (X=1, Y=1) doesn't cause faster movement in diagonal directions
	const FVector MoveDirection = FVector(ForwardValue, RightValue, 0.f).GetClampedToMaxSize(1.0f);

	// Calculate  movement
	const FVector Movement = MoveDirection * MoveSpeed * DeltaSeconds;

	// If non-zero size, move this actor
	if (Movement.SizeSquared() > 0.0f)
	{
		const FRotator NewRotation = Movement.Rotation();
		FHitResult Hit(1.f);
		RootComponent->MoveComponent(Movement, NewRotation, true, &Hit);
		
		if (Hit.IsValidBlockingHit())
		{
			const FVector Normal2D = Hit.Normal.GetSafeNormal2D();
			const FVector Deflection = FVector::VectorPlaneProject(Movement, Normal2D) * (1.f - Hit.Time);
			RootComponent->MoveComponent(Deflection, NewRotation, true);
		}
	}
	
	// Create fire direction vector
	const float FireForwardValue = GetInputAxisValue(FireForwardBinding);
	const float FireRightValue = GetInputAxisValue(FireRightBinding);
	const FVector FireDirection = FVector(FireForwardValue, FireRightValue, 0.f);

	// Try and fire a shot
	FireShot(FireDirection);
}
Exemple #14
0
Hit BVH::BVHLeaf::trace(const AABB_Ray & aabb_ray, const Ray & ray, Amount minT)
{
   if(object.bounds.intersect(aabb_ray)){
      return object.geometry->intersectTransform(ray,minT);
   }
   return Hit(ray);
}
// does the recursive (shadow rays & recursive/glossy rays) work
Vec3f RayTracer::TraceRay(const Ray &ray, Hit &hit, int bounce_count) const
{
        hit = Hit();
        bool intersect = CastRay(ray,hit,false);

        Vec3f answer(args->background_color_linear);

        if (intersect == true) {
                const Material *m = hit.getMaterial();
                assert (m != NULL);

                // rays coming from the light source are set to white, don't bother to ray trace further.
                if (m->getEmittedColor().Length() > 0.001) {
                        answer = Vec3f(1,1,1);
                } else {
                        // ambient light
                        answer = args->ambient_light_linear *
                                 m->getDiffuseColor(hit.get_s(),hit.get_t());

                        // Shadows
                        answer += shadows(ray, hit);

                        // Reflections
                        Vec3f reflectiveColor = m->getReflectiveColor();
                        double roughness = m->getRoughness();
                        if (bounce_count > 0 && reflectiveColor.Length() > MIN_COLOR_LEN) {
                        	answer += reflectiveColor * reflections(ray, hit, bounce_count, roughness);
                        }
                }
        }

        return answer;
}
Hit ComplexObject::intersectBoundingBox(Vec3Df origin, Vec3Df dest) {
  // Our implementation is based on the ray-box intersection algorithm
  // as proposed here: http://people.csail.mit.edu/amy/papers/box-jgt.pdf

  // This section should be stored in a ray datastructure where it's cached
  Vec3Df direction = dest - origin;
  Vec3Df inverseDirection = Vec3Df(1/direction[0], 1/direction[1], 1/direction[2]);
  int sign[3];
  sign[0] = (inverseDirection[0] < 0);
  sign[1] = (inverseDirection[1] < 0);
  sign[2] = (inverseDirection[2] < 0);

  // Intersection algorithm
  float xMin, yMin, zMin, xMax, yMax, zMax;
  xMin = (bounds[  sign[0]  ][0] - origin[0]) * inverseDirection[0];
  xMax = (bounds[ 1-sign[0] ][0] - origin[0]) * inverseDirection[0];
  yMin = (bounds[  sign[1]  ][1] - origin[1]) * inverseDirection[1];
  yMax = (bounds[ 1-sign[1] ][1] - origin[1]) * inverseDirection[1];
  zMin = (bounds[  sign[2]  ][2] - origin[2]) * inverseDirection[2];
  zMax = (bounds[ 1-sign[2] ][2] - origin[2]) * inverseDirection[2];
  if ( (xMin > yMax) || (yMin > xMax) ) return noHit;
  if (yMin > xMin) xMin = yMin;
  if (yMax < xMax) xMax = yMax;
  if ( (xMin > zMax) || (zMin > xMax) ) return noHit;
  if (zMin > xMin) xMin = zMin;
  if (zMax < xMax) xMax = zMax;
  return Hit(1, Vec3Df(xMin, yMin, zMin), nullVector, defaultMaterial);
}
Exemple #17
0
std::vector<Hit>& Scene::getHitList(Ray* ray)
{
#ifdef _DEBUG_SCENE	
	std::cout << "\n+++++++++++++++++++++++++++++++++++++++++++++++++++\n";
	std::cout << "\nFrom: " << __FILE__;
	std::cout << "trying to get hit list\n";
	std::cout << "\n+++++++++++++++++++++++++++++++++++++++++++++++++++\n";
#endif	
	
	// interect all objects and check if there is an intersection and store result in hit list
	for (int i = 0; i < mObjectList.size(); i++) {
		double intersectD = mObjectList[i]->intersectObject(ray);				
		
		if (intersectD != NO_INTERSECTION) {
			vec3 intersectPoint = ray->getRayOrigin() + vec3(ray->getRayDirection().x * intersectD, 
												             ray->getRayDirection().y * intersectD,
													         ray->getRayDirection().z * intersectD);	
													         			
			mHitList.push_back( Hit(mObjectList[i], intersectD, intersectPoint) );
		} else {		
#ifdef _DEBUG_SCENE	
			std::cout << "\n+++++++++++++++++++++++++++++++++++++++++++++++++++\n";
			std::cout << "\nFrom: " << __FILE__;
			std::cout << "\nObject: " << OBJ_STR[mObjectList[i]->getObjectType()] << " does not intersect!";
			std::cout << "\n+++++++++++++++++++++++++++++++++++++++++++++++++++\n";
#endif			
		}		
	}
	
	return mHitList;
}
Exemple #18
0
ShipBattle::Hits ShipBattle::GetHitsToDestroy(const Group& group, Dice& dice, int toHit) const
{
	const auto shipIndices = GetShipIndicesWeakestFirst(group);

	Hits hits;
	for (int shipIndex : shipIndices)
	{
		int lives = group.lifeCounts[shipIndex];
		Dice used = dice.Remove(lives, toHit);
		if (used.empty())
			break; // Can't destroy any more ships in this group. 

		// We can destroy this ship. 
		int damage = used.GetDamage();
		if (damage > lives) // Don't want to waste damage. Can we destroy a healthier ship? 
		{
			for (int shipIndex2 : shipIndices)
				if (group.lifeCounts[shipIndex2] == damage)
				{
					// We can destroy this one with no waste. 
					shipIndex = shipIndex2;
					lives = damage;
					break;
				}
		}

		hits.push_back(Hit(group.shipType, shipIndex, used));
	}
	return hits;
}
Exemple #19
0
FHitResult UGTTraceBase::SingleLineRangedTrace(const FVector& StartTrace, const FVector& EndTrace)
{
	FHitResult Hit(ForceInit);
	UWorld* world = GetWorld();
	if (!TraceInterface->GetGamePawn())
		return Hit;

	static FName PowerTag = FName(TEXT("SingleLineTrace"));
	FCollisionQueryParams TraceParams(PowerTag, false, TraceInterface->GetGamePawn());
	TraceParams.bTraceComplex = false;
	TraceParams.bTraceAsyncScene = false;
	TraceParams.bReturnPhysicalMaterial = true;
	
	if (bIgnoreSelf)
	{
		TraceParams.AddIgnoredActor(TraceInterface->GetGamePawn());
	}

	bool traceResult = GetWorld()->LineTraceSingle(Hit, StartTrace, EndTrace, TraceParams, CollisionObjectParams);
	if (bDrawDebug)
	{
		if (traceResult && Hit.bBlockingHit)
		{
			::DrawDebugLine(world, StartTrace, Hit.ImpactPoint, FColor::Red, false, 2);
			::DrawDebugLine(world, Hit.ImpactPoint, EndTrace, FColor::Green, false, 2);
			::DrawDebugPoint(world, Hit.ImpactPoint, 7, FColor::Red, false, 2);
		}
		else
		{
			::DrawDebugPoint(world, Hit.ImpactPoint, 15, FColor::Red, false, 2);
		}
	}
	return Hit;
}
AActor* USCarryObjectComponent::GetActorInView()
{
	APawn* PawnOwner = Cast<APawn>(GetOwner());
	AController* Controller = PawnOwner->Controller;
	if (Controller == nullptr)
	{
		return nullptr;
	}

	FVector CamLoc;
	FRotator CamRot;
	Controller->GetPlayerViewPoint(CamLoc, CamRot);

	const FVector TraceStart = CamLoc;
	const FVector Direction = CamRot.Vector();
	const FVector TraceEnd = TraceStart + (Direction * MaxPickupDistance);

	FCollisionQueryParams TraceParams(TEXT("TraceActor"), true, PawnOwner);
	TraceParams.bTraceAsyncScene = true;
	TraceParams.bReturnPhysicalMaterial = false;
	TraceParams.bTraceComplex = false;

	FHitResult Hit(ForceInit);
	GetWorld()->LineTraceSingleByChannel(Hit, TraceStart, TraceEnd, ECC_Visibility, TraceParams);

	/* Check to see if we hit a staticmesh component that has physics simulation enabled */
	UStaticMeshComponent* MeshComp = Cast<UStaticMeshComponent>(Hit.GetComponent());
	if (MeshComp && MeshComp->IsSimulatingPhysics())
	{
		return Hit.GetActor();
	}

	return nullptr;
}
//------------------------------------------------------------------------
bool CMelee::PerformRayTest(const Vec3 &pos, const Vec3 &dir, float strength, bool remote)
{
	IEntity *pOwner = m_pWeapon->GetOwner();
	IPhysicalEntity *pIgnore = pOwner ? pOwner->GetPhysics() : 0;
	ray_hit hit;
	int n = gEnv->pPhysicalWorld->RayWorldIntersection(pos, dir.normalized() * m_pShared->meleeparams.range, ent_all | ent_water,
			rwi_stop_at_pierceable | rwi_ignore_back_faces, &hit, 1, &pIgnore, pIgnore ? 1 : 0);

	//===================OffHand melee (also in PerformCylincerTest)===================
	if(m_ignoredEntity && (n > 0))
	{
		if(IEntity *pHeldObject = gEnv->pEntitySystem->GetEntity(m_ignoredEntity))
		{
			IPhysicalEntity *pHeldObjectPhysics = pHeldObject->GetPhysics();

			if(pHeldObjectPhysics == hit.pCollider)
			{
				return false;
			}
		}
	}

	//=================================================================================

	if (n > 0)
	{
		Hit(&hit, dir, strength, remote);
		Impulse(hit.pt, dir, hit.n, hit.pCollider, hit.partid, hit.ipart, hit.surface_idx, strength);
	}

	return n > 0;
}
/*
Performs ray-trace to find closest looked-at UsableActor.
*/
ASUsableActor* ASCharacter::GetUsableInView()
{
	FVector CamLoc;
	FRotator CamRot;

	if (Controller == nullptr)
		return nullptr;

	Controller->GetPlayerViewPoint(CamLoc, CamRot);
	const FVector TraceStart = CamLoc;
	const FVector Direction = CamRot.Vector();
	const FVector TraceEnd = TraceStart + (Direction * MaxUseDistance);

	FCollisionQueryParams TraceParams(TEXT("TraceUsableActor"), true, this);
	TraceParams.bTraceAsyncScene = true;
	TraceParams.bReturnPhysicalMaterial = false;

	/* Not tracing complex uses the rough collision instead making tiny objects easier to select. */
	TraceParams.bTraceComplex = false;

	FHitResult Hit(ForceInit);
	GetWorld()->LineTraceSingleByChannel(Hit, TraceStart, TraceEnd, ECC_Visibility, TraceParams);

	//DrawDebugLine(GetWorld(), TraceStart, TraceEnd, FColor::Red, false, 1.0f);

	return Cast<ASUsableActor>(Hit.GetActor());
}
Exemple #23
0
LRESULT CWorldLog::OnLButtonDown(WPARAM wParam, LPARAM lParam){
	LRESULT ret = CWSScrollView::OnLButtonDown(wParam,lParam);
 	
    POINTS* p = (POINTS*)(&lParam);

	if(m_ScrollSelected){
		//if(m_SpaceSelected)m_SpaceSelected->m_State &= ~SPACE_SELECTED;
		//m_SpaceSelected = NULL; //when clicked on the Scrollbar, it can not click on other
		return 0;
	}

	POINT point;
	point.x =p->x;
	point.y =p->y;

	CVSpace2* SpaceSelected = Hit(point);

	if(SpaceSelected && SpaceSelected->m_Alias != 0){
		if(m_SpaceSelected)m_SpaceSelected->m_State &= ~SPACE_SELECTED;
		SpaceSelected->m_State |= SPACE_SELECTED;
		m_SpaceSelected = SpaceSelected;
	}	
	Invalidate();
	return 0;
}
ComplexObject::ComplexObject(Mesh mesh) {
  this->mesh = mesh;
  Material defaultMaterial = Material();
  nullVector = Vec3Df(0, 0, 0);
  noHit = Hit(0, nullVector, nullVector, defaultMaterial);
  initBoundingBox();
}
void APawnWithCamera::DoTrace()
{
	FVector Loc = CameraOne->GetActorLocation();
	UE_LOG(LogClass, Error, TEXT("Loc is %s"), *Loc.ToString());
	FRotator Rot = CameraOne->GetActorRotation();
	UE_LOG(LogClass, Error, TEXT("Rot is %s"), *Rot.ToString());
	FVector Start = Loc;
	UE_LOG(LogClass, Error, TEXT("Start is %s"), *Start.ToString());
	FVector End = Loc + (Rot.Vector() * Distance);
	UE_LOG(LogClass, Error, TEXT("End is %s"), *End.ToString());
	TempActor->SetActorLocation(End);

	FCollisionQueryParams TraceParam = FCollisionQueryParams(FName(TEXT("Trace")), true, this);
	TraceParam.bTraceComplex = true;
	TraceParam.bTraceAsyncScene = true;
	TraceParam.bReturnPhysicalMaterial = false;
	TraceParam.AddIgnoredActor(this);

	FHitResult Hit(ForceInit);

	GetWorld()->LineTraceSingle(Hit, Start, End, ECC_Pawn, TraceParam);
	DrawDebugLine(GetWorld(), Start, End, FColor(255, 0, 0), false, -1, 0, 12.33f);

	if (Hit.bBlockingHit)
	{
		UE_LOG(LogClass, Error, TEXT("Hit Something"));
	}
	else
	{
		UE_LOG(LogClass, Error, TEXT("No Hit"));
	}
}
Exemple #26
0
void AGameObject::OnHitContactBegin_Implementation( AActor* OtherActor,
  UPrimitiveComponent* OtherComp, int32 OtherBodyIndex,
  bool bFromSweep, const FHitResult & SweepResult )
{
  //info( FS( "OnHitContactBegin %s with %s", *Name, *OtherActor->GetName() ) );
  if( OtherActor == this )
  {
    // Don't do anything with reports of collision with self.
    return;
  }

  AGameObject* THAT = Cast<AGameObject>( OtherActor );
  if( THAT )
  {
    //info( FS( "HitContactBegin: %s : %s/%s", *GetName(), *OtherActor->GetName(), *OtherComp->GetName() ) );
    if( in( HitOverlaps, THAT ) )
    {
      warning( FS( "HitContactBegin: %s was already overlapped by %s/%s", *GetName(), *OtherActor->GetName(), *OtherComp->GetName() ) );
    }
    else
    {
      // Both were gameobjects
      Hit( THAT );
      HitOverlaps += THAT; // Retain collection of objects i'm overlapping with
    }
  }
  else
  {
    error( FS( "%s", *THAT->GetName() ) );
  }
}
Exemple #27
0
void Enemie3::Move(sf::Sprite &a_Player)
{
    m_Enemie.move(0, 0.2f);
    for(auto it = m_TirList.begin(); it != m_TirList.end(); it++){
        it->Move();
        Hit(a_Player);
    }
}
Exemple #28
0
    Hit intersect(const Ray& ray) {
        // ray in h**o coords
        float4 e = float4(ray.origin.x,
                          ray.origin.y, ray.origin.z, 1);
        float4 d = float4(ray.dir.x,
                          ray.dir.y, ray.dir.z, 0);
        // quadratic coeffs.
        double a = d.dot( A * d );
        double b = e.dot( A * d )
        + d.dot( A * e );
        double c = e.dot( A * e );
        // from here on identical to Sphere
        
        double discr = b * b - 4.0 * a * c;
        if ( discr < 0 )
            return Hit();
        double sqrt_discr = sqrt( discr );
        double t1 = (-b + sqrt_discr)/2.0/a;
        double t2 = (-b - sqrt_discr)/2.0/a;
        
		float t = (t1<t2)?t1:t2;
		if(t < 0)
			t = (t1<t2)?t2:t1;
		if (t < 0)
            return Hit();
        
        Hit h;
        
        h.t = t;
		h.material = material;
		h.position = ray.origin + ray.dir * t;
        
        // h**o position
        float4 hPos = float4(h.position.x,
                             h.position.y, h.position.z, 1);
        // h**o normal per quadric normal formula
        float4 hNormal = A * hPos +  hPos * A;
        // Cartesian normal
        h.normal = float3(hNormal.x, hNormal.y, hNormal.z).normalize();
        
        h.normal.normalize();
        

        
		return h;
    }
void Projectile::Update(float elapsedTime) 
{
	// Test si les conditions de fin du projectile sont vraies
	if (m_timeToLive <= 0 || !m_shot || elapsedTime == 0)
		return;

	// Test si atteint la cible
	if(	abs(m_destination.x - m_pos.x) < m_collisionRadius.x 
		&& abs(m_destination.y - m_pos.y) < m_collisionRadius.y 
		&& abs(m_destination.z - m_pos.z) < m_collisionRadius.z) {
			Hit();
			return;
	}
	Vector3f speed = m_rot * m_speed;
	speed = speed * m_speed.Lenght();
	// Met a jour la valeur de la vitesse en 
	// fonction de l'acceleration et du temps
	m_speed += m_acceleration * elapsedTime;

	m_timeToLive -= elapsedTime;

	// distance entre le projectile et sa destination
	// chemin le plus court
	Vector3f distance;
	distance.x = m_pos.x - m_destination.x;
	distance.y = m_pos.y - m_destination.y;
	distance.z = m_pos.z - m_destination.z;

	// calculer l'angle entre les 2 vecteurs
	// fix imprecision float
	float n = distance.Dot(speed) / (distance.Lenght() * speed.Lenght());
	if (n > 1)
		n = 1;
	else if (n < -1)
		n = -1;
	float angleA = acos(n);
	std::cout << angleA << std::endl;
	Vector3f axis = distance.Cross(speed);
	axis.Normalize();
	// rotation autour de laxe
	float rotation;
	if (abs(angleA) >= m_maxRot && abs(angleA) < PII - m_maxRot) {
		rotation = (angleA > 0) ? -m_maxRot : m_maxRot;
		rotation *= elapsedTime;
	}
	else
		rotation = angleA - PII;
	Quaternion q;
	q.FromAxis(rotation, axis);
	q.Normalise();

	m_rot = q * m_rot;
	m_rot.Normalise();
	
	// calcul la nouvelle position
	m_pos += speed * elapsedTime;
}
void PhotonMapping::TracePhoton(const Vec3f &position, const Vec3f &direction, 
				const Vec3f &energy, int iter) {
  
  if(iter>args->num_bounces){
    return;
  }

  Hit h = Hit();
  Ray R = Ray(position, direction);
  bool intersect = raytracer->CastRay(R, h, false);
  if(!intersect){
    return;
  }
  Material *m = h.getMaterial();
  Vec3f normal = h.getNormal();
  Vec3f point = R.pointAtParameter(h.getT());
  Vec3f opDirec = direction;
  opDirec.Negate();
  opDirec.Normalize();
  Vec3f diffuse = m->getDiffuseColor(), reflec = m->getReflectiveColor();
  double diffuseAnswer = diffuse.x()+diffuse.y()+diffuse.z();
  double reflecAnswer = reflec.x()+reflec.y()+reflec.z();
  double total = reflecAnswer+diffuseAnswer;
  diffuseAnswer /= total;
  reflecAnswer /= total;
  double seed = GLOBAL_mtrand.rand();
  if(seed <= diffuseAnswer && seed >= 0){
    Vec3f newEnergy = energy * diffuse;
    Vec3f newPosition = point;
    Vec3f newDirection = Vec3f(GLOBAL_mtrand.rand(),GLOBAL_mtrand.rand(),GLOBAL_mtrand.rand());
    newDirection.Normalize();
    Photon answer = Photon(point,opDirec,newEnergy,iter+1);
    kdtree->AddPhoton(answer);
    TracePhoton(newPosition, newDirection, newEnergy, iter+1);
  }
  else if(seed>diffuseAnswer && seed <= 1){
    Vec3f newEnergy = energy * reflec;
    Vec3f newPosition = point;
    Vec3f newDirection = direction - 2 * direction.Dot3(normal) * normal;
    Photon answer = Photon(point,opDirec,newEnergy,iter+1);
    kdtree->AddPhoton(answer);
    TracePhoton(newPosition, newDirection, newEnergy, iter+1);
  }
  // ==============================================
  // ASSIGNMENT: IMPLEMENT RECURSIVE PHOTON TRACING
  // ==============================================

  // Trace the photon through the scene.  At each diffuse or
  // reflective bounce, store the photon in the kd tree.

  // One optimization is to *not* store the first bounce, since that
  // direct light can be efficiently computed using classic ray
  // tracing.



}