Example #1
0
void
Camara::Pintar(int ojo)
{
    try
    {
        glLoadIdentity();
        
        if ( objetivo )
        {
            Vector orientacion = objetivo->GetOrientacion();
            
            glRotatef( orientacion.GetX(), 1, 0, 0);
            glRotatef( orientacion.GetY()+(ojo?5:-5), 0, 1, 0);
            
            Vector posicion = objetivo->GetPosicion();

            glTranslatef( -posicion.GetX(), -posicion.GetY()-1, -posicion.GetZ() );
        }
        

    } 
    catch ( Excepcion &ex )
    {
        throw Excepcion(ex, "Camara::Pintar()");
    }
    catch ( exception &ex )
    {
        throw Excepcion(ex, "Camara::Pintar()");
    }
}
Example #2
0
bool	Game::isNaN(Vector v) 
{ 
	if (v.GetX() != v.GetX() || v.GetY() != v.GetY()) {
		return true; 
	}
	else return false; 
}
Example #3
0
void CairoDrawer::DrawLine(const Vector &a, const Vector &b) {
   cairo_new_path(mCairo);
   cairo_set_line_width (mCairo, 1.2);

   cairo_set_source_rgb(mCairo, 1.0, 1.0, 1.0);
   cairo_move_to(mCairo, a.GetX(), a.GetY());
   cairo_line_to(mCairo, b.GetX(), b.GetY());
   cairo_stroke_preserve(mCairo);
}
PhysicsState::PhysicsState(const Vector& pos, const Vector& vel, const Vector& maxvel, const Vector& grav){
	
	posNext = new Vector(pos.GetX(), pos.GetY());
	posPrev = new Vector(pos.GetX(), pos.GetY());
	maxSpeed = new Vector(maxvel.GetX(), maxvel.GetY());
	
	speed = new Vector(vel.GetX(), vel.GetY());
	speedPrev = new Vector(vel.GetX(), vel.GetY());
	
	gravity = new Vector(grav.GetX(), grav.GetY());
    
}
Example #5
0
Puerta::Puerta(Nivel *nivel, int cod, Vector centroCelda, Vector radioCelda, int orien):
    Item(nivel, cod)
{
    float rad = 0.3 ;
    estado = Cerrada ;
    
    posicion = centroCelda ;
    switch (orien)
    {
        case Orientacion::Norte:
            posicion.SetZ( posicion.GetZ() - radioCelda.GetZ() + rad ) ;
            posicion.SetY( posicion.GetY() + 0.8*radioCelda.GetY() );
            radio = Vector( radioCelda.GetX(), 0.8*radioCelda.GetY(), rad);
            break ;
        case Orientacion::Este:
            posicion.SetX( posicion.GetX() + radioCelda.GetX() - rad ) ;
            posicion.SetY( posicion.GetY() + 0.8*radioCelda.GetY() );
            radio = Vector( rad, 0.8*radioCelda.GetY(), radioCelda.GetZ());
            break ;
        case Orientacion::Sur:
            posicion.SetZ( posicion.GetZ() + radioCelda.GetZ() - rad ) ;
            posicion.SetY( posicion.GetY() + 0.8*radioCelda.GetY() );
            radio = Vector( radioCelda.GetX(), 0.8*radioCelda.GetY(), rad);
            break ;
        case Orientacion::Oeste:
            posicion.SetX( posicion.GetX() - radioCelda.GetX() + rad ) ;
            posicion.SetY( posicion.GetY() + 0.8*radioCelda.GetY() );
            radio = Vector( rad, 0.8*radioCelda.GetY(), radioCelda.GetZ());
            break ;
            
    }
    posicionCerrada = posicion ;
    posicionAbierta = posicionCerrada - Vector(0, 1.6*radioCelda.GetY(), 0) ;
    obstaculo = true ;
    orientacion = orien;
    
    
    BITMAP * bitmap = load_bitmap("Texturas\\puerta.bmp", NULL);
    
    if (!bitmap)
    {
        throw Excepcion("No se puedo cargar la textura puerta.bmp");
    }
    
    // Creamos la textura
    glTexPuerta = allegro_gl_make_texture_ex(AGL_TEXTURE_MIPMAP | AGL_TEXTURE_MASKED | AGL_TEXTURE_FLIP | AGL_TEXTURE_RESCALE, bitmap, -1);

}
Example #6
0
void MenuState::Init() {
    releaseMouse = true;
    dialogVisible = false;
    
	LoadResources(); // Cargamos recursos
    
    if(!ConfigurationManager::Instance()->loaded)
        ConfigurationManager::Instance()->LoadConfigurations();
    
    if(!StatusManager::Instance()->loaded)
        StatusManager::Instance()->LoadStatus();
    
    musicPlayer->Play();
	
	// Inicializamos fuentes
	background = new SpriteSheet(resourceManager->GetTexture("texBackground"));
    
    
    // Dialog
    backgroundDialog = new SpriteSheet(resourceManager->GetTexture("texDialogBack"));
    
    Vector posDialog = Vector(
        RenderWindow::Instance()->width/2 - backgroundDialog->getGlobalBounds().GetWidth()/2,
        RenderWindow::Instance()->height/2 - backgroundDialog->getGlobalBounds().GetHeight()/2
    );
    backgroundDialog->SetPosition(posDialog);
    
    
    dialogNo = new ImageButton(posDialog.GetX()+50.f, posDialog.GetY()+100.f, 2, resourceManager->GetTexture("texDialogNo"));
    dialogNo->SetFrame(1);
    dialogYes = new ImageButton(posDialog.GetX()+200.f, posDialog.GetY()+100.f ,2,resourceManager->GetTexture("texDialogYes"));
    
    for(int i=0; i<6; i++)         //  x   ,  y,            contenido
        vButtons->push_back(new Button(512.f, 380.f + 50.f*i, ""));

    
    vButtons->at(0)->SetText("Nueva Partida");
    vButtons->at(1)->SetText("Continuar");
    vButtons->at(2)->SetText("Controles");
    vButtons->at(3)->SetText("Opciones");
    vButtons->at(4)->SetText("Acerca De");
    vButtons->at(5)->SetText("Salir");
    
    for(int i=0; i<6; i++)         //  w , h  ,  x   ,  y,            contenido
        vButtons->at(i)->Center();
    
    requestStateChange = std::make_pair(States::ID::LoadingState,false);
}
void Vector::SetVector(Vector vecV)
{
	this->fX = vecV.GetX();
	this->fY = vecV.GetY();
	this->fZ = vecV.GetZ();
	this->fMag = vecV.GetMagnitude();
}
Example #8
0
void SampleTree::RecursiveOutput(int currNode, int indent) const {
    Indent(indent);

    for (int i = 0; i < 3; i++) {
        if (i) printf(" x ");
        printf("[%lf, %lf]", GetVectorComponent(this->nodes[currNode].lowerPoint, i),
                             GetVectorComponent(this->nodes[currNode].upperPoint, i));
    }
    printf(", population = %d\n", this->nodes[currNode].population);

    if (this->nodes[currNode].sampleList) {
        Indent(indent);
        printf("Leaf:");
        for (int i = 0; i < this->nodes[currNode].population; i++) {
            Vector point = this->samples[this->nodes[currNode].sampleList[i]];
            printf(" (%lf, %lf, %lf)", point.GetX(), point.GetY(), point.GetZ());
        }
        printf("\n");
    } else {
        Indent(indent);
        printf("Non-leaf:\n");
        this->RecursiveOutput(this->nodes[currNode].leftIndex, indent + 4);
        this->RecursiveOutput(this->nodes[currNode].rightIndex, indent + 4);
    }
}
Example #9
0
void CairoDrawer::DrawCircle(const Vector &a, double radius) {
   cairo_new_path(mCairo);
   cairo_set_line_width (mCairo, 1.2);
   cairo_set_source_rgb(mCairo, 1.0, 1.0, 0.5);
   cairo_arc(mCairo, a.GetX(), a.GetY(), radius, 0.0, 2*M_PI);
   cairo_stroke_preserve(mCairo);
}
Example #10
0
void Rectangle::SetCenterAndDimensions(const Vector& centerPoint, float w, float h)
{
    this->vector.SetX(centerPoint.GetX() - w/2.0);
    this->vector.SetY(centerPoint.GetY() - h/2.0);
    this->w = w;
    this->h = h;
}
Example #11
0
void CairoDrawer::DrawText(const Vector &pos, const char *text) {
   cairo_select_font_face (mCairo, "terminus", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
   cairo_select_font_face (mCairo, "monospace", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
   cairo_set_font_size (mCairo, 16.0);
   cairo_set_source_rgb (mCairo, 1.0, 1.0, 1.0);
   cairo_move_to (mCairo, pos.GetX(), pos.GetY());
   cairo_show_text (mCairo, text);
}
Example #12
0
static double GetVectorComponent(const Vector &a, int dim) {
    switch (dim) {
        case 0: return a.GetX(); break;
        case 1: return a.GetY(); break;
        case 2: return a.GetZ(); break;
    }
    Error("invalid dimension");
}
Vector Vector::operator + (Vector &vecV)
{
	Vector pvecNew;// = new Vector();

	pvecNew.SetVector(this->fX + vecV.GetX(), this->fY + vecV.GetY(), this->fZ + vecV.GetZ());

	return pvecNew;
}
Example #14
0
TEST(PointTests, ShouldScalePoint){
    Vector p(1, 2, 3);

    Matrix transformationMatrix = Matrix::CreateScaleMatrix(2, 0.5, 1);

    Vector result = p.Transform(transformationMatrix);

    EXPECT_EQ(2, result.GetX());
    EXPECT_EQ(1, result.GetY());
    EXPECT_EQ(3, result.GetZ());
}
Example #15
0
TEST(PointTests, ShouldRotatePointAroundZAxis){
    Vector p(1, 2, 3);

    Matrix transformationMatrix = Matrix::CreateZAxisRotationMatrix(M_PI / 6);

    Vector result = p.Transform(transformationMatrix);

    EXPECT_NEAR(-1 + sqrt(3) / 2, result.GetX(), 0.0001); // problems with accuracy
    EXPECT_DOUBLE_EQ(0.5 + sqrt(3), result.GetY());
    EXPECT_DOUBLE_EQ(3, result.GetZ());
}
Example #16
0
TEST(PointTests, ShouldRotatePointAroundYAxis){
    Vector p(1, 2, 3);

    Matrix transformationMatrix = Matrix::CreateYAxisRotationMatrix(M_PI / 4);

    Vector result = p.Transform(transformationMatrix);

    EXPECT_DOUBLE_EQ(2 * sqrt(2), result.GetX());
    EXPECT_DOUBLE_EQ(2, result.GetY());
    EXPECT_DOUBLE_EQ(sqrt(2), result.GetZ());
}
Example #17
0
TEST(PointTests, ShouldTranslatePoint){
    Vector p(1, 2, 3);

    Matrix transformationMatrix = Matrix::CreateTranslationMatrix(0, 20, -5);

    Vector result = p.Transform(transformationMatrix);

    EXPECT_EQ(1, result.GetX());
    EXPECT_EQ(22, result.GetY());
    EXPECT_EQ(-2, result.GetZ());
}
Example #18
0
void MenuState::ProcessRealEvent(){
	bool buttonLeft , buttonRight;
	buttonLeft = buttonRight = false;
	
	//sf::Event ev;
	
    if(inputManager->IsPressedMouseLeft() && !releaseMouse)
    {
        Vector posMouse = inputManager->GetMousePosition();
        
        if(!dialogVisible){
            if(vButtons->at(0)->IsPressed(posMouse.GetX(), posMouse.GetY()))
                dialogVisible=true;   
            else if(vButtons->at(1)->IsPressed(posMouse.GetX(), posMouse.GetY()))
               requestStateChange = std::make_pair(States::ID::LevelSelectionState, true);  // Continuar
            else if(vButtons->at(2)->IsPressed(posMouse.GetX(), posMouse.GetY()))
               requestStateChange = std::make_pair(States::ID::TutorialState, true);  // Tutorial
            else if(vButtons->at(3)->IsPressed(posMouse.GetX(), posMouse.GetY()))
               requestStateChange = std::make_pair(States::ID::SettingsState, true);  // Opciones
            else if(vButtons->at(4)->IsPressed(posMouse.GetX(), posMouse.GetY()))
               requestStateChange = std::make_pair(States::ID::CreditsState, true);  // Acerca De
            else if(vButtons->at(5)->IsPressed(posMouse.GetX(), posMouse.GetY())){
                ConfigurationManager::Instance()->SaveConfigurations();                 // Salir
                StatusManager::Instance()->SaveStatus();
                window->Close(); 
            }
        }                                                   
    }
    
	
	//vRealEvents->clear();
}
Example #19
0
extern bool CollisionUtils::IntersectPointAxisBox(Vector a_point, Vector a_boxPos, Vector a_boxDimensions)
{
	const Vector halfDim = a_boxDimensions * 0.5f;
	if (a_point.GetX() >= a_boxPos.GetX() - halfDim.GetX() && 
		a_point.GetX() <= a_boxPos.GetX() + halfDim.GetX() &&
		a_point.GetY() >= a_boxPos.GetY() - halfDim.GetY() && 
		a_point.GetY() <= a_boxPos.GetY() + halfDim.GetY() &&
		a_point.GetZ() >= a_boxPos.GetZ() - halfDim.GetZ() && 
		a_point.GetZ() <= a_boxPos.GetZ() + halfDim.GetZ())
	{
		return true;
	}

	return false;
}
Example #20
0
void		screenToWorldCoords(int xin, int yin, float* xout, float* yout)
{
	// if mouse X > 600, it wasn't for a ball
	if (xin > 600) {
		*xout = 100.0f;
		*yout = 100.0f;
		return;
	}

	float x = (float)xin;
	float y = (float)yin;

	float height = 600;
	y = height - y;

	// pixel coords -> [0,1]
	float xx = x / (float)600;
	float yy = y / (float)height;

	float zoom = renderer->getZoom();
	float zoom2 = zoom * 2.0f;

	// [0, 50]
	xx *= zoom2;
	yy *= zoom2;

	// [-25, 25]
	xx -= zoom;
	yy -= zoom;
	
	Vector translation = renderer->getTranslation();
	xx -= translation.GetX();
	yy -= translation.GetY();

	*xout = xx;
	*yout = yy;
}
Example #21
0
Ray::Ray(const Vector pos, const Vector dir, const Level& level)
{
   // The player's current grid position inside the level.
   mMapX = pos.GetX();
   mMapY = pos.GetY();

   // Length of the ray from one X and Y-side to next X and Y-side.
   const double delta_dist_x = std::sqrt(std::pow(dir.GetY(), 2) / std::pow(dir.GetX(), 2) + 1);
   const double delta_dist_y = std::sqrt(std::pow(dir.GetX(), 2) / std::pow(dir.GetY(), 2) + 1);

   int step_x; // +1 if heading north, -1 if heading south.
   int step_y; // +1 if heading east, -1 if heading west.
   double side_dist_x;
   double side_dist_y;

   if (dir.GetX() < 0) {
      step_x = -1;
      side_dist_x = (pos.GetX() - mMapX) * delta_dist_x;
   }
   else {
      step_x = 1;
      side_dist_x = (mMapX + 1. - pos.GetX()) * delta_dist_x;
   }

   if (dir.GetY() < 0) {
      step_y = -1;
      side_dist_y = (pos.GetY() - mMapY) * delta_dist_y;
   }
   else {
      step_y = 1;
      side_dist_y = (mMapY + 1. - pos.GetY()) * delta_dist_y;
   }

   for (;;)
   {
      if (side_dist_x < side_dist_y)
      {
         // Jump one square in X-direction.
         mMapX += step_x;
         side_dist_x += delta_dist_x;
         mVerticalSideHit = false;
      }
      else
      {
         // Jump one square in Y-direction.
         mMapY += step_y;
         side_dist_y += delta_dist_y;
         mVerticalSideHit = true;
      }

      // Check if the ray has hit a wall.
      if ((mMapX < 0) || (mMapX >= level.GetWidth()) ||
          (mMapY < 0) || (mMapY >= level.GetHeight()) ||
          level.IsBlocking(mMapX, mMapY))
      {
         break;
      }
   }

   if (!mVerticalSideHit)
   {
      const double unit_x = mMapX + (1 - step_x) / 2;
      const double intersect_x = pos.GetY() + ((unit_x - pos.GetX()) / dir.GetX()) * dir.GetY();
      mIntersection = { unit_x, intersect_x };

      // FIXME: May be to small.
      mDistance = std::fabs((unit_x - pos.GetX()) / dir.GetX());
   }
   else
   {
      const double unit_y = mMapY + (1 - step_y) / 2;
      const double intersect_y = pos.GetX() + ((unit_y - pos.GetY()) / dir.GetY()) * dir.GetX();
      mIntersection = { unit_y, intersect_y };

      // FIXME: May be too small.
      mDistance = std::fabs((unit_y - pos.GetY()) / dir.GetY());
   }
}
Example #22
0
void Rectangle::SetCenter(const Vector& centerPoint)
{
    this->vector.SetX(centerPoint.GetX() - w/2.0);
    this->vector.SetY(centerPoint.GetY() - h/2.0);
}
Example #23
0
bool Rectangle::IsInside(const Vector& vector) const
{
    return (vector.GetX() >= this->vector.GetX() and vector.GetX() <= this->vector.GetX() + w and
            vector.GetY() >= this->vector.GetY() and vector.GetY() <= this->vector.GetY() + h);
}
Example #24
0
void CameraManager::Update(float a_dt)
{
	m_currentCamera = &m_gameCamera;
	
	// Process camera controls
	InputManager & inMan = InputManager::Get();
	if (DebugMenu::Get().IsDebugMenuEnabled())
	{
		m_currentCamera = &m_debugCamera;
	
		// Create a view direction matrix
		Matrix cameraMat = m_currentCamera->GetCameraMatrix();
		Vector camPos = m_currentCamera->GetPosition();
		Vector camTarget = m_currentCamera->GetTarget();
		const float speed = m_currentCamera->GetTranslationSpeed();
		const float rotSpeed = m_currentCamera->GetRotationSpeed();
		
		// Don't change camera while there is a dialog up
		if (!DebugMenu::Get().IsDebugMenuActive())
		{
			// WSAD for FPS style movement
			Vector moveOffset(0.0f);
			if (inMan.IsKeyDepressed(SDLK_w)) {	moveOffset -= cameraMat.GetUp() * a_dt * speed; }	
			if (inMan.IsKeyDepressed(SDLK_s)) {	moveOffset += cameraMat.GetUp() * a_dt * speed; }	
			if (inMan.IsKeyDepressed(SDLK_d)) { moveOffset += cameraMat.GetRight() * a_dt * speed; }	
			if (inMan.IsKeyDepressed(SDLK_a)) {	moveOffset -= cameraMat.GetRight() * a_dt * speed; }
			if (inMan.IsKeyDepressed(SDLK_q)) {	moveOffset += Vector(0.0f, 0.0f, speed * a_dt); }
			if (inMan.IsKeyDepressed(SDLK_e)) { moveOffset -= Vector(0.0f, 0.0f, speed * a_dt); }	
		
			// Move both the camera and the target together
			m_currentCamera->SetPosition(camPos + moveOffset);
			m_currentCamera->SetTarget(camTarget + moveOffset);

			// Set rotation based on mouse delta while hotkey pressed
			if (inMan.IsKeyDepressed(SDLK_LSHIFT))
			{
				// Get current camera inputs
				const float maxRot = 360.0f;
				Vector2 curInput = inMan.GetMousePosRelative();
				Vector2 lastInput = m_debugOrientationInput;

				// Cancel out mouse movement above an epsilon to prevent the camera jumping around
				const float cameraMoveEpsilonSq = 0.05f;
				Vector2 vecInput = curInput - lastInput;
				if (vecInput.LengthSquared() > cameraMoveEpsilonSq)
				{
					vecInput = Vector2::Vector2Zero();
				}

				m_debugMouseLookAngleEuler += Vector(vecInput.GetY() * a_dt * rotSpeed, 0.0f, -vecInput.GetX() * a_dt * rotSpeed);
				Quaternion rotation(m_debugMouseLookAngleEuler);
				Matrix rotMat = Matrix::Identity();
				rotation.ApplyToMatrix(rotMat);
				Vector newTarget = rotMat.Transform(Vector(0.0f, Camera::sc_defaultCameraTargetDistance, 0.0f));
				m_currentCamera->SetTarget(camPos + newTarget);

				m_debugOrientationInput = curInput;
			}


			// Draw camera position on top of everything
			if (DebugMenu::Get().IsDebugMenuEnabled())
			{
				const Vector & camPos = m_currentCamera->GetPosition();
				char buf[32];
				sprintf(buf, "%.2f, %.2f, %.2f", camPos.GetX(), camPos.GetY(), camPos.GetZ());
				FontManager::Get().DrawDebugString2D(buf, Vector2(0.8f, 0.95f));
			}
		}
	}

	m_currentCamera->Update();
}
Example #25
0
extern bool CollisionUtils::IntersectLineAxisBox(Vector a_lineStart, Vector a_lineEnd, Vector a_boxPos, Vector a_boxDimensions, Vector & a_intersection_OUT)
{
	// Check the dimensions of the line against the box
	const Vector halfDim = a_boxDimensions * 0.5f;

	// Check the front plane of the box first
	Vector planeCentre = Vector(a_boxPos.GetX(), a_boxPos.GetY() - halfDim.GetY(), a_boxPos.GetZ());
	if (IntersectLinePlane(a_lineStart, a_lineEnd, planeCentre, Vector(0.0f, -1.0f, 0.0f), a_intersection_OUT))
	{
		if (fabsf(a_intersection_OUT.GetX() - planeCentre.GetX()) <= halfDim.GetX() &&
			fabsf(a_intersection_OUT.GetY() - planeCentre.GetY()) <= halfDim.GetY() &&
			fabsf(a_intersection_OUT.GetZ() - planeCentre.GetZ()) <= halfDim.GetZ())
		{
			return true;
		}
	}

	// Check back plane
	planeCentre = Vector(a_boxPos.GetX(), a_boxPos.GetY() + halfDim.GetY(), a_boxPos.GetZ());
	if (IntersectLinePlane(a_lineStart, a_lineEnd, planeCentre, Vector(0.0f, 1.0f, 0.0f), a_intersection_OUT))
	{
		if (fabsf(a_intersection_OUT.GetX() - planeCentre.GetX()) <= halfDim.GetX() &&
			fabsf(a_intersection_OUT.GetY() - planeCentre.GetY()) <= halfDim.GetY() &&
			fabsf(a_intersection_OUT.GetZ() - planeCentre.GetZ()) <= halfDim.GetZ())
		{
			return true;
		}
	}

	// Check left plane
	planeCentre = Vector(a_boxPos.GetX() - halfDim.GetX(), a_boxPos.GetY(), a_boxPos.GetZ());
	if (IntersectLinePlane(a_lineStart, a_lineEnd, planeCentre, Vector(-1.0f, 0.0f, 0.0f), a_intersection_OUT))
	{
		if (fabsf(a_intersection_OUT.GetX() - planeCentre.GetX()) <= halfDim.GetX() &&
			fabsf(a_intersection_OUT.GetY() - planeCentre.GetY()) <= halfDim.GetY() &&
			fabsf(a_intersection_OUT.GetZ() - planeCentre.GetZ()) <= halfDim.GetZ())
		{
			return true;
		}
	}

	// Check right plane
	planeCentre = Vector(a_boxPos.GetX() + halfDim.GetX(), a_boxPos.GetY(), a_boxPos.GetZ());
	if (IntersectLinePlane(a_lineStart, a_lineEnd, planeCentre, Vector(1.0f, 0.0f, 0.0f), a_intersection_OUT))
	{
		if (fabsf(a_intersection_OUT.GetX() - planeCentre.GetX()) <= halfDim.GetX() &&
			fabsf(a_intersection_OUT.GetY() - planeCentre.GetY()) <= halfDim.GetY() &&
			fabsf(a_intersection_OUT.GetZ() - planeCentre.GetZ()) <= halfDim.GetZ())
		{
			return true;
		}
	}

	// Check top plane
	planeCentre = Vector(a_boxPos.GetX(), a_boxPos.GetY(), a_boxPos.GetZ() + halfDim.GetZ());
	if (IntersectLinePlane(a_lineStart, a_lineEnd, planeCentre, Vector(0.0f, 0.0f, 1.0f), a_intersection_OUT))
	{
		if (fabsf(a_intersection_OUT.GetX() - planeCentre.GetX()) <= halfDim.GetX() &&
			fabsf(a_intersection_OUT.GetY() - planeCentre.GetY()) <= halfDim.GetY() &&
			fabsf(a_intersection_OUT.GetZ() - planeCentre.GetZ()) <= halfDim.GetZ())
		{
			return true;
		}
	}

	// Check bottom plane
	planeCentre = Vector(a_boxPos.GetX(), a_boxPos.GetY(), a_boxPos.GetZ() - halfDim.GetZ());
	if (IntersectLinePlane(a_lineStart, a_lineEnd, planeCentre, Vector(0.0f, 0.0f, -1.0f), a_intersection_OUT))
	{
		if (fabsf(a_intersection_OUT.GetX() - planeCentre.GetX()) <= halfDim.GetX() &&
			fabsf(a_intersection_OUT.GetY() - planeCentre.GetY()) <= halfDim.GetY() &&
			fabsf(a_intersection_OUT.GetZ() - planeCentre.GetZ()) <= halfDim.GetZ())
		{
			return true;
		}
	}

	return false;
}
Example #26
0
bool	Game::StaticLineCollisionDetection(Line* line, Circle* circle, ContactManifold* contactManifold)
{

	if (circle->getActive() == false)
		return false;

	bool loop = false;
	Vector b = circle->GetPos();
	Vector n = line->getNormal();

	float rad = circle->GetRadius();
	Vector p1 = line->GetPos(1);
	Vector p2 = line->GetPos(0);

	// Static line-circle collision detection :
	// Plug circle's eq. into line's equation to find if circle intersects line
	Vector d = p1 - p2;
	Vector f = p2 - b;
	float  r = rad;
	float A = d.dot(d);
	float B = 2.0f*f.dot(d);
	float C = f.dot(f) - r*r;

	float t1 = -1, t2 = -1;

	float discriminant = B*B - 4.0f*A*C;
	if (discriminant < 0)
		return false; // no collision
	else {
		float discriminant_squared = sqrt(discriminant);
		float t1 = (-B + discriminant_squared) / (2.0f * A);
		float t2 = (-B - discriminant_squared) / (2.0f * A);

		float offset=0.0f;

		// two circle-line intersections
		if (t1 >= 0.0f && t1 <= 1.0f || t2 >= 0.0f && t2 <= 1.0f)
		{
			// increase support
			circle->support++;

			// check if both t1,t2 are valid (inside [0,1])
			float v1= -1.0f, v2= -1.0f;
			if (t1 >= 0.0f && t1 <= 1.0f)
				v1 = v2 = t1;
			if (t2 >= 0.0f && t2 <= 1.0f)
				v2 = t2;
			if (v1 == -1.0f)
				v1 = t2;
			// -----------------------------------------

			// v1, v2 averaged
			float t_middle = (v1+v2)/2.0f;

			// intersection point on the line
			Vector middle_point = line->GetPos(0) + (line->GetPos(1)-line->GetPos(0)) * t_middle;

			// vector from circles's center to intersection point
			Vector normal = middle_point - circle->GetPos();

			// middle point-circle = 0 (circle on line)
			if (normal.length() < 0.00001f) {
				Vector new_c = circle->GetPos() + circle->GetRadius() * line->getNormal();
				circle->SetPos(new_c.GetX(), new_c.GetY());
				return true;
			}

			// normalize
			normal = normal.normalise();

			// edge point of circle
			Vector edge_point = circle->GetPos() + normal * circle->GetRadius();

			// displacement t
			float t= (middle_point - edge_point).length();
			t += 0.005f;

			// new position for circle
			Vector new_c = circle->GetPos() - t * normal; // normal looks 'towards' the collision so use -

			Vector q;
			q = circle->GetPos() + normal * circle->GetRadius();
			q.Set(q.GetX(), q.GetY(), t);

			ManifoldPoint point;
			point.impulse = 0.0f;
			point.contactID1 = line;
			point.t_impulse = 0;
			point.contactID2 = circle;
			point.contactPoint = q; // contact Point + t
			point.contactNormal = normal * (-1.0f);
			point.t = -1.0f;
			point.responded = false;

			#ifdef COMMON_RESPONSE
				point.contactID1 = circle;
				point.contactID2 = line;
			#endif

			contactManifold->Add(point);
			return false;

			circle->SetPos(new_c.GetX(), new_c.GetY());
			return true;
		}
	}	

	return false;
}
float Vector::VectorDotProduct(Vector V1, Vector V2)
{
	return (V1.GetX()*V2.GetX() + V1.GetY()*V2.GetY() + V1.GetZ()*V2.GetZ());
}
Example #28
0
void Slice::Draw(Ray ray, Vector pos, Vector dir, const Level& level, const ResourceCache& res)
{
   const int wall_height = std::abs(int(mSurface->h / ray.GetDistance()));

   int wall_start = (mSurface->h / 2) - (wall_height / 2);
   int wall_end = (mSurface->h / 2) + (wall_height / 2);

   if (wall_start < 0) {
      wall_start = 0;
   }

   if (wall_end >= mSurface->h) {
      wall_end = mSurface->h - 1;
   }

   // Get the texture that matches the cell type.
   const auto cell_id = level.mGrid[ray.GetMapIntersectionX()][ray.GetMapIntersectionY()] - 1;
   //const auto cell_id = level.mGrid[ray.GetMapIntersectionX()][ray.GetMapIntersectionY()] - 1;
   const auto wall_tex = res.GetWall(cell_id);

   // Where exactly the wall was hit.
   double wall_x = ray.GetIntersection().GetY();
   wall_x -= std::floor(wall_x);

   // X-coordinate on the texture.
   int tex_x = wall_x * wall_tex->w;

   if (( ray.VerticalSideHit() && dir.GetY() < 0) ||
       (!ray.VerticalSideHit() && dir.GetX() > 0))
   {
      tex_x = wall_tex->w - tex_x - 1;
   }

   for (int y = wall_start; y < wall_end; y++)
   {
      const int tex_y = (y * 2 - mSurface->h + wall_height) *
                        (wall_tex->h / 2) / wall_height;

      const auto tex_offset = (wall_tex->pitch * tex_y) + (tex_x * 4);
      const auto tex_ptr = static_cast<Uint8*>(wall_tex->pixels) + tex_offset;

      SDL_Color color = { tex_ptr[0], tex_ptr[1], tex_ptr[2] };

      if (ray.VerticalSideHit())
      {
         // Give X and Y-sides different brightness.
         color.r /= 2;
         color.g /= 2;
         color.b /= 2;
      }

      const auto scr_offset = (mSurface->pitch * y) + (mXCoordinate * 4);
      const auto scr_ptr = static_cast<Uint8*>(mSurface->pixels) + scr_offset;
      memcpy(scr_ptr, &color, sizeof(color));
   }

   // Get the texture for the ceiling and floor.
//   const auto ceiling_tex = res.GetCeiling(0);
   const auto floor_tex = res.GetWall(2);

   // Position of the floor at the bottom of the wall.
   double floor_x_wall;
   double floor_y_wall;

   if (!ray.VerticalSideHit() && (dir.GetX() > 0)) {
      floor_x_wall = ray.GetMapIntersectionX();
      floor_y_wall = ray.GetMapIntersectionY() + wall_x;
   }
   else if (!ray.VerticalSideHit() && (dir.GetX() < 0)) {
      floor_x_wall = ray.GetMapIntersectionX() + 1.;
      floor_y_wall = ray.GetMapIntersectionY() + wall_x;
   }
   else if (ray.VerticalSideHit() && (dir.GetY() > 0)) {
      floor_x_wall = ray.GetMapIntersectionX() + wall_x;
      floor_y_wall = ray.GetMapIntersectionY();
   }
   else {
      floor_x_wall = ray.GetMapIntersectionX() + wall_x;
      floor_y_wall = ray.GetMapIntersectionY() + 1.;
   }

   const double dist_wall = ray.GetDistance();
   const double dist_player = .0;

   // Draw the floor from below the wall to the bottom of the screen.
   for (int y = wall_end; y < mSurface->h; y++)
   {
      const double cur_dist = mSurface->h / (2. * y - mSurface->h);
      const double weight = (cur_dist - dist_player) / (dist_wall - dist_player);

      double cur_floor_x = weight * floor_x_wall + (1.0 - weight) * pos.GetX();
      double cur_floor_y = weight * floor_y_wall + (1.0 - weight) * pos.GetY();
      if (cur_floor_x < 0.) { cur_floor_x = 0.; }
      if (cur_floor_y < 0.) { cur_floor_y = 0.; }

      const int floor_tex_x = int(cur_floor_x * floor_tex->w / 4) % floor_tex->w;
      const int floor_tex_y = int(cur_floor_y * floor_tex->h / 4) % floor_tex->h;

//      const auto ceiling_tex_offset = (ceiling_tex->pitch * floor_tex_y) + (floor_tex_x * 4);
//      const auto ceiling_tex_ptr = static_cast<Uint8*>(ceiling_tex->pixels) + ceiling_tex_offset;

      const auto floor_tex_offset = (floor_tex->pitch * floor_tex_y) + (floor_tex_x * 4);
      const auto floor_tex_ptr = static_cast<Uint8*>(floor_tex->pixels) + floor_tex_offset;

//      const SDL_Color ceiling_color = { ceiling_tex_ptr[0], ceiling_tex_ptr[1], ceiling_tex_ptr[2] };
      SDL_Color floor_color = { floor_tex_ptr[0], floor_tex_ptr[1], floor_tex_ptr[2] };

      // Make the floor darker.
      floor_color.r /= 2;
      floor_color.g /= 2;
      floor_color.b /= 2;

//      const auto ceiling_offset = (mSurface->pitch * (mSurface->h - y - 1)) + (mXCoordinate * 4);
//      const auto ceiling_ptr = static_cast<Uint8*>(mSurface->pixels) + ceiling_offset;
//      memcpy(ceiling_ptr, &ceiling_color, sizeof(ceiling_color));

      const auto floor_offset = (mSurface->pitch * y) + (mXCoordinate * 4);
      const auto floor_ptr = static_cast<Uint8*>(mSurface->pixels) + floor_offset;
      memcpy(floor_ptr, &floor_color, sizeof(floor_color));
   }
}
Example #29
0
void Circle::CollisionResponseWithLine(ManifoldPoint& point, float dt)
{
	float e = Elasticity; 
	////////////////////////////////////////////////////////////

	Circle* c1 = this;
	Line* l = (Line*)point.contactID1;
	////////////////////////////////////////////////////////////////////////////


	//----------------------
	if (l->GetPos(0).GetX() >= -4.0f && l->GetPos(0).GetX() < 3.9f &&
		l->GetPos(0).GetY() <= 12.0f && l->GetPos(0).GetY() >= 0.0f)  {
			
			if (l->getNormal().dot(c1->GetPos()-l->GetPos(0)) > 0.0f && m_game->activeRope())
				m_game->rope.addForce(Vector(0, -m_data->m_mass * 9.81f));
	}

	//----------------------


	double invDt = 1.0f / dt;

	Vector nn = point.contactNormal;

	Vector r1 = point.contactPoint - c1->GetPos();
	r1.Set(r1.GetX(), r1.GetY(), 0);
 
	// get all of relative normal velocity
	double relNv = ((c1->GetVel() + c1->GetAngularVel().cross(r1)).dot(nn));

	double vBias = 0.0f;
	if (point.t == -1.0f) {
		vBias = (point.contactPoint.GetZ()-0.0001f) * 0.2f  * invDt;
	}

	double velBias = relNv * Circle::Elasticity;
	double remove = relNv - vBias + velBias;// + dist * 200.0f;	


	
	double denom = 1.0f / c1->GetMass();

	//if (point.t != -1.0f) {
	
	denom = (1.0f / c1->GetMass() + 
	nn.dot(Vector((r1.cross(point.contactNormal)) / c1->GetInertia()).cross(r1)));  

	//}

	denom = 1.0 / denom;

	//// compute impulse
	double imp = remove * denom/*c1->GetMass()*/;
	 

	// sequential impulses

	double temp = point.impulse;
	point.impulse = min(point.impulse + imp, 0);
	imp = point.impulse - temp;

	
	//////////////

	// apply impulse
	
	Vector Vel = c1->GetVel() -  (float)imp * nn / c1->GetMass();
	c1->SetVel(Vel.GetX(), Vel.GetY());

	
	Vector w1_n = c1->GetAngularVel() - (r1.cross((float)imp*nn)) / c1->GetInertia();
	c1->SetAngularVel(w1_n);
	

	
	// ----------------------------------
	// F R I C T I O N ------------------
	// __________________________________
	bool bFriction = true;

	if (bFriction) {
		Vector t = nn.cross(Vector(0,0,1));

		denom = 
		(1.0f/c1->GetMass() +
		t.dot(Vector((r1.cross(t))/c1->GetInertia()).cross(r1))); 
	}
	denom = 1.0 / denom;

	Vector t = nn.cross(Vector(0,0,1));
	double vt = (c1->GetVel() + c1->GetAngularVel().cross(r1)).dot(t);
	double dPt = denom * (-vt);

	// sequential impulse
	double maxPt = Friction * point.impulse;

	double oldTangentImpulse = point.t_impulse;
	// clamp
	point.t_impulse = oldTangentImpulse + dPt;
	if (point.t_impulse < -maxPt)
		point.t_impulse = -maxPt;
	else if (point.t_impulse > maxPt)
		point.t_impulse = maxPt;

	dPt = point.t_impulse - oldTangentImpulse;
	 // /

	// Apply contact impulse
	Vector Pt = (float)dPt * t;


	Vector Vel0 = c1->GetVel() + Pt / c1->GetMass() ; 	
	c1->SetVel(Vel0.GetX(), Vel0.GetY());
	
	
	//if (point.t != -1.0f) {
	Vector angVel0 = c1->GetAngularVel() - (r1.cross(Pt)) / c1->GetInertia();
	c1->SetAngularVel(angVel0);
		
	//}

	point.responded = true;
}
Example #30
0
bool	Game::StaticSphereCollisionDetection(Circle* circle1, Circle* circle2, ContactManifold* contactManifold)
{

	// no check if both circles sleep
	if (circle1->getActive() == false && circle2->getActive() == false)
		return false;

	bool loop = false;
	Vector pos1 = circle1->GetPos();
	Vector pos2 = circle2->GetPos();
	float r1 = circle1->GetRadius();
	float r2 = circle2->GetRadius();

	float dist = pos1.distance(pos2);
	dist -= (r1 + r2);

	if(dist < 0.0f)
	{
		// set support var
		circle1->support++;
		circle2->support++;
		////

		// many balls -> poss. that pos1==pos2 -> colNormal = NaN after normalization
		Vector colNormal = (pos1 - pos2).normalise();

		Vector n1, n2;
		n1 = n2 = colNormal;

		Vector hitPoint = pos1 + circle1->GetRadius() * (pos1-pos2).normalise();
		// Save the penetration value in the unused Z component 
		hitPoint.Set(hitPoint.GetX(), hitPoint.GetY(), -dist);

			ManifoldPoint mpoint;
			mpoint.contactID1 = circle1;
			mpoint.contactID2 = circle2;
			mpoint.contactPoint = hitPoint;
			mpoint.responded = false;
			mpoint.impulse = 0.0f;
			mpoint.t_impulse = 0;
			mpoint.t = -1;
			mpoint.contactNormal = colNormal;
			contactManifold->Add(mpoint);
			
			circle1->setActive(true);
			circle2->setActive(true);
			return false;

		pos1 = pos1 - (n1 * dist * 1.1f);
		pos2 = pos2 + (n2 * dist * 1.1f);


		// critical section
		circle1->SetPos(pos1.GetX(), pos1.GetY());
		circle2->SetPos(pos2.GetX(), pos2.GetY());
		// critical section

		// make sure collided circles are awake
		circle1->setActive(true);
		circle2->setActive(true);

		loop = true;
	}

	return loop;
}