Example #1
0
AABB CLevelEntity::CalculateBoundingBox(CLevelEntity* pThis)
{
	size_t iModel = pThis->GetModelID();
	CModel* pModel = CModelLibrary::GetModel(iModel);

	if (pModel)
		return pModel->m_aabbVisBoundingBox;

	tstring sAABB = pThis->GetParameterValue("BoundingBox");

	AABB aabbBounds = AABB(Vector(-0.5f, -0.5f, -0.5f), Vector(0.5f, 0.5f, 0.5f));

	if (CanUnserializeString_AABB(sAABB))
	{
		aabbBounds = UnserializeString_AABB(sAABB, pThis->GetName(), pThis->m_sClass, "BoundingBox");

		// Center the entity around this bounding box.
		Vector vecGlobalOrigin = aabbBounds.Center();
		aabbBounds.m_vecMins -= vecGlobalOrigin;
		aabbBounds.m_vecMaxs -= vecGlobalOrigin;
	}
	else
	{
		CSaveData* pSaveData = CBaseEntity::FindSaveDataByHandle(tstring("C"+pThis->m_sClass).c_str(), "BoundingBox");
		if (pSaveData && pSaveData->m_bDefault)
			memcpy(&aabbBounds, &pSaveData->m_oDefault, sizeof(aabbBounds));
	}

	if (pThis->m_hMaterialModel.IsValid() && pThis->m_hMaterialModel->m_ahTextures.size())
	{
		CTextureHandle hBaseTexture = pThis->m_hMaterialModel->m_ahTextures[0];

		if (hBaseTexture.IsValid())
		{
			aabbBounds.m_vecMaxs.y *= (float)hBaseTexture->m_iHeight/pThis->m_hMaterialModel->m_iTexelsPerMeter;
			aabbBounds.m_vecMins.y *= (float)hBaseTexture->m_iHeight/pThis->m_hMaterialModel->m_iTexelsPerMeter;

			aabbBounds.m_vecMaxs.z *= (float)hBaseTexture->m_iWidth/pThis->m_hMaterialModel->m_iTexelsPerMeter;
			aabbBounds.m_vecMins.z *= (float)hBaseTexture->m_iWidth/pThis->m_hMaterialModel->m_iTexelsPerMeter;
		}
	}

	aabbBounds.m_vecMins = aabbBounds.m_vecMins * pThis->GetScale();
	aabbBounds.m_vecMaxs = aabbBounds.m_vecMaxs * pThis->GetScale();

	return aabbBounds;
}
Example #2
0
AABB buildBox (const Segment &s, const float &pitch, const float &height, const float &thickness) {
	const MatrixCoord3D &start = s.start;
	const MatrixCoord3D &end = s.end;

	Vec3f xyz (static_cast<float>(start[0])*pitch, static_cast<float>(start[2])*height, static_cast<float>(start[1])*pitch);
	Vec3f XYZ (static_cast<float>(end[0])*pitch, static_cast<float>(end[2])*height, static_cast<float>(end[1])*pitch);

	// must swap z and Z. because -XYZ will yield the smallest negative value for Z, that needs to be swapped so that the xyz and XYZ points get right for AABB creation.
	const float buffer = -xyz[2];
	xyz[2] = -XYZ[2];
	XYZ[2] = buffer;

	xyz -= Vec3f (thickness, thickness, thickness); // 0
	XYZ += Vec3f (thickness, thickness, thickness); // 1

	return AABB (xyz, XYZ);
}
Example #3
0
	TEST(AABBTest, SplitZ)
	{
		auto split_z = AABB({10, 100, 1000}, {20, 200, 2000}).split(2, 1500);

		EXPECT_NEAR(10, split_z.left.minimum().x(), 1e-100);
		EXPECT_NEAR(100, split_z.left.minimum().y(), 1e-100);
		EXPECT_NEAR(1000, split_z.left.minimum().z(), 1e-100);
		EXPECT_NEAR(20, split_z.left.maximum().x(), 1e-100);
		EXPECT_NEAR(200, split_z.left.maximum().y(), 1e-100);
		EXPECT_NEAR(1500, split_z.left.maximum().z(), 1e-100);
		EXPECT_NEAR(10, split_z.right.minimum().x(), 1e-100);
		EXPECT_NEAR(100, split_z.right.minimum().y(), 1e-100);
		EXPECT_NEAR(1500, split_z.right.minimum().z(), 1e-100);
		EXPECT_NEAR(20, split_z.right.maximum().x(), 1e-100);
		EXPECT_NEAR(200, split_z.right.maximum().y(), 1e-100);
		EXPECT_NEAR(2000, split_z.right.maximum().z(), 1e-100);
	}
Example #4
0
	TEST(AABBTest, SplitX)
	{
		auto split_x = AABB({10, 100, 1000}, {20, 200, 2000}).split(0, 15);

		EXPECT_NEAR(10, split_x.left.minimum().x(), 1e-100);
		EXPECT_NEAR(100, split_x.left.minimum().y(), 1e-100);
		EXPECT_NEAR(1000, split_x.left.minimum().z(), 1e-100);
		EXPECT_NEAR(15, split_x.left.maximum().x(), 1e-100);
		EXPECT_NEAR(200, split_x.left.maximum().y(), 1e-100);
		EXPECT_NEAR(2000, split_x.left.maximum().z(), 1e-100);
		EXPECT_NEAR(15, split_x.right.minimum().x(), 1e-100);
		EXPECT_NEAR(100, split_x.right.minimum().y(), 1e-100);
		EXPECT_NEAR(1000, split_x.right.minimum().z(), 1e-100);
		EXPECT_NEAR(20, split_x.right.maximum().x(), 1e-100);
		EXPECT_NEAR(200, split_x.right.maximum().y(), 1e-100);
		EXPECT_NEAR(2000, split_x.right.maximum().z(), 1e-100);
	}
Example #5
0
bool SSaPCollisionManager::collide_(CollisionObject* obj, void* cdata, CollisionCallBack callback) const
{
  static const unsigned int CUTOFF = 100;

  DummyCollisionObject dummyHigh(AABB(obj->getAABB().max_));
  bool coll_res = false;

  std::vector<CollisionObject*>::const_iterator pos_start1 = objs_x.begin();
  std::vector<CollisionObject*>::const_iterator pos_end1 = std::upper_bound(pos_start1, objs_x.end(), &dummyHigh, SortByXLow());
  unsigned int d1 = pos_end1 - pos_start1;

  if(d1 > CUTOFF)
  {
    std::vector<CollisionObject*>::const_iterator pos_start2 = objs_y.begin();
    std::vector<CollisionObject*>::const_iterator pos_end2 = std::upper_bound(pos_start2, objs_y.end(), &dummyHigh, SortByYLow());
    unsigned int d2 = pos_end2 - pos_start2;

    if(d2 > CUTOFF)
    {
      std::vector<CollisionObject*>::const_iterator pos_start3 = objs_z.begin();
      std::vector<CollisionObject*>::const_iterator pos_end3 = std::upper_bound(pos_start3, objs_z.end(), &dummyHigh, SortByZLow());
      unsigned int d3 = pos_end3 - pos_start3;

      if(d3 > CUTOFF)
      {
        if(d3 <= d2 && d3 <= d1)
          coll_res = checkColl(pos_start3, pos_end3, obj, cdata, callback);
        else
        {
          if(d2 <= d3 && d2 <= d1)
            coll_res = checkColl(pos_start2, pos_end2, obj, cdata, callback);
          else
            coll_res = checkColl(pos_start1, pos_end1, obj, cdata, callback);
        }
      }
      else
        coll_res = checkColl(pos_start3, pos_end3, obj, cdata, callback);
    }
    else
      coll_res = checkColl(pos_start2, pos_end2, obj, cdata, callback);
  }
  else
    coll_res = checkColl(pos_start1, pos_end1, obj, cdata, callback);

  return coll_res;
}
Example #6
0
void Node::evaluateChildBounds() const {
	if (_childBoundsChanged) {
		ASSERT_MESSAGE(!_childBoundsMutex, "re-entering bounds evaluation");
		_childBoundsMutex = true;

		_childBounds = AABB();

		// Instantiate an AABB accumulator
		AABBAccumulateWalker accumulator(_childBounds);

		// greebo: traverse the children of this node
		traverse(accumulator);
		
		_childBoundsMutex = false;
		_childBoundsChanged = false;
	}
}
Example #7
0
/* Creates the sphere from a scene file. */
Sphere::Sphere(std::fstream& file, std::vector<Material*>* materials, std::vector<Light*>* lights) : Primitive(file, materials, lights)
{
    /* Read the sphere definition from the scene file. */
    SphereDefinition definition;
    file.read((char*)&definition, sizeof(SphereDefinition));

    /* Read the geometric center and radius of the sphere. */
    this->center = Vector(definition.center[0], definition.center[1], definition.center[2]);
    this->radius = definition.radius;

    /* Compute the sphere's radius squared. */
    this->radiusSquared = this->radius * this->radius;

    /* Compute the sphere's bounding box. */
    Vector radiusVector = Vector(this->radius, this->radius, this->radius);
    this->boundingBox = AABB(this->center - radiusVector, this->center + radiusVector);
}
Example #8
0
    void Locator::Update(const FrameTime& fr, UpdateTypeEnum updateType)
    {               
        super::Update(fr,updateType);
		bool updatedBound = m_worldXformUpdated;

        Model* model = m_resource ? (Model*)m_resource->GetTarget() : NULL;                     
        if( model && model->IsReady())
        {
            if(m_modelTransforms.empty() || m_worldXformUpdated)
            {
                 const MatrixList& matrices = model->AbsoluteTransforms();
                 m_modelTransforms.resize(matrices.size());
                 for( unsigned int i = 0; i < m_modelTransforms.size(); ++i)
                 {
                     m_modelTransforms[i] = matrices[i] * m_world; // transform matrix array now holds complete world transform.
                 }
                 BuildRenderables(); 
				 updatedBound = true;
            }                               
        }

        m_boundsDirty = updatedBound;
        if(m_boundsDirty)        
        {                  
            if(!m_modelTransforms.empty())
            {                
               // assert(model && model->IsReady());
                m_localBounds = model->GetBounds();                                
                if(m_parent) m_parent->InvalidateBounds();                
            }
            else
            {
                m_localBounds = AABB(float3(-0.5f,-0.5f,-0.5f), float3(0.5f,0.5f,0.5f));                
            }      
            this->UpdateWorldAABB();            
        }

        if(RenderContext::Inst()->LightEnvDirty)
        {
            // update light env.
            for(auto  renderNode = m_renderables.begin(); renderNode != m_renderables.end(); renderNode++)
            {
                LightingState::Inst()->UpdateLightEnvironment(*renderNode);
            }
        }         
    }
Example #9
0
AABB RasterizerDummy::mesh_get_aabb(RID p_mesh) const {

	Mesh *mesh = mesh_owner.get( p_mesh );
	ERR_FAIL_COND_V(!mesh,AABB());

	AABB aabb;

	for (int i=0;i<mesh->surfaces.size();i++) {

		if (i==0)
			aabb=mesh->surfaces[i]->aabb;
		else
			aabb.merge_with(mesh->surfaces[i]->aabb);
	}

	return aabb;
}
void CIntersectionAssistanceUnit::DebugUpdate() const
{
    if(g_pGameCVars->pl_pickAndThrow.intersectionAssistDebugEnabled)
        {
            IEntity* pEntity = gEnv->pEntitySystem->GetEntity(m_subjectEntityId);
            if(pEntity)
                {
                    IPhysicalEntity *pPhysical = pEntity->GetPhysics();
                    if(pPhysical)
                        {
                            const float fFontSize = 1.2f;
                            float drawColor[4] = {1.0f, 1.0f, 1.0f, 1.0f};

                            string sMsg(string().Format(" Entity ID: [%d]", m_subjectEntityId));
                            sMsg += string().Format("\n Entity Name: [%s]", pEntity->GetName());

                            sMsg += string().Format("\n EmbedTimer: [%.3f]", m_embedTimer);
                            sMsg += string().Format("\n EmbedState: [%s]",(m_embedState == eES_None) ? "NONE" : (m_embedState == eES_Evaluating) ? "EVALUATING" : (m_embedState == eES_ReEvaluating) ? "REEVALUATING" : (m_embedState == eES_NotEmbedded) ? "NOT EMBEDDED" : (m_embedState == eES_Embedded) ? "EMBEDDED" : "UNKNOWN");

                            Vec3 vCurrTrans = m_entityStartingWPos - pEntity->GetWorldPos();
                            sMsg += string().Format("\n Translation: < %.3f, %.3f, %.3f >", vCurrTrans.x, vCurrTrans.y, vCurrTrans.z );
                            sMsg += string().Format("\n Trans magnitude: < %.3f >", vCurrTrans.GetLength() );
                            sMsg += string().Format("\n Trans per sec: < %.3f >", vCurrTrans.GetLength() / g_pGameCVars->pl_pickAndThrow.intersectionAssistTimePeriod );

                            sMsg += string().Format("\n Collision count: %u", m_collisionCount );

                            // RENDER
                            Vec3 vDrawPos = pEntity->GetWorldPos() + Vec3(0.0f,0.0f,0.6f);
                            gEnv->pRenderer->DrawLabelEx(vDrawPos, fFontSize, drawColor, true, true, sMsg.c_str());

                            // Box
                            pe_params_bbox bbox;
                            if(pPhysical->GetParams(&bbox))
                                {
                                    ColorB colDefault = ColorB( 127,127,127 );
                                    ColorB embedded = ColorB(255, 0, 0);
                                    ColorB notEmbedded = ColorB(0, 255, 0);

                                    gEnv->pRenderer->GetIRenderAuxGeom()->DrawAABB( AABB(bbox.BBox[0],bbox.BBox[1]), Matrix34(IDENTITY), false, (m_embedState == eES_Embedded) ? embedded : (m_embedState == eES_NotEmbedded) ? notEmbedded : colDefault, eBBD_Faceted);
                                }
                        }
                }

        }
}
Example #11
0
TriMesh::TriMesh(Stream *stream, InstanceManager *manager) 
	: Shape(stream, manager), m_tangents(NULL) {
	m_name = stream->readString();
	m_aabb = AABB(stream);

	uint32_t flags = stream->readUInt();
	m_vertexCount = stream->readSize();
	m_triangleCount = stream->readSize();

	m_positions = new Point[m_vertexCount];
	stream->readFloatArray(reinterpret_cast<Float *>(m_positions), 
		m_vertexCount * sizeof(Point)/sizeof(Float));

	m_faceNormals = flags & EFaceNormals;

	if (flags & EHasNormals) {
		m_normals = new Normal[m_vertexCount];
		stream->readFloatArray(reinterpret_cast<Float *>(m_normals), 
			m_vertexCount * sizeof(Normal)/sizeof(Float));
	} else {
		m_normals = NULL;
	}

	if (flags & EHasTexcoords) {
		m_texcoords = new Point2[m_vertexCount];
		stream->readFloatArray(reinterpret_cast<Float *>(m_texcoords), 
			m_vertexCount * sizeof(Point2)/sizeof(Float));
	} else {
		m_texcoords = NULL;
	}

	if (flags & EHasColors) {
		m_colors = new Spectrum[m_vertexCount];
		stream->readFloatArray(reinterpret_cast<Float *>(m_colors), 
			m_vertexCount * sizeof(Spectrum)/sizeof(Float));
	} else {
		m_colors = NULL;
	}

	m_triangles = new Triangle[m_triangleCount];
	stream->readUIntArray(reinterpret_cast<uint32_t *>(m_triangles), 
		m_triangleCount * sizeof(Triangle)/sizeof(uint32_t));
	m_flipNormals = false;
	configure();
}
Example #12
0
void SSaPCollisionManager::unregisterObject(CollisionObject* obj)
{
  setup();

  DummyCollisionObject dummyHigh(AABB(obj->getAABB().max_));

  std::vector<CollisionObject*>::iterator pos_start1 = objs_x.begin();
  std::vector<CollisionObject*>::iterator pos_end1 = std::upper_bound(pos_start1, objs_x.end(), &dummyHigh, SortByXLow());

  while(pos_start1 < pos_end1)
  {
    if(*pos_start1 == obj)
    {
      objs_x.erase(pos_start1);
      break;
    }
    ++pos_start1;
  }

  std::vector<CollisionObject*>::iterator pos_start2 = objs_y.begin();
  std::vector<CollisionObject*>::iterator pos_end2 = std::upper_bound(pos_start2, objs_y.end(), &dummyHigh, SortByYLow());

  while(pos_start2 < pos_end2)
  {
    if(*pos_start2 == obj)
    {
      objs_y.erase(pos_start2);
      break;
    }
    ++pos_start2;
  }

  std::vector<CollisionObject*>::iterator pos_start3 = objs_z.begin();
  std::vector<CollisionObject*>::iterator pos_end3 = std::upper_bound(pos_start3, objs_z.end(), &dummyHigh, SortByZLow());

  while(pos_start3 < pos_end3)
  {
    if(*pos_start3 == obj)
    {
      objs_z.erase(pos_start3);
      break;
    }
    ++pos_start3;
  }
}
/*!
*  \brief      Loads the environment configuration from a json file.
*  \author     Sascha Kaden
*  \param[in]  file path
*  \param[out] result of the loading
*  \date       2017-10-18
*/
bool EnvironmentConfigurator::loadConfig(const std::string &filePath) {
    nlohmann::json json = loadJson(filePath);
    if (json.empty())
        return false;

    m_obstaclePaths.clear();
    auto numObstacles = json["NumObstacles"].get<size_t>();
    for (size_t i = 0; i < numObstacles; ++i)
        m_obstaclePaths.push_back(json["ObstaclePath" + std::to_string(i)].get<std::string>());
    m_workspaceDim = json["WorkspaceDim"].get<unsigned int>();
    Vector3 bottomLeft = stringToVector<3>(json["MinWorkspaceBound"].get<std::string>());
    Vector3 topRight = stringToVector<3>(json["MaxWorkspaceBound"].get<std::string>());
    m_workspceBounding = AABB(bottomLeft, topRight);
    m_factoryType = static_cast<FactoryType>(json["FactoryType"].get<int>());
    m_robotType = static_cast<RobotType>(json["RobotType"].get<int>());

    return true;
}
Example #14
0
VillagerC::VillagerC()
{
	Texture* tex = textureLoader::getTexture("friendly_npcs");
	AnimatedSprite sprite = AnimatedSprite(&tex->texture, 0, 0, tex->cellWidth, tex->cellHeight, 0 * tex->uSize, 5 * tex->vSize, 1 * tex->uSize, 1 * tex->vSize);
	*this = VillagerC((VillagerC&)sprite);
	type = 1;
	name = "villagerC";
	isAnimated = false;

	//Setup Collider
	int xOffset = 18;
	int yOffset = 15;
	int width = 28;
	int height = 45;
	float uSize = 1;
	float vSize = 1;
	colliderXOffset = xOffset;
	colliderYOffset = yOffset;
	setCollider(&AABB(x + xOffset, y + yOffset, width, height));
	maxSpeed = 50;
	isColliderDrawn = false;
	
	// Walking Animation
	int numFrames = 1;
	int timeToNextFrame = 300;
	std::vector<AnimationFrame> frames;
	frames.assign(numFrames, AnimationFrame());

	frames[0] = AnimationFrame(0, 5, uSize, vSize);
	//frames[1] = AnimationFrame(1, 0, uSize, vSize);
	Animation animation_walking = Animation("Walking", frames, numFrames);
	animations[animation_walking.name] = AnimationData(animation_walking, timeToNextFrame, true);

	// Idle Animation
	numFrames = 1;
	frames.clear();
	frames.assign(numFrames, AnimationFrame());

	frames[0] = AnimationFrame(0, 5, uSize, vSize);
	Animation animation_idle = Animation("Idle", frames, numFrames);
	animations[animation_idle.name] = AnimationData(animation_idle, timeToNextFrame, true);

	//setAnimation("Walking");
}
Example #15
0
void main( int argc, char ** argv )
{
   Environment env(argc, argv);
   WALBERLA_UNUSED(env);
   walberla::mpi::MPIManager::instance()->useWorldComm();

   //init domain partitioning
   auto forest = blockforest::createBlockForest( AABB(0,0,0,20,20,20), // simulation domain
                                                 Vector3<uint_t>(2,2,2), // blocks in each direction
                                                 Vector3<bool>(false, false, false) // periodicity
                                                 );
   domain::BlockForestDomain domain(forest);

   //init data structures
   data::ParticleStorage ps(100);

   //initialize particle
   auto uid = createSphere(ps, domain);
   WALBERLA_LOG_DEVEL_ON_ROOT("uid: " << uid);

   //init kernels
   mpi::ReduceProperty    RP;
   mpi::SyncNextNeighbors SNN;

   //sync
   SNN(ps, domain);

   auto pIt = ps.find(uid);
   if (pIt != ps.end())
   {
      pIt->getForceRef() += Vec3(real_c(walberla::mpi::MPIManager::instance()->rank()));
   }

   RP.operator()<ForceTorqueNotification>(ps);

   if (walberla::mpi::MPIManager::instance()->rank() == 0)
   {
      WALBERLA_CHECK_FLOAT_EQUAL( pIt->getForce(), Vec3(real_t(28)) );
   } else
   {
      WALBERLA_CHECK_FLOAT_EQUAL( pIt->getForce(), Vec3(real_t(walberla::mpi::MPIManager::instance()->rank())) );
   }
}
Example #16
0
AABB AnimatedTransform::getTranslationBounds() const {
	if (m_tracks.size() == 0) {
		Point p = m_transform(Point(0.0f));
		return AABB(p, p);
	}

	AABB aabb;

	for (size_t i=0; i<m_tracks.size(); ++i) {
		const AbstractAnimationTrack *absTrack = m_tracks[i];
		switch (absTrack->getType()) {
			case AbstractAnimationTrack::ETranslationX:
			case AbstractAnimationTrack::ETranslationY:
			case AbstractAnimationTrack::ETranslationZ: {
					int idx  = absTrack->getType() - AbstractAnimationTrack::ETranslationX;
					const FloatTrack *track =
						static_cast<const FloatTrack *>(absTrack);
					for (size_t j=0; j<track->getSize(); ++j) {
						Float value = track->getValue(j);
						aabb.max[idx] = std::max(aabb.max[idx], value);
						aabb.min[idx] = std::min(aabb.min[idx], value);
					}
				}
				break;

			case AbstractAnimationTrack::ETranslationXYZ: {
					const VectorTrack *track =
						static_cast<const VectorTrack *>(absTrack);
					for (size_t j=0; j<track->getSize(); ++j)
						aabb.expandBy(Point(track->getValue(j)));
				}
				break;
			default:
				break;
		}
	}
	for (int i=0; i<3; ++i) {
		if (aabb.min[i] > aabb.max[i])
			aabb.min[i] = aabb.max[i] = 0.0f;
	}

	return aabb;
}
Example #17
0
const AABB& LightNode::getSelectedComponentsBounds() const {
	// Create a new axis aligned bounding box
	m_aabb_component = AABB();

	if (_light.isProjected()) {
		// Include the according vertices in the AABB
		m_aabb_component.includePoint(_lightTargetInstance.getVertex());
		m_aabb_component.includePoint(_lightRightInstance.getVertex());
		m_aabb_component.includePoint(_lightUpInstance.getVertex());
		m_aabb_component.includePoint(_lightStartInstance.getVertex());
		m_aabb_component.includePoint(_lightEndInstance.getVertex());
	}
	else {
		// Just include the light center, this is the only vertex that may be out of the light volume
		m_aabb_component.includePoint(_lightCenterInstance.getVertex());
	}

	return m_aabb_component;
}
/*!
*  \brief      Transforms an AABB with the passed transformations and return the new AABB.
*  \details    The new AABB has a larger size as the original and the AABB is no more tight!
*  \author     Sascha Kaden
*  \param[in]  original AABB
*  \param[in]  Transform
*  \param[out] transformed AABB
*  \date       2017-06-21
*/
static AABB transformAABB(const AABB &aabb, const Transform &T) {
    Vector3 min = aabb.min();
    Vector3 max = aabb.max();
    Vector4 min4  = util::append<3>(min, 1);
    Vector4 max4  = util::append<3>(max, 1);
    min4 = T * min4;
    max4 = T * max4;
    return AABB(Vector3(min4[0], min4[1], min4[2]), Vector3(max4[0], max4[1], max4[2]));

//    Vector3 center(T.translation());
//    Vector3 radius = Vector3::Zero(3, 1);
//    for (size_t i = 0; i < 3; i++) {
//        for (size_t j = 0; j < 3; j++) {
//            center[i] += T(i, j) * aabb.center()[j];
//            radius[i] += std::abs(T(i, j)) * aabb.diagonal()[j] / 2;
//        }
//    }
//    return AABB(center - radius, center + radius);
}
Example #19
0
/**
 * @brief Moves the given mins/maxs volume through the world from start to end.
 * @param[in] start Start vector to start the trace from
 * @param[in] end End vector to stop the trace at
 * @param[in] size Bounding box size used for tracing
 * @param[in] contentmask Searched content the trace should watch for
 */
void R_Trace (const vec3_t start, const vec3_t end, float size, int contentmask)
{
	vec3_t mins, maxs;
	float frac;
	trace_t tr;
	int i;

	r_locals.tracenum++;

	if (r_locals.tracenum > 0xffff)  /* avoid overflows */
		r_locals.tracenum = 0;

	VectorSet(mins, -size, -size, -size);
	VectorSet(maxs, size, size, size);

	refdef.trace = CM_CompleteBoxTrace(refdef.mapTiles, start, end, AABB(mins, maxs), TRACING_ALL_VISIBLE_LEVELS, contentmask, 0);
	refdef.traceEntity = NULL;

	frac = refdef.trace.fraction;

	/* check bsp models */
	for (i = 0; i < refdef.numEntities; i++) {
		entity_t *ent = R_GetEntity(i);
		const model_t *m = ent->model;

		if (!m || m->type != mod_bsp_submodel)
			continue;

		tr = CM_TransformedBoxTrace(&(refdef.mapTiles->mapTiles[m->bsp.maptile]), start, end, mins, maxs, m->bsp.firstnode,
				contentmask, 0, ent->origin, ent->angles);

		if (tr.fraction < frac) {
			refdef.trace = tr;
			refdef.traceEntity = ent;

			frac = tr.fraction;
		}
	}

	assert(refdef.trace.mapTile >= 0);
	assert(refdef.trace.mapTile < r_numMapTiles);
}
Example #20
0
Chicken::Chicken()
{
   Texture* tex = textureLoader::getTexture("cucco");
   AnimatedSprite sprite = AnimatedSprite(&tex->texture, 0, 0, tex->width, tex->height, 0, 0, 0.5, 1);
   *this = Chicken((Chicken&)sprite);
   type = 1;
   name = "cucco";

   //Setup Collider
   int xOffset = 20;
   int yOffset = 25;
   int width = 20;
   int height = 20;
   float uSize = 0.5;
   float vSize = 1;
   colliderXOffset = xOffset;
   colliderYOffset = yOffset;
   setCollider(&AABB(x + xOffset, y + yOffset, width, height));
   maxSpeed = 50;

   // Walking Animation
   int numFrames = 2;
   int timeToNextFrame = 300;
   std::vector<AnimationFrame> frames;
   frames.assign(numFrames, AnimationFrame());

   frames[0] = AnimationFrame(0, 0, uSize, vSize);
   frames[1] = AnimationFrame(0.5, 0, uSize, vSize);
   Animation animation_walking = Animation("Walking", frames, numFrames);
   animations[animation_walking.name] = AnimationData(animation_walking, timeToNextFrame, true);

   // Idle Animation
   numFrames = 1;
   frames.clear();
   frames.assign(numFrames, AnimationFrame());
   
   frames[0] = AnimationFrame(0, 0, uSize, vSize);
   Animation animation_idle = Animation("Idle", frames, numFrames);
   animations[animation_idle.name] = AnimationData(animation_idle, timeToNextFrame, true);
   
   setAnimation("Walking");
}
Example #21
0
/**
 * @brief Particle tracing with caching
 */
static inline trace_t PTL_Trace (ptl_t *ptl, const vec3_t mins, const vec3_t maxs)
{
	static ptlTraceCache_t ptlCache;
	const float epsilonPos = 3.0f;
	const float epsilonBBox = 1.0f;

	if (VectorCompareEps(ptlCache.start, ptl->origin, epsilonPos) && VectorCompareEps(ptlCache.end, ptl->s, epsilonPos)
			&& VectorCompareEps(ptlCache.mins, mins, epsilonBBox) && VectorCompareEps(ptlCache.maxs, maxs, epsilonBBox)) {
		ptlCache.count++;
		return ptlCache.trace;
	}

	VectorCopy(ptl->origin, ptlCache.start);
	VectorCopy(ptl->s, ptlCache.end);
	VectorCopy(mins, ptlCache.mins);
	VectorCopy(maxs, ptlCache.maxs);

	ptlCache.trace = CL_Trace(ptl->origin, ptl->s, AABB(mins, maxs), nullptr, nullptr, MASK_SOLID, cl.mapMaxLevel - 1);
	return ptlCache.trace;
}
// Generate particle geometry, time is absolute in msecs
void RenderableParticleStage::update(std::size_t time, const Matrix4& viewRotation)
{
	// Invalidate our bounds information
	_bounds = AABB();

	// Check time offset (msecs)
	std::size_t timeOffset = static_cast<std::size_t>(SEC2MS(_stageDef.getTimeOffset()));

	if (time < timeOffset)
	{
		// We're still in the timeoffset zone where particle spawn is inhibited
		_bunches[0].reset();
		_bunches[1].reset();
		return;
	}

	// Time >= timeOffset at this point

	// Get rid of the time offset
	std::size_t localtimeMsec = time - timeOffset;

	// Consider stage orientation (x,y,z,view,aimed)
	calculateStageViewRotation(viewRotation);

	// Make sure the correct bunches are allocated for this stage time
	ensureBunches(localtimeMsec);

	// The 0 bunch is the active one, the 1 bunch is the previous one if not null

	// Tell the particle batches to update their geometry
	if (_bunches[0] != NULL)
	{
		// Get one of our seed values
		_bunches[0]->update(localtimeMsec);
	}

	if (_bunches[1] != NULL)
	{
		_bunches[1]->update(localtimeMsec);
	}
}
Example #23
0
void Bvh::update(std::list<IModel*> &modelList)
{
    if(!bTree)
        return;

    primList.clear();
    
    Point3 minPt(POS_INF, POS_INF,POS_INF);
    Point3 maxPt(-POS_INF,-POS_INF,-POS_INF);
    myTriSize = 0;

    std::list<IModel*>::iterator model;
    std::list<IPrimitive*>::iterator p;

    for( model = modelList.begin(); model != modelList.end(); model++ )
    {
        myTriSize += (*model)->GetPrimitiveCount();

        // update uniform grids min and max values;
        minPt.X() = min((*model)->MinPoint().X(), minPt.X());
        minPt.Y() = min((*model)->MinPoint().Y(), minPt.Y());
        minPt.Z() = min((*model)->MinPoint().Z(), minPt.Z());

        maxPt.X() = max((*model)->MaxPoint().X(), maxPt.X());
        maxPt.Y() = max((*model)->MaxPoint().Y(), maxPt.Y());
        maxPt.Z() = max((*model)->MaxPoint().Z(), maxPt.Z());

        std::list<IPrimitive*>* pl = &(*model)->getPrimitiveList();
        for ( p = pl->begin(); p != pl->end(); p++ )
        {
            primList.push_back( (*p) );
        }
    }

    myBound = AABB( minPt, maxPt );
    unsigned int *temp = new unsigned int[myTriSize];
    // check as we go
    trace(0, temp, 0);
    delete [] temp;
    bTree[0].bound = myBound;
}
Example #24
0
AABB TransformMatrix::transformAABB (AABB aabb) {
    std::array<Vec3f, 24> points;
    //Devant
    points[0] = aabb.position;
    points[1] = Vec3f (aabb.position.x + aabb.width, aabb.position.y, aabb.position.z);
    points[2] = Vec3f (aabb.position.x + aabb.width, aabb.position.y + aabb.height, aabb.position.z);
    points[3] = Vec3f (aabb.position.x, aabb.position.y + aabb.height, aabb.position.z);
    //Derrière
    points[4] = Vec3f (aabb.position.x, aabb.position.y, aabb.position.z - aabb.depth);
    points[5] = Vec3f (aabb.position.x, aabb.position.y + aabb.height, aabb.position.z - aabb.depth);
    points[6] = Vec3f (aabb.position.x + aabb.width, aabb.position.y + aabb.height, aabb.position.z - aabb.depth);
    points[7] = Vec3f (aabb.position.x + aabb.width, aabb.position.y, aabb.position.z - aabb.depth);
    //Dessus
    points[8] = Vec3f (aabb.position.x, aabb.position.y + aabb.height, aabb.position.z);
    points[9] = Vec3f (aabb.position.x + aabb.width, aabb.position.y + aabb.height, aabb.position.z);
    points[10] = Vec3f (aabb.position.x + aabb.width, aabb.position.y + aabb.height, aabb.position.z - aabb.depth);
    points[11] = Vec3f (aabb.position.x, aabb.position.y + aabb.height, aabb.position.z - aabb.depth);
    //Dessous
    points[12] = aabb.position;
    points[13] = Vec3f(aabb.position.x + aabb.width, aabb.position.y, aabb.position.z);
    points[14] = Vec3f(aabb.position.x + aabb.width, aabb.position.y, aabb.position.z - aabb.depth);
    points[15] = Vec3f(aabb.position.x, aabb.position.y, aabb.position.z - aabb.depth);
    //Gauche
    points[16] = aabb.position;
    points[17] = Vec3f(aabb.position.x, aabb.position.y + aabb.height, aabb.position.z);
    points[18] = Vec3f(aabb.position.x, aabb.position.y + aabb.height, aabb.position.z - aabb.depth);
    points[19] = Vec3f (aabb.position.x, aabb.position.y, aabb.position.z - aabb.depth);
    //Droite
    points[20] = Vec3f(aabb.position.x + aabb.width, aabb.position.y, aabb.position.z);
    points[21] = Vec3f(aabb.position.x + aabb.width, aabb.position.y + aabb.height, aabb.position.z);
    points[22] = Vec3f(aabb.position.x + aabb.width, aabb.position.y + aabb.height, aabb.position.z - aabb.depth);
    points[23] = Vec3f (aabb.position.x + aabb.width, aabb.position.y, aabb.position.z - aabb.depth);
    for (unsigned int i = 0; i < points.size(); i++) {

        points[i] = transform(points[i]);
    }
    std::array<std::array<float, 3>, 2> store;
    store = Computer::getExtends(points);
    return AABB(Vec3f(store[0][0], store[1][0],store[2][0]), store[0][1] - store[0][0],store[1][1] - store[1][0], store[2][1] - store[2][0]);
}
Example #25
0
void Model::computeRuntimeData(const uint8* vertices)
{
	int index = 0;
	float bounding_radius_squared = 0;
	Vec3 min_vertex(0, 0, 0);
	Vec3 max_vertex(0, 0, 0);

	for (int i = 0; i < m_meshes.size(); ++i)
	{
		int mesh_vertex_count = m_meshes[i].getAttributeArraySize() /
								m_meshes[i].getVertexDefinition().getStride();
		int mesh_attributes_array_offset =
			m_meshes[i].getAttributeArrayOffset();
		int mesh_vertex_size = m_meshes[i].getVertexDefinition().getStride();
		int mesh_position_attribute_offset =
			m_meshes[i].getVertexDefinition().getOffset(bgfx::Attrib::Position);
		for (int j = 0; j < mesh_vertex_count; ++j)
		{
			m_vertices[index] =
				*(const Vec3*)&vertices[mesh_attributes_array_offset +
										j * mesh_vertex_size +
										mesh_position_attribute_offset];
			bounding_radius_squared = Math::maxValue(
				bounding_radius_squared,
				dotProduct(m_vertices[index], m_vertices[index]) > 0
					? m_vertices[index].squaredLength()
					: 0);
			min_vertex.x = Math::minValue(min_vertex.x, m_vertices[index].x);
			min_vertex.y = Math::minValue(min_vertex.y, m_vertices[index].y);
			min_vertex.z = Math::minValue(min_vertex.z, m_vertices[index].z);
			max_vertex.x = Math::maxValue(max_vertex.x, m_vertices[index].x);
			max_vertex.y = Math::maxValue(max_vertex.y, m_vertices[index].y);
			max_vertex.z = Math::maxValue(max_vertex.z, m_vertices[index].z);
			++index;
		}
	}

	m_bounding_radius = sqrt(bounding_radius_squared);
	m_aabb = AABB(min_vertex, max_vertex);
}
Example #26
0
    void generate2D(Point2* samplesArray, size_t sampleCount, Float radius) {
        Point2 sample;
        bool dist_ok;
        unsigned tries;
        QuadTree samplesTree(AABB(0., 0., 1.));

        // generate a random points
        samplesArray[0] = Point2(m_random->nextFloat(),
                                 m_random->nextFloat());
        samplesTree.insert(samplesArray[0]);

        // generate all others
        for (size_t i = 1; i < sampleCount; ++i) {
            tries = 0;
            do {
                // if too much trying, we narrow the circle around samples
                if( tries >= TRY_LIMIT ) {
                    radius *= FACTOR;
                    tries = 0;
                    //Log(EWarn, "Radius to large ! New radius : %f", radius);
                } else {
                    // generate a new random point
                    sample.x = m_random->nextFloat();
                    sample.y = m_random->nextFloat();
                }

                dist_ok = true;
                if( samplesTree.bNNSearch(sample, radius) ) {
                    dist_ok = false;
                    ++tries;
                }
            } while ( !dist_ok );

            // add sample to the list
            samplesArray[i] = Point2(sample.x, sample.y);
            // ...and to the tree
            samplesTree.insert(samplesArray[i]);
        }
    }
Example #27
0
PhysicsInterface::BodyTemplateObject Bullet::createBodyTemplateFromGeometry(const Vector<Vec3>& vertices,
                                                                            const Vector<RawIndexedTriangle>& triangles,
                                                                            bool deleteOnceUnused,
                                                                            float customCollisionMargin)
{
    if (vertices.empty() || triangles.empty())
        return nullptr;

    auto bodyTemplate = new BodyTemplate(deleteOnceUnused);
    bodyTemplates_.append(bodyTemplate);

    // Copy the geometry data
    bodyTemplate->vertices = vertices;
    bodyTemplate->triangles = triangles;

    // Create interface to the geometry data for Bullet to use
    auto mesh = btIndexedMesh();
    mesh.m_numTriangles = bodyTemplate->triangles.size();
    mesh.m_triangleIndexBase = reinterpret_cast<byte_t*>(bodyTemplate->triangles.getData());
    mesh.m_triangleIndexStride = 3 * sizeof(unsigned int);
    mesh.m_numVertices = bodyTemplate->vertices.size();
    mesh.m_vertexBase = bodyTemplate->vertices.as<byte_t>();
    mesh.m_vertexStride = 3 * sizeof(float);

    auto meshInterface = new btTriangleIndexVertexArray();
    meshInterface->addIndexedMesh(mesh);

    // Calculate an AABB around the geometry
    auto aabb = AABB(bodyTemplate->vertices);

    // Create the collision shape
    bodyTemplate->collisionShape =
        new btBvhTriangleMeshShape(meshInterface, true, toBullet(aabb.getMinimum()), toBullet(aabb.getMaximum()));

    if (customCollisionMargin > 0.0f)
        bodyTemplate->collisionShape->setMargin(customCollisionMargin);

    return bodyTemplate;
}
Example #28
0
ParticleSystemSW::ParticleSystemSW() {

	amount=8;
	emitting=true;
	
	for (int i=0;i<VS::PARTICLE_VAR_MAX;i++) {
		particle_randomness[i]=0.0;
	}
	
	particle_vars[VS::PARTICLE_LIFETIME]=2.0;//
	particle_vars[VS::PARTICLE_SPREAD]=0.2;//
	particle_vars[VS::PARTICLE_GRAVITY]=9.8;//
	particle_vars[VS::PARTICLE_LINEAR_VELOCITY]=0.2;//
	particle_vars[VS::PARTICLE_ANGULAR_VELOCITY]=0.0;//
	particle_vars[VS::PARTICLE_LINEAR_ACCELERATION]=0.0;//
	particle_vars[VS::PARTICLE_RADIAL_ACCELERATION]=0.0;//
	particle_vars[VS::PARTICLE_TANGENTIAL_ACCELERATION]=1.0;//
	particle_vars[VS::PARTICLE_DAMPING]=0.0;//
	particle_vars[VS::PARTICLE_INITIAL_SIZE]=1.0;
	particle_vars[VS::PARTICLE_FINAL_SIZE]=0.8;
	particle_vars[VS::PARTICLE_HEIGHT]=1;
	particle_vars[VS::PARTICLE_HEIGHT_SPEED_SCALE]=1;

	height_from_velocity=false;
	local_coordinates=false;

	particle_vars[VS::PARTICLE_INITIAL_ANGLE]=0.0;//

	gravity_normal=Vector3(0,-1.0,0);
	//emission_half_extents=Vector3(0.1,0.1,0.1);
	emission_half_extents=Vector3(1,1,1);
	color_phase_count=0;
	color_phases[0].pos=0.0;
	color_phases[0].color=Color(1.0,0.0,0.0);
	visibility_aabb=AABB(Vector3(-64,-64,-64),Vector3(128,128,128));

	attractor_count=0;

}
Example #29
0
void CAVMine::Launch(const Vec3 &pos, const Vec3 &dir, const Vec3 &velocity, float speedScale)
{
	// sit flat on the ground.
	Vec3 newDir = dir;
	newDir.z = 0.0f;

	CProjectile::Launch(pos, newDir, velocity, speedScale);

	if(gEnv->bMultiplayer && gEnv->bServer)
	{
		CActor* pOwner = GetWeapon()->GetOwnerActor();
		if(pOwner && pOwner->IsPlayer())
		{
			((CPlayer*)pOwner)->RecordExplosivePlaced(GetEntityId(), 1);
		}
	}

	float boxDimension = 3;
	m_triggerWeight = GetParam("triggerweight", m_triggerWeight);
	boxDimension = GetParam("box_dimension", boxDimension);

	if(gEnv->bServer)
	{
		IEntityTriggerProxy *pTriggerProxy = (IEntityTriggerProxy*)(GetEntity()->GetProxy(ENTITY_PROXY_TRIGGER));
		
		if (!pTriggerProxy)
		{
			GetEntity()->CreateProxy(ENTITY_PROXY_TRIGGER);
			pTriggerProxy = (IEntityTriggerProxy*)GetEntity()->GetProxy(ENTITY_PROXY_TRIGGER);
		}

		if(pTriggerProxy)
		{
			// increase box in the z direction to cope with big vehicles passing over the top (eg NK truck)
			AABB boundingBox = AABB(Vec3(-boxDimension,-boxDimension,0), Vec3(boxDimension,boxDimension,(boxDimension+1)));
			pTriggerProxy->SetTriggerBounds(boundingBox);
		}
	}
}
Example #30
0
 BaseMesh* FixedPlaneMesh::ToBaseMesh() 
 {
     std::vector<Point3D> pts; 
     ListOfvertices results;
     BaseMesh* pMesh = new BaseMesh;
     pMesh->SetTransformedAABB(AABB());
	//auto center = AABB().Center();
	//auto scale = AABB().Diagonal();

     for (int i = 0 ; i < mPolygons.size(); i++)
     {
        for (int j = 0 ; j < mPolygons[i].bplanes.size(); j++)
        {
            int prevPtIdx = j == 0? mPolygons[i].bplanes.size() -1 : j -1;
			Point3D pt = InexactComputePoint(mPolygons[i].splane, mPolygons[i].bplanes[prevPtIdx], mPolygons[i].bplanes[j] );
			//pt = denormalize(pt, center, scale);
			if (!pts.size() || 
				!IsSimilar(pt, pts.back())) 
				pts.push_back(pt);
        }
        auto normal = normalize(mPolygons[i].splane.Normal());
		TrianglatePolygon(normal, pts, results);
		//catch (...){
		//	wchar_t ch[64];
		//	swprintf(ch, 64, L"Error, %u", i);
		//	OutputDebugString(ch);
		//	results.clear();
		//}

        for (int k = 0 ; k < results.size(); k+=3)
        {   
            pMesh->Add(results[k], results[k+1], results[k+2], normal);
        }
        pts.clear();
		results.clear();
     }
     pMesh->GenID();
     return pMesh;
 }