Ejemplo n.º 1
0
void ConstructRegionBrushes(scene::Node* brushes[6], const Vector3& region_mins, const Vector3& region_maxs)
{
  {
    // set mins
    Vector3 mins(region_mins[0]-32, region_mins[1]-32, region_mins[2]-32);

    // vary maxs
    for(std::size_t i=0; i<3; i++)
    {
      Vector3 maxs(region_maxs[0]+32, region_maxs[1]+32, region_maxs[2]+32);
      maxs[i] = region_mins[i];
      Brush_ConstructCuboid(*Node_getBrush(*brushes[i]), aabb_for_minmax(mins, maxs), texdef_name_default(), TextureProjection());
    }
  }

  {
    // set maxs
    Vector3 maxs(region_maxs[0]+32, region_maxs[1]+32, region_maxs[2]+32);

    // vary mins
    for(std::size_t i=0; i<3; i++)
    {
      Vector3 mins(region_mins[0]-32, region_mins[1]-32, region_mins[2]-32);
      mins[i] = region_maxs[i];
      Brush_ConstructCuboid(*Node_getBrush(*brushes[i+3]), aabb_for_minmax(mins, maxs), texdef_name_default(), TextureProjection());
    }
  }
}
Ejemplo n.º 2
0
void ConstructRegionBrushes(scene::INodePtr brushes[6], const Vector3& region_mins, const Vector3& region_maxs)
{
	const float THICKNESS = 10;
  {
    // set mins
    Vector3 mins(region_mins[0]-THICKNESS, region_mins[1]-THICKNESS, region_mins[2]-THICKNESS);

    // vary maxs
    for(std::size_t i=0; i<3; i++)
    {
      Vector3 maxs(region_maxs[0]+THICKNESS, region_maxs[1]+THICKNESS, region_maxs[2]+THICKNESS);
      maxs[i] = region_mins[i];
      Brush_ConstructCuboid(*Node_getBrush(brushes[i]), 
      						AABB::createFromMinMax(mins, maxs),
      						texdef_name_default(), 
      						TextureProjection());
    }
  }

  {
    // set maxs
    Vector3 maxs(region_maxs[0]+THICKNESS, region_maxs[1]+THICKNESS, region_maxs[2]+THICKNESS);

    // vary mins
    for(std::size_t i=0; i<3; i++)
    {
      Vector3 mins(region_mins[0]-THICKNESS, region_mins[1]-THICKNESS, region_mins[2]-THICKNESS);
      mins[i] = region_maxs[i];
      Brush_ConstructCuboid(*Node_getBrush(brushes[i+3]), 
      						AABB::createFromMinMax(mins, maxs),
      						texdef_name_default(),
      						TextureProjection());
    }
  }
}
Ejemplo n.º 3
0
Q3BSPNode *Q3BSPRep::createNode( int n ){
	q3_node *q3node=(q3_node*)header.dir[3].lump+n;
	q3_plane *q3plane=(q3_plane*)header.dir[2].lump+q3node->plane;

	Q3BSPNode *node=new Q3BSPNode;

	Vector mins( q3node->mins[0],q3node->mins[1],q3node->mins[2] );
	Vector maxs( q3node->maxs[0],q3node->maxs[1],q3node->maxs[2] );

	node->box=Box( tf(mins) );
	node->box.update( tf(maxs) );
	node->plane.n=tf(q3plane->normal);
	node->plane.d=-q3plane->distance;

	for( int k=0;k<2;++k ){
		if( q3node->children[k]>=0 ){
			node->nodes[k]=createNode( q3node->children[k] );
			node->leafs[k]=0;
		}else{
			node->leafs[k]=createLeaf( -q3node->children[k]-1 );
			node->nodes[k]=0;
		}
	}

	return node;
}
Ejemplo n.º 4
0
void Brush_ConstructCuboid(Brush& brush, const AABB& bounds, const std::string& shader, const TextureProjection& projection)
{
  const unsigned char box[3][2] = { { 0, 1 }, { 2, 0 }, { 1, 2 } };
  Vector3 mins(bounds.origin - bounds.extents);
  Vector3 maxs(bounds.origin + bounds.extents);

  brush.clear();
  brush.reserve(6);

  {
    for(int i=0; i < 3; ++i)
    {
      Vector3 planepts1(maxs);
      Vector3 planepts2(maxs);
      planepts2[box[i][0]] = mins[box[i][0]];
      planepts1[box[i][1]] = mins[box[i][1]];

      brush.addPlane(maxs, planepts1, planepts2, shader, projection);
    }
  }
  {
    for(int i=0; i < 3; ++i)
    {
      Vector3 planepts1(mins);
      Vector3 planepts2(mins);
      planepts1[box[i][0]] = maxs[box[i][0]];
      planepts2[box[i][1]] = maxs[box[i][1]];

      brush.addPlane(mins, planepts1, planepts2, shader, projection);
    }
  }
}
Ejemplo n.º 5
0
void Clipper::getPlanePoints(Vector3 planepts[3], const AABB& bounds) const {
	ASSERT_MESSAGE(valid(), "clipper points not initialised");

	planepts[0] = _clipPoints[0]._coords;
	planepts[1] = _clipPoints[1]._coords;
	planepts[2] = _clipPoints[2]._coords;

	Vector3 maxs(bounds.origin + bounds.extents);
	Vector3 mins(bounds.origin - bounds.extents);

	if (!_clipPoints[2].isSet()) {
		int n = (_viewType == XY) ? 2 : (_viewType == YZ) ? 0 : 1;
		int x = (n == 0) ? 1 : 0;
		int y = (n == 2) ? 1 : 2;

		if (n == 1) // on viewtype XZ, flip clip points
		{
			planepts[0][n] = maxs[n];
			planepts[1][n] = maxs[n];
			planepts[2][x] = _clipPoints[0]._coords[x];
			planepts[2][y] = _clipPoints[0]._coords[y];
			planepts[2][n] = mins[n];
		}
		else {
			planepts[0][n] = mins[n];
			planepts[1][n] = mins[n];
			planepts[2][x] = _clipPoints[0]._coords[x];
			planepts[2][y] = _clipPoints[0]._coords[y];
			planepts[2][n] = maxs[n];
		}
	}
}
Ejemplo n.º 6
0
Vertex3D_PCT* Fonts::CreateCharactersVerts(Vector3 startPos, std::string words, float scale, RGBA& color, int& size)
{
	size_t wordsLength = words.length();
	Vertex3D_PCT* verts = new Vertex3D_PCT[wordsLength*6];
	float startPosX = startPos.x;
	float startPosY = startPos.y;
	for (size_t i = 0; i < wordsLength; i++)
	{
		for (unsigned int j = 0; j<m_characters.size(); j++)
		{
			if (m_characters[j].m_ID != words[i])
			{
				continue;
			}
			Vector2 mins(startPosX + scale*m_characters[j].m_OffsetXY.x, startPosY - scale*(m_characters[j].m_OffsetXY.y + m_characters[j].m_GLYPHWH.y));
			Vector2 maxs(startPosX + scale*(m_characters[j].m_OffsetXY.x + m_characters[j].m_GLYPHWH.x), startPosY - scale*(m_characters[j].m_OffsetXY.y));
			verts[i*6] = Vertex3D_PCT(Vector3(mins.x, maxs.y, startPos.z), Vector2(m_characters[j].m_XY.x, m_characters[j].m_XY.y), color);
			verts[i*6+1] = Vertex3D_PCT(Vector3(mins.x, mins.y, startPos.z), Vector2(m_characters[j].m_XY.x, m_characters[j].m_XY.y + m_characters[j].m_WH.y), color);
			verts[i*6+2] = Vertex3D_PCT(Vector3(maxs.x, mins.y, startPos.z), Vector2(m_characters[j].m_XY.x + m_characters[j].m_WH.x, m_characters[j].m_XY.y + m_characters[j].m_WH.y), color);
															
			verts[i * 6 + 3] = Vertex3D_PCT(Vector3(mins.x, maxs.y, startPos.z), Vector2(m_characters[j].m_XY.x, m_characters[j].m_XY.y), color);
			verts[i * 6 + 4] = Vertex3D_PCT(Vector3(maxs.x, mins.y, startPos.z), Vector2(m_characters[j].m_XY.x + m_characters[j].m_WH.x, m_characters[j].m_XY.y + m_characters[j].m_WH.y), color);
			verts[i * 6 + 5] = Vertex3D_PCT(Vector3(maxs.x, maxs.y, startPos.z), Vector2(m_characters[j].m_XY.x + m_characters[j].m_WH.x, m_characters[j].m_XY.y), color);


			startPosX += scale*m_characters[j].m_XAdvance;
			break;
		}
	}
	size = wordsLength*6;
	return verts;
}
Ejemplo n.º 7
0
void glBox(idVec3_t &color, idVec3_t &point, float size) {
	idVec3_t mins(point);
	idVec3_t maxs(point);
	mins[0] -= size;
	mins[1] += size;
	mins[2] -= size;
	maxs[0] += size;
	maxs[1] -= size;
	maxs[2] += size;
	qglColor3fv(color);
	qglBegin(GL_LINE_LOOP);
	qglVertex3f(mins[0],mins[1],mins[2]);
	qglVertex3f(maxs[0],mins[1],mins[2]);
	qglVertex3f(maxs[0],maxs[1],mins[2]);
	qglVertex3f(mins[0],maxs[1],mins[2]);
	qglEnd();
	qglBegin(GL_LINE_LOOP);
	qglVertex3f(mins[0],mins[1],maxs[2]);
	qglVertex3f(maxs[0],mins[1],maxs[2]);
	qglVertex3f(maxs[0],maxs[1],maxs[2]);
	qglVertex3f(mins[0],maxs[1],maxs[2]);
	qglEnd();

	qglBegin(GL_LINES);
  	qglVertex3f(mins[0],mins[1],mins[2]);
	qglVertex3f(mins[0],mins[1],maxs[2]);
	qglVertex3f(mins[0],maxs[1],maxs[2]);
	qglVertex3f(mins[0],maxs[1],mins[2]);
	qglVertex3f(maxs[0],mins[1],mins[2]);
	qglVertex3f(maxs[0],mins[1],maxs[2]);
	qglVertex3f(maxs[0],maxs[1],maxs[2]);
	qglVertex3f(maxs[0],maxs[1],mins[2]);
	qglEnd();

}
Ejemplo n.º 8
0
    std::pair<Float3, Float3> TransformBoundingBox(const Float3x4& transformation, std::pair<Float3, Float3> boundingBox)
    {
        Float3 corners[] = 
        {
            Float3(  boundingBox.first[0], boundingBox.first[1],  boundingBox.first[2] ),
            Float3( boundingBox.second[0], boundingBox.first[1],  boundingBox.first[2] ),
            Float3(  boundingBox.first[0], boundingBox.second[1], boundingBox.first[2] ),
            Float3( boundingBox.second[0], boundingBox.second[1], boundingBox.first[2] ),

            Float3(  boundingBox.first[0], boundingBox.first[1],  boundingBox.second[2] ),
            Float3( boundingBox.second[0], boundingBox.first[1],  boundingBox.second[2] ),
            Float3(  boundingBox.first[0], boundingBox.second[1], boundingBox.second[2] ),
            Float3( boundingBox.second[0], boundingBox.second[1], boundingBox.second[2] )
        };

        for (unsigned c=0; c<dimof(corners); ++c) {
            corners[c] = TransformPoint(transformation, corners[c]);
        }

        Float3 mins(FLT_MAX, FLT_MAX, FLT_MAX), maxs(-FLT_MAX, -FLT_MAX, -FLT_MAX);
        for (unsigned c=0; c<dimof(corners); ++c) {
            mins[0] = std::min(mins[0], corners[c][0]);
            mins[1] = std::min(mins[1], corners[c][1]);
            mins[2] = std::min(mins[2], corners[c][2]);

            maxs[0] = std::max(maxs[0], corners[c][0]);
            maxs[1] = std::max(maxs[1], corners[c][1]);
            maxs[2] = std::max(maxs[2], corners[c][2]);
        }

        return std::make_pair(mins, maxs);
    }
//=mins if dir < 0
//=maxs if dir >= 0
array minmaxs(const array f1,const array f2,const array df,const array dir )
{
  array condition = (dir>=0);
  array res = condition*maxs(f1, f2, df)
    +(1-condition)*mins(f1, f2, df);
  res.eval();
  return res;
}
Ejemplo n.º 10
0
	void Cone::generate (Brush& brush, const AABB& bounds, std::size_t sides, const TextureProjection& projection,
			const std::string& shader)
	{
		if (sides < _minSides) {
			gtkutil::errorDialog(_("Too few sides for constructing the prism, minimum is 3"));
			return;
		}
		if (sides > _maxSides) {
			gtkutil::errorDialog(_("Too many sides for constructing the prism, maximum is 32"));
			return;
		}

		brush.clear();
		brush.reserve(sides + 1);

		Vector3 mins(bounds.origin - bounds.extents);
		Vector3 maxs(bounds.origin + bounds.extents);

		float radius = maxExtent(bounds.extents);
		const Vector3& mid = bounds.origin;
		Vector3 planepts[3];

		planepts[0][0] = mins[0];
		planepts[0][1] = mins[1];
		planepts[0][2] = mins[2];
		planepts[1][0] = maxs[0];
		planepts[1][1] = mins[1];
		planepts[1][2] = mins[2];
		planepts[2][0] = maxs[0];
		planepts[2][1] = maxs[1];
		planepts[2][2] = mins[2];

		brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection);

		for (std::size_t i = 0; i < sides; ++i) {
			double sv = sin(i * 3.14159265 * 2 / sides);
			double cv = cos(i * 3.14159265 * 2 / sides);

			planepts[0][0] = static_cast<float> (floor(mid[0] + radius * cv + 0.5));
			planepts[0][1] = static_cast<float> (floor(mid[1] + radius * sv + 0.5));
			planepts[0][2] = mins[2];

			planepts[1][0] = mid[0];
			planepts[1][1] = mid[1];
			planepts[1][2] = maxs[2];

			planepts[2][0] = static_cast<float> (floor(planepts[0][0] - radius * sv + 0.5));
			planepts[2][1] = static_cast<float> (floor(planepts[0][1] + radius * cv + 0.5));
			planepts[2][2] = maxs[2];

			brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection);
		}
	}
//#################### PUBLIC METHODS ####################
void BroadPhaseCollisionDetector::add_object(const PhysicsObject_Ptr& object)
{
	// Step 1:	Determine the lowest grid for the object, based on the maximum dimension of
	// the bounding box of its movement.
	Vector3d halfDimensions = object->bounds(m_boundsManager)->half_dimensions();
	Vector3d previousPos = object->previous_position() ? *object->previous_position() : object->position();
	Vector3d pos = object->position();

	Vector3d mins(std::min(previousPos.x, pos.x), std::min(previousPos.y, pos.y), std::min(previousPos.z, pos.z));
	mins -= halfDimensions;
	Vector3d maxs(std::max(previousPos.x, pos.x), std::max(previousPos.y, pos.y), std::max(previousPos.z, pos.z));
	maxs += halfDimensions;

	Vector3d size = maxs - mins;
	double maxDimension = std::max(std::max(size.x, size.y), size.z);

	HGrid::iterator lowestGrid = m_hgrid.lower_bound(maxDimension);

	// Step 2:	Determine which cells it overlaps on the lowest grid just identified.
	std::set<CellIndex> cells = determine_overlapped_cells(mins, maxs, lowestGrid->first);

	// Step 3:	Insert the object into every grid above (and including) the lowest one,
	//			flagging collisions where applicable.
	for(HGrid::iterator it=lowestGrid, iend=m_hgrid.end(); it!=iend; ++it)
	{
		bool lowest = it == lowestGrid;

		if(!lowest)
		{
			// Propagate the cells up to the next layer.
			cells = propagate_cells(cells);
		}

		for(std::set<CellIndex>::const_iterator jt=cells.begin(), jend=cells.end(); jt!=jend; ++jt)
		{
			CellData& data = it->second[*jt];

			// Look through the objects already overlapping the cell and flag any necessary collisions.
			for(CellData::const_iterator kt=data.begin(), kend=data.end(); kt!=kend; ++kt)
			{
				if(lowest || kt->second)	// if this is the lowest layer for at least one of the objects
				{
					m_potentialCollisions.insert(std::make_pair(kt->first, object));
				}
			}

			// Add the object itself to the set of those overlapping the cell.
			data.push_back(std::make_pair(object, lowest));
		}
	}
}
Ejemplo n.º 12
0
void Brush_ConstructCone(Brush& brush, const AABB& bounds, std::size_t sides, const char* shader, const TextureProjection& projection)
{
  if(sides < c_brushCone_minSides)
  {
    globalErrorStream() << c_brushCone_name << ": sides " << Unsigned(sides) << ": too few sides, minimum is " << Unsigned(c_brushCone_minSides) << "\n";
    return;
  }
  if(sides > c_brushCone_maxSides)
  {
    globalErrorStream() << c_brushCone_name << ": sides " << Unsigned(sides) << ": too many sides, maximum is " << Unsigned(c_brushCone_maxSides) << "\n";
    return;
  }

  brush.undoSave();
  brush.clear();
  brush.reserve(sides+1);

  Vector3 mins(vector3_subtracted(bounds.origin, bounds.extents));
  Vector3 maxs(vector3_added(bounds.origin, bounds.extents));

  float radius = max_extent(bounds.extents);
  const Vector3& mid = bounds.origin;
  Vector3 planepts[3];

  planepts[0][0] = mins[0];planepts[0][1] = mins[1];planepts[0][2] = mins[2];
  planepts[1][0] = maxs[0];planepts[1][1] = mins[1];planepts[1][2] = mins[2];
  planepts[2][0] = maxs[0];planepts[2][1] = maxs[1];planepts[2][2] = mins[2];

  brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection);

  for (std::size_t i=0 ; i<sides ; ++i)
  {
    double sv = sin (i*3.14159265*2/sides);
    double cv = cos (i*3.14159265*2/sides);

    planepts[0][0] = static_cast<float>(floor(mid[0]+radius*cv+0.5));
    planepts[0][1] = static_cast<float>(floor(mid[1]+radius*sv+0.5));
    planepts[0][2] = mins[2];

    planepts[1][0] = mid[0];
    planepts[1][1] = mid[1];
    planepts[1][2] = maxs[2];

    planepts[2][0] = static_cast<float>(floor(planepts[0][0] - radius * sv + 0.5));
    planepts[2][1] = static_cast<float>(floor(planepts[0][1] + radius * cv + 0.5));
    planepts[2][2] = maxs[2];

    brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection);
  }
}
Ejemplo n.º 13
0
NTBVertex3D_PCT* Fonts::CreateNTBVertsFromStringVector(Vector3 startPos, std::vector<std::string>& currentStringVec, float scale, RGBA& color, int& size)
{
	size = 0;
	std::vector<NTBVertex3D_PCT> verts;
	RGBA fadeColor = RGBA(color.GetRed(), color.GetGreen(), color.GetBlue(), fadeScale);
	for (int k = (int)currentStringVec.size() - 1; k >= 0; k--)
	{
		size_t wordsLength = currentStringVec[k].length();

		float startPosX = startPos.x;
		float startPosY = startPos.y;
		float yOffsetFloat = 0.0f;
		m_curserPos.x = startPosX;
		for (size_t i = 0; i < wordsLength; i++)
		{
			for (unsigned int j = 0; j < m_characters.size(); j++)
			{
				if (m_characters[j].m_ID != currentStringVec[k][i])
				{
					continue;
				}
				Vector2 mins(startPosX + scale*m_characters[j].m_OffsetXY.x, startPosY - scale*(m_characters[j].m_OffsetXY.y + m_characters[j].m_GLYPHWH.y));
				Vector2 maxs(startPosX + scale*(m_characters[j].m_OffsetXY.x + m_characters[j].m_GLYPHWH.x), startPosY - scale*(m_characters[j].m_OffsetXY.y));
				mins += Vector2(0.0f, m_scale * (currentStringVec.size() - k - 1));
				maxs += Vector2(0.0f, m_scale * (currentStringVec.size() - k - 1));
				verts.push_back(NTBVertex3D_PCT(Vector3(mins.x, maxs.y - yOffsetFloat, startPos.z), Vector2(m_characters[j].m_XY.x, m_characters[j].m_XY.y), Vector3(0.0F, 0.0F, 0.0F), Vector3(0.0F, 0.0F, 0.0F), Vector3(0.0F, 0.0F, 0.0F), fadeColor));
				verts.push_back(NTBVertex3D_PCT(Vector3(mins.x, mins.y - yOffsetFloat, startPos.z), Vector2(m_characters[j].m_XY.x, m_characters[j].m_XY.y + m_characters[j].m_WH.y), Vector3(0.0F, 0.0F, 0.0F), Vector3(0.0F, 0.0F, 0.0F), Vector3(0.0F, 0.0F, 0.0F), fadeColor));
				verts.push_back(NTBVertex3D_PCT(Vector3(maxs.x, mins.y - yOffsetFloat, startPos.z), Vector2(m_characters[j].m_XY.x + m_characters[j].m_WH.x, m_characters[j].m_XY.y + m_characters[j].m_WH.y), Vector3(0.0F, 0.0F, 0.0F), Vector3(0.0F, 0.0F, 0.0F), Vector3(0.0F, 0.0F, 0.0F), fadeColor));
								
				verts.push_back(NTBVertex3D_PCT(Vector3(mins.x, maxs.y - yOffsetFloat, startPos.z), Vector2(m_characters[j].m_XY.x, m_characters[j].m_XY.y), Vector3(0.0F, 0.0F, 0.0F), Vector3(0.0F, 0.0F, 0.0F), Vector3(0.0F, 0.0F, 0.0F), fadeColor));
				verts.push_back(NTBVertex3D_PCT(Vector3(maxs.x, mins.y - yOffsetFloat, startPos.z), Vector2(m_characters[j].m_XY.x + m_characters[j].m_WH.x, m_characters[j].m_XY.y + m_characters[j].m_WH.y), Vector3(0.0F, 0.0F, 0.0F), Vector3(0.0F, 0.0F, 0.0F), Vector3(0.0F, 0.0F, 0.0F), fadeColor));
				verts.push_back(NTBVertex3D_PCT(Vector3(maxs.x, maxs.y - yOffsetFloat, startPos.z), Vector2(m_characters[j].m_XY.x + m_characters[j].m_WH.x, m_characters[j].m_XY.y), Vector3(0.0F, 0.0F, 0.0F), Vector3(0.0F, 0.0F, 0.0F), Vector3(0.0F, 0.0F, 0.0F), fadeColor));
				startPosX += scale*m_characters[j].m_XAdvance;

				break;
			}

		}
		yOffsetFloat += 0.0f;
	}
	NTBVertex3D_PCT* passOutVerts = new NTBVertex3D_PCT[verts.size()];
	memcpy(passOutVerts, verts.data(), verts.size()*sizeof(NTBVertex3D_PCT));
	size = verts.size();
	return passOutVerts;
}
Ejemplo n.º 14
0
inline HRectBound<MetricType, ElemType>& HRectBound<MetricType, ElemType>::operator|=(
    const MatType& data)
{
  Log::Assert(data.n_rows == dim);

  arma::Col<ElemType> mins(min(data, 1));
  arma::Col<ElemType> maxs(max(data, 1));

  minWidth = std::numeric_limits<ElemType>::max();
  for (size_t i = 0; i < dim; i++)
  {
    bounds[i] |= math::RangeType<ElemType>(mins[i], maxs[i]);
    const ElemType width = bounds[i].Width();
    if (width < minWidth)
      minWidth = width;
  }

  return *this;
}
Ejemplo n.º 15
0
Vertex3D_PCT* Fonts::CreateConsoleCharactersVerts(Vector3 startPos, float scale, RGBA& color, int& size)
{
	size = 0;
	std::vector<Vertex3D_PCT> verts;
	RGBA fadeColor = RGBA(color.GetRed(), color.GetGreen(), color.GetBlue(), fadeScale);
	for (int k = (int)m_log.size()-1; k >= 0; k--)
	{
		size_t wordsLength = m_log[k].length();
		
		float startPosX = startPos.x;
		float startPosY = startPos.y;
		m_curserPos.x = startPosX;
		for (size_t i = 0; i < wordsLength; i++)
		{
			for (unsigned int j = 0; j < m_characters.size(); j++)
			{
				if (m_characters[j].m_ID != m_log[k][i])
				{
					continue;
				}
				Vector2 mins(startPosX + scale*m_characters[j].m_OffsetXY.x, startPosY - scale*(m_characters[j].m_OffsetXY.y + m_characters[j].m_GLYPHWH.y));
				Vector2 maxs(startPosX + scale*(m_characters[j].m_OffsetXY.x + m_characters[j].m_GLYPHWH.x), startPosY - scale*(m_characters[j].m_OffsetXY.y));
				mins += Vector2(0.0f, m_scale * (m_log.size() - k - 1));
				maxs += Vector2(0.0f, m_scale * (m_log.size() - k - 1));
				verts.push_back(Vertex3D_PCT(Vector3(mins.x, maxs.y, startPos.z), Vector2(m_characters[j].m_XY.x, m_characters[j].m_XY.y), fadeColor));
				verts.push_back(Vertex3D_PCT(Vector3(mins.x, mins.y, startPos.z), Vector2(m_characters[j].m_XY.x, m_characters[j].m_XY.y + m_characters[j].m_WH.y), fadeColor));
				verts.push_back(Vertex3D_PCT(Vector3(maxs.x, mins.y, startPos.z), Vector2(m_characters[j].m_XY.x + m_characters[j].m_WH.x, m_characters[j].m_XY.y + m_characters[j].m_WH.y), fadeColor));
					 
				verts.push_back(Vertex3D_PCT(Vector3(mins.x, maxs.y, startPos.z), Vector2(m_characters[j].m_XY.x, m_characters[j].m_XY.y), fadeColor));
				verts.push_back(Vertex3D_PCT(Vector3(maxs.x, mins.y, startPos.z), Vector2(m_characters[j].m_XY.x + m_characters[j].m_WH.x, m_characters[j].m_XY.y + m_characters[j].m_WH.y), fadeColor));
				verts.push_back(Vertex3D_PCT(Vector3(maxs.x, maxs.y, startPos.z), Vector2(m_characters[j].m_XY.x + m_characters[j].m_WH.x, m_characters[j].m_XY.y), fadeColor));
				startPosX += scale*m_characters[j].m_XAdvance;
				
				break;
			}
			
		}
	}
	Vertex3D_PCT* passOutVerts = new Vertex3D_PCT[verts.size()];
	memcpy(passOutVerts,verts.data(),verts.size()*sizeof(Vertex3D_PCT));
	size = verts.size();
	return passOutVerts;
}
void CPhysicsCollision::InitBBoxCache()
{
	Vector boxVerts[8], *ppVerts[8];
	Vector mins(-16,-16,0), maxs(16,16,72);
	// init with the player box
	InitBoxVerts( boxVerts, ppVerts, mins, maxs );
	// Generate a convex hull from the verts
	CPhysConvex *pConvex = ConvexFromVerts( ppVerts, 8 );
	IVP_Compact_Poly_Point *pPoints = reinterpret_cast<IVP_Compact_Ledge *>(pConvex)->get_point_array();
	for ( int i = 0; i < 8; i++ )
	{
		int nearest = -1;
		float minDist = 0.1;
		Vector tmp;
		ConvertPositionToHL( pPoints[i], tmp );
		for ( int j = 0; j < 8; j++ )
		{
			float dist = (boxVerts[j] - tmp).Length();
			if ( dist < minDist )
			{
				minDist = dist;
				nearest = j;
			}
		}
		
		m_bboxVertMap[i] = nearest;

#if _DEBUG
		for ( int k = 0; k < i; k++ )
		{
			Assert( m_bboxVertMap[k] != m_bboxVertMap[i] );
		}
#endif
		// NOTE: If this is wrong, you can disable FAST_BBOX above to fix
		AssertMsg( nearest != -1, "CPhysCollide: Vert map is wrong\n" );
	}
	CPhysCollide *pCollide = ConvertConvexToCollide( &pConvex, 1 );
	AddBBoxCache( pCollide, mins, maxs );
}
Ejemplo n.º 17
0
 int maximumGap(vector<int>& nums) {
     if (nums.size() < 2)
         return 0;
     int min = *min_element(nums.begin(), nums.end());
     int mymax = *max_element(nums.begin(), nums.end());
     int range = mymax - min;
     int nbuckets = nums.size();
     vector<int> mins(nbuckets, INT_MAX), maxs(nbuckets, INT_MIN);
     for(auto x : nums) {
         int index = ((double)(x-min)*(nbuckets-1))/range;
         if (mins[index] > x) mins[index] = x;
         if (maxs[index] < x) maxs[index] = x;
     }
     int prev = maxs[0];
     mymax = 0;
     for (int i = 1; i < nbuckets; i++) {
         if (mins[i] == INT_MAX) continue;
         mymax = max(mymax, mins[i]-prev);
         prev = maxs[i];
     }
     return mymax;
 }
Ejemplo n.º 18
0
/*
================
glBox
================
*/
void glBox(idVec4 &color, idVec3 &point, float size) {
	idVec3 mins(point);
	idVec3 maxs(point);
	mins[0] -= size;
	mins[1] += size;
	mins[2] -= size;
	maxs[0] += size;
	maxs[1] -= size;
	maxs[2] += size;
	idVec4	saveColor;
	qglGetFloatv(GL_CURRENT_COLOR, saveColor.ToFloatPtr());
	qglColor3fv( color.ToFloatPtr() );
	qglBegin(GL_LINE_LOOP);
	qglVertex3f(mins[0],mins[1],mins[2]);
	qglVertex3f(maxs[0],mins[1],mins[2]);
	qglVertex3f(maxs[0],maxs[1],mins[2]);
	qglVertex3f(mins[0],maxs[1],mins[2]);
	qglEnd();
	qglBegin(GL_LINE_LOOP);
	qglVertex3f(mins[0],mins[1],maxs[2]);
	qglVertex3f(maxs[0],mins[1],maxs[2]);
	qglVertex3f(maxs[0],maxs[1],maxs[2]);
	qglVertex3f(mins[0],maxs[1],maxs[2]);
	qglEnd();

	qglBegin(GL_LINES);
  	qglVertex3f(mins[0],mins[1],mins[2]);
	qglVertex3f(mins[0],mins[1],maxs[2]);
	qglVertex3f(mins[0],maxs[1],maxs[2]);
	qglVertex3f(mins[0],maxs[1],mins[2]);
	qglVertex3f(maxs[0],mins[1],mins[2]);
	qglVertex3f(maxs[0],mins[1],maxs[2]);
	qglVertex3f(maxs[0],maxs[1],maxs[2]);
	qglVertex3f(maxs[0],maxs[1],mins[2]);
	qglEnd();
	qglColor4fv(saveColor.ToFloatPtr());

}
Ejemplo n.º 19
0
void CDecalsDrawerGL4::UpdateBoundingBox(SDecalGroup& g)
{
	if (g.ids.front() == 0) {
		g.boundAABB.fill(float4());
		return;
	}

	// compute the AABB
	float3 mins(1e9,1e9,1e9), maxs(-1e9,-1e9,-1e9);
	for (int idx: g.ids) {
		if (idx == 0)
			break;

		Decal& d = decals[idx];
		const auto e = GetEdgePoinsOfDecal(d);
		for (const float2& p: e) {
			mins = float3::min(mins, float3(p.x, d.pos.y - d.size.x, p.y));
			maxs = float3::max(maxs, float3(p.x, d.pos.y + d.size.x, p.y));
		}
	}
	mins.y = std::max(mins.y, readMap->GetCurrMinHeight());
	maxs.y = std::min(maxs.y, readMap->GetCurrMaxHeight());
	g.boundAABB = {{ float4(mins, 0.f), float4(maxs, 0.f) }};
}
//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CFuncLadder::Spawn()
{
	BaseClass::Spawn();

	// Entity is symbolid
	SetSolid( SOLID_NONE );
	SetMoveType( MOVETYPE_NONE );
	SetCollisionGroup( COLLISION_GROUP_NONE );
	
	//AddFlag( FL_WORLDBRUSH );
	SetModelName( NULL_STRING );

	// Make entity invisible
	AddEffects( EF_NODRAW );
	// No model but should still network
	AddEFlags( EFL_FORCE_CHECK_TRANSMIT );

	Vector playerMins = VEC_HULL_MIN;
	Vector playerMaxs = VEC_HULL_MAX;

	// This will swap them if they are inverted
	SetEndPoints( m_vecPlayerMountPositionTop, m_vecPlayerMountPositionBottom );

#if !defined( CLIENT_DLL )
	trace_t bottomtrace, toptrace;
	UTIL_TraceHull( m_vecPlayerMountPositionBottom, m_vecPlayerMountPositionBottom, 
		playerMins, playerMaxs, MASK_PLAYERSOLID_BRUSHONLY, NULL, COLLISION_GROUP_PLAYER_MOVEMENT, &bottomtrace );
	UTIL_TraceHull( m_vecPlayerMountPositionTop, m_vecPlayerMountPositionTop, 
		playerMins, playerMaxs, MASK_PLAYERSOLID_BRUSHONLY, NULL, COLLISION_GROUP_PLAYER_MOVEMENT, &toptrace );

	if ( bottomtrace.startsolid || toptrace.startsolid )
	{
		if ( bottomtrace.startsolid )
		{
			DevMsg( 1, "Warning, funcladder with blocked bottom point (%.2f %.2f %.2f) stuck in (%s)\n",
				m_vecPlayerMountPositionBottom.GetX(),
				m_vecPlayerMountPositionBottom.GetY(),
				m_vecPlayerMountPositionBottom.GetZ(),
				bottomtrace.m_pEnt 
					? 
					UTIL_VarArgs( "%s/%s", bottomtrace.m_pEnt->GetClassname(), bottomtrace.m_pEnt->GetEntityName().ToCStr() ) 
					//UTIL_VarArgs( "%s/%s", bottomtrace.m_pEnt->GetClassname(), STRING(bottomtrace.m_pEnt->GetEntityName()) ) ?
					: 
					"NULL" );
		}
		if ( toptrace.startsolid )
		{
			DevMsg( 1, "Warning, funcladder with blocked top point (%.2f %.2f %.2f) stuck in (%s)\n",
				m_vecPlayerMountPositionTop.GetX(),
				m_vecPlayerMountPositionTop.GetY(),
				m_vecPlayerMountPositionTop.GetZ(),
				toptrace.m_pEnt 
					? 
					UTIL_VarArgs( "%s/%s", toptrace.m_pEnt->GetClassname(), toptrace.m_pEnt->GetEntityName().ToCStr() ) 
					//UTIL_VarArgs( "%s/%s", toptrace.m_pEnt->GetClassname(), STRING(toptrace.m_pEnt->GetEntityName()) ) ?
					: 
					"NULL" );
		}

		// Force geometry overlays on, but only if developer 2 is set...
		if ( developer.GetInt() > 1 )
		{
			m_debugOverlays |= OVERLAY_TEXT_BIT;
		}
	}

	m_vecPlayerMountPositionTop -= GetAbsOrigin();
	m_vecPlayerMountPositionBottom -= GetAbsOrigin();

	// Compute mins, maxs of points
	// 
	Vector mins( MAX_COORD_INTEGER, MAX_COORD_INTEGER, MAX_COORD_INTEGER );
	Vector maxs( -MAX_COORD_INTEGER, -MAX_COORD_INTEGER, -MAX_COORD_INTEGER );
	int i;
	for ( i = 0; i < 3; i++ )
	{
		if ( m_vecPlayerMountPositionBottom.m_Value[ i ] < mins[ i ] )
		{
			mins[ i ] = m_vecPlayerMountPositionBottom.m_Value[ i ];
		}
		if ( m_vecPlayerMountPositionBottom.m_Value[ i ] > maxs[ i ] )
		{
			maxs[ i ] = m_vecPlayerMountPositionBottom.m_Value[ i ];
		}
		if ( m_vecPlayerMountPositionTop.m_Value[ i ] < mins[ i ] )
		{
			mins[ i ] = m_vecPlayerMountPositionTop.m_Value[ i ];
		}
		if ( m_vecPlayerMountPositionTop.m_Value[ i ] > maxs[ i ] )
		{
			maxs[ i ] = m_vecPlayerMountPositionTop.m_Value[ i ];
		}
	}

	// Expand mins/maxs by player hull size
	mins += playerMins;
	maxs += playerMaxs;

	UTIL_SetSize( this, mins, maxs );

	m_bFakeLadder = HasSpawnFlags(SF_LADDER_DONTGETON);
#endif
}
Ejemplo n.º 21
0
int main(int argc, char **argv) {
#ifndef QUESO_HAS_MPI
  return 77;
#else
  MPI_Init(&argc, &argv);

  QUESO::EnvOptionsValues options;
  options.m_numSubEnvironments = 2;
  options.m_subDisplayFileName = "outputData/test_SequenceOfVectorsMax";
  options.m_subDisplayAllowAll = 1;
  options.m_seed = 1.0;
  options.m_checkingLevel = 1;
  options.m_displayVerbosity = 55;

  QUESO::FullEnvironment env(MPI_COMM_WORLD, "", "", &options);

  // Create a vector space
  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> paramSpace(env, "", 1,
      NULL);

  QUESO::SequenceOfVectors<QUESO::GslVector, QUESO::GslMatrix> pretendChain(
      paramSpace, 3, "pretendChain");

  QUESO::GslVector v(paramSpace.zeroVector());
  v[0] = 0.0;

  // Create a scalar sequence on each processor
  std::string name = "name";
  QUESO::ScalarSequence<double> scalarSequence(env, 3, name);
  pretendChain.setPositionValues(0, v);
  pretendChain.setPositionValues(1, v);
  pretendChain.setPositionValues(2, v);

  if (env.inter0Rank() == 0) {
    scalarSequence[0] = 10.0;
    scalarSequence[1] = 11.0;
    scalarSequence[2] = 12.0;
  }
  else if (env.inter0Rank() == 1) {
    scalarSequence[0] = 0.0;
    scalarSequence[1] = 1.0;
    scalarSequence[2] = 2.0;
  }
  else {
    queso_error_msg("Test should not get here!");
  }

  // Create a sequence of vectors
  QUESO::SequenceOfVectors<QUESO::GslVector, QUESO::GslMatrix> maxs(paramSpace,
      0, "name2");

  pretendChain.unifiedPositionsOfMaximum(scalarSequence, maxs);

  // Should not fail
  QUESO::GslVector tmpVec(paramSpace.zeroVector());

  // The loop should only actually do anything on process zero
  for (unsigned int i = 0; i < maxs.subSequenceSize(); i++) {
    maxs.getPositionValues(0, tmpVec);
  }

  MPI_Finalize();

  return 0;
#endif
}
Ejemplo n.º 22
0
int main ( int argc, char **argv )
{
    int intervals=5;
    int octave=0;
    /*CvCapture *capture;
    capture = cvCreateFileCapture("/users/eleves-a/x2008/benoit.seguin/INF560/Projet/cuda.avi");
    if (!capture) {
     printf("Ouverture du flux vidéo impossible !\n");
     return 1;
    }
    IplImage *img = cvQueryFrame(capture);*/
    IplImage *img = cvLoadImage("image1.jpg");
    uint width=img->width;
    uint height=img->height;
    IplImage *imgGrayscale = cvCreateImage( cvSize( width, height ), IPL_DEPTH_8U, 1 );
    cvCvtColor( img, imgGrayscale, CV_RGB2GRAY );
    //initialisation de la memoire CUDA
    CUDAinit(imgGrayscale->width,imgGrayscale->height,intervals);

    //initialisation des variables
    char s[255];
    clock_t totaltime;
    IplImage *integral = cvCreateImage(cvSize(imgGrayscale->width,imgGrayscale->height),IPL_DEPTH_32S,1);
    IplImage *imgs[intervals];
    IplImage *imgsShow[intervals];
    for(int i=0; i<intervals; i++) {
        imgs[i]=cvCreateImage(cvSize(imgGrayscale->width,imgGrayscale->height),IPL_DEPTH_32S,1);
        imgsShow[i]=cvCreateImage(cvSize(imgGrayscale->width,imgGrayscale->height),IPL_DEPTH_32S,1);
    }
    //initialisation de la boucle
    makeIntegralImage(imgGrayscale,integral);
    CUDAcalculateGaussianDerivative(integral,octave,intervals);
    //boucle de traitement
    for(int frame=1; frame<=90; frame++) {
        totaltime=clock();
        sprintf(s,"image%i.jpg",frame);
        img = cvLoadImage(s);
        cvCvtColor( img, imgGrayscale, CV_RGB2GRAY );
        //integralImage
        clock_t timer=clock();
        makeIntegralImage(imgGrayscale,integral);
        std::cout << "integrale : " << 1000*(float)(clock()-timer)/(float)CLOCKS_PER_SEC <<"ms"<< std::endl;
        //  for(int i=1;i<img->height;i++){
        //  	for(int j=1;j<img->width;j++){
        //  		i=j;
        //  		//if(((int*)( imgs[0]->imageData + imgs[0]->widthStep * i)) [j] != ((int*)( imgs2[0]->imageData + imgs2[0]->widthStep * i)) [j])
        //  		std::cout << i << "," << j << " "<< (int)((uchar*)( (img->imageData) + (img->widthStep) * i)) [j]<< " "<< getPixel(img2,i,j)+getPixel(img2,i-1,j-1)-getPixel(img2,i-1,j)-getPixel(img2,i,j-1) << std::endl;
        //    }
        //  }

        //filtres gaussiens
        timer=clock();

        CUDAretrieveGaussianDerivative(imgs,intervals);
        CUDAcalculateGaussianDerivative(integral,octave,intervals);

        //calculateGaussianDerivative(integral,imgs,octave,intervals);
        std::cout << "calculateGaussianDerivative : " << 1000*(float)(clock()-timer)/(float)CLOCKS_PER_SEC <<"ms"<< std::endl;


        //recherche d'extremas
        timer=clock();
        std::list<std::vector<int> > maxs(findExtrema(imgs,intervals));
        std::cout << "findExtrema : " << 1000*(float)(clock()-timer)/(float)CLOCKS_PER_SEC <<"ms"<< std::endl;

        std::cout << "tmps total avt affichage : " << 1000*(float)(clock()-totaltime)/(float)CLOCKS_PER_SEC <<"ms"<< std::endl;

        //affichage
        //cvShowImage( "Integrale", img2 );

        std::list<vector<int> >::iterator tmp=maxs.begin();
        for (int i = 0; i < intervals; ++i) {
            cvScale(imgs[i],imgsShow[i],100);
            while(tmp!=maxs.end() && (*tmp)[0]==i) {
                cvCircle(imgsShow[i], cvPoint((*tmp)[2],(*tmp)[1]), borderSize(octave,i), cvScalar(0,255,0), 1);
                cvCircle(img, cvPoint((*tmp)[2],(*tmp)[1]), borderSize(octave,i), cvScalar(0,255,0), 2);
                tmp++;
            }
            sprintf(s,"%i",i);
            cvShowImage( s, imgsShow[i] );
        }
        cvShowImage( "Image originale", img );
        cvWaitKey();
    }
    //FIN
    cvWaitKey();
    cvReleaseImage(&imgGrayscale);
    cvReleaseImage(&integral);
    //cvReleaseCapture(&capture);
    CUDAclose(intervals);
    return 0;
}
Ejemplo n.º 23
0
//--------------------------------------------------------------------------------------------------------------
void CNavNode::CheckCrouch( void )
{
	CTraceFilterWalkableEntities filter( NULL, COLLISION_GROUP_PLAYER_MOVEMENT, WALK_THRU_EVERYTHING );
	trace_t tr;

	// Trace downward from duck height to find the max floor height for the node's surroundings
	Vector mins( -HalfHumanWidth, -HalfHumanWidth, 0 );
	Vector maxs( HalfHumanWidth, HalfHumanWidth, 0 );
	Vector start( m_pos.x, m_pos.y, m_pos.z + VEC_DUCK_HULL_MAX.z - 0.1f );
	UTIL_TraceHull(
		start,
		m_pos,
		mins,
		maxs,
		MASK_PLAYERSOLID_BRUSHONLY,
		&filter,
		&tr );

	Vector groundPos = tr.endpos;

	if ( tr.startsolid && !tr.allsolid )
	{
		// Try going down out of the solid and re-check for the floor height
		start.z -= tr.endpos.z - 0.1f;

		UTIL_TraceHull(
			start,
			m_pos,
			mins,
			maxs,
			MASK_PLAYERSOLID_BRUSHONLY,
			&filter,
			&tr );

		groundPos = tr.endpos;
	}

	if ( tr.startsolid )
	{
		// we don't even have duck height clear.  try a simple check to find floor height.
		float x, y;

		// Find the highest floor z - for a player to stand in this area, we need a full
		// VEC_HULL_MAX.z of clearance above this height at all points.
		float maxFloorZ = m_pos.z;
		for( y = -HalfHumanWidth; y <= HalfHumanWidth + 0.1f; y += HalfHumanWidth )
		{
			for( x = -HalfHumanWidth; x <= HalfHumanWidth + 0.1f; x += HalfHumanWidth )
			{
				float floorZ;
				if ( TheNavMesh->GetGroundHeight( m_pos, &floorZ ) )
				{
					maxFloorZ = MAX( maxFloorZ, floorZ + 0.1f );
				}
			}
		}

		groundPos.Init( m_pos.x, m_pos.y, maxFloorZ );
	}

	// For each direction, trace upwards from our best ground height to VEC_HULL_MAX.z to see if we have standing room.
	for ( int i=0; i<NUM_CORNERS; ++i )
	{
#if DEBUG_NAV_NODES
		if ( nav_test_node_crouch_dir.GetInt() != NUM_CORNERS && i != nav_test_node_crouch_dir.GetInt() )
			continue;
#endif // DEBUG_NAV_NODES

		NavCornerType corner = (NavCornerType)i;
		Vector2D cornerVec;
		CornerToVector2D( corner, &cornerVec );

		Vector actualGroundPos = groundPos; // we might need to adjust this if the tracehull failed above and we fell back to m_pos.z

		// Build a mins/maxs pair for the HumanWidth x HalfHumanWidth box facing the appropriate direction
		mins.Init();
		maxs.Init( cornerVec.x * HalfHumanWidth, cornerVec.y * HalfHumanWidth, 0 );

		// now make sure that mins is smaller than maxs
		for ( int j=0; j<3; ++j )
		{
			if ( mins[j] > maxs[j] )
			{
				float tmp = mins[j];
				mins[j] = maxs[j];
				maxs[j] = tmp;
			}
		}

		UTIL_TraceHull(
			actualGroundPos + Vector( 0, 0, 0.1f ),
			actualGroundPos + Vector( 0, 0, VEC_HULL_MAX.z - 0.2f ),
			mins,
			maxs,
			MASK_PLAYERSOLID_BRUSHONLY,
			&filter,
			&tr );
		actualGroundPos.z += tr.fractionleftsolid * VEC_HULL_MAX.z;
		float maxHeight = actualGroundPos.z + VEC_DUCK_HULL_MAX.z;
		for ( ; tr.startsolid && actualGroundPos.z <= maxHeight; actualGroundPos.z += 1.0f )
		{
			// In case we didn't find a good ground pos above, we could start in the ground.  Move us up some.
			UTIL_TraceHull(
				actualGroundPos + Vector( 0, 0, 0.1f ),
				actualGroundPos + Vector( 0, 0, VEC_HULL_MAX.z - 0.2f ),
				mins,
				maxs,
				MASK_PLAYERSOLID_BRUSHONLY,
				&filter,
				&tr );
		}
		if (tr.startsolid || tr.fraction != 1.0f)
		{
			SetAttributes( NAV_MESH_CROUCH );
			m_crouch[corner] = true;
		}

#if DEBUG_NAV_NODES
		if ( nav_show_nodes.GetBool() )
		{
			if ( nav_test_node_crouch_dir.GetInt() == i || nav_test_node_crouch_dir.GetInt() == NUM_CORNERS  )
			{
				if ( tr.startsolid )
				{
					NDebugOverlay::Box( actualGroundPos, mins, maxs+Vector( 0, 0, VEC_HULL_MAX.z), 255, 0, 0, 10, 20.0f );
				}
				else if ( m_crouch[corner] )
				{
					NDebugOverlay::Box( actualGroundPos, mins, maxs+Vector( 0, 0, VEC_HULL_MAX.z), 0, 0, 255, 10, 20.0f );
				}
				else
				{
					NDebugOverlay::Box( actualGroundPos, mins, maxs+Vector( 0, 0, VEC_HULL_MAX.z), 0, 255, 0, 10, 10.0f );
				}
			}
		}
#endif // DEBUG_NAV_NODES
	}
}
Ejemplo n.º 24
0
Q3BSPLeaf *Q3BSPRep::createLeaf( int n ){
	q3_leaf *q3leaf=(q3_leaf*)header.dir[4].lump+n;

	Q3BSPLeaf *leaf=d_new Q3BSPLeaf;

	leaf->cluster=q3leaf->cluster;

	Vector mins( q3leaf->mins[0],q3leaf->mins[1],q3leaf->mins[2] );
	Vector maxs( q3leaf->maxs[0],q3leaf->maxs[1],q3leaf->maxs[2] );
	leaf->box=Box( tf(mins) );
	leaf->box.update( tf(maxs) );
	int *leaffaces=(int*)header.dir[5].lump+q3leaf->leafface;

	for( int k=0;k<q3leaf->n_leaffaces;++k ){

		int face_n=leaffaces[k];

		map<int,Q3BSPFace*>::const_iterator it=q3face_map.find(face_n);
		if( it!=q3face_map.end() ){
			if( it->second ) leaf->faces.push_back( it->second );
			continue;
		}

		q3_face *q3face=(q3_face*)header.dir[13].lump+leaffaces[k];

		if( q3face->type==1 || q3face->type==3 ){
			if( !q3face->n_meshverts || (q3face->n_meshverts%3) ) continue;
		}else if( q3face->type!=2 ) continue;

		bool draw=true,solid=true;

		if( q3face->texture>=0 ){
			q3_tex *q3tex=(q3_tex*)header.dir[1].lump+q3face->texture;
			if( !(q3tex->contents & 1) ) continue;
			if( q3tex->flags & 0x84 ) draw=false;
		}

		if( !draw && !solid ) continue;

		Q3BSPFace *face=0;
		if( draw ){
			Surf *surf=findSurf( q3face );
			face=d_new Q3BSPFace;
			face->t_surf=surf;
			face->vert=surf->verts.size();
			face->tri=surf->tris.size();
			face->n_verts=face->n_tris=0;
			leaf->faces.push_back( face );
			faces.push_back( face );
			q3face_map.insert( make_pair( face_n,face ) );
		}

		if( q3face->type==2 ){
			patchFace( face,q3face,draw,solid,1 );
		}else{
			meshFace( face,q3face,draw,solid );
		}
	}

	return leaf;
}
Ejemplo n.º 25
0
//-----------------------------------------------------------------------------
// Purpose: 
// Input  : pszBuf - 
//-----------------------------------------------------------------------------
void Box3D::GetStatusString(char *pszBuf)
{
	*pszBuf = '\0';



	Vector mins(0,0,0);
	Vector maxs(0,0,0);

	if ( IsValidBox() )
	{
		mins = bmins;
		maxs = bmaxs;
	}

	if ( IsTranslating() )
	{
		TranslateBox( mins, maxs );
	}

	Vector size = maxs - mins;
	Vector center = ( maxs + mins ) * 0.5f;

	if ( !IsTranslating() || m_TranslateMode == modeScale || m_TranslateMode == modeMove )
	{
		if (!IsEmpty())
		{
			if ( IsTranslating() && m_TranslateMode == modeMove )
			{
				center = m_vTranslationFixPoint;
				TranslatePoint( center );
			}

			switch (m_eWorldUnits)
			{
				case Units_None:
				{
					sprintf(pszBuf, " %dw %dl %dh @(%.0f %.0f %.0f)", 
						(int)fabs(size.x), (int)fabs(size.y), (int)fabs(size.z),
						center.x,center.y,center.z );
					break;
				}

				case Units_Inches:
				{
					sprintf(pszBuf, " %d\"w %d\"l %d\"h", (int)fabs(size.x), (int)fabs(size.y), (int)fabs(size.z));
					break;
				}

				case Units_Feet_Inches:
				{
					int nFeetWide = (int)fabs(size.x) / 12;
					int nInchesWide = (int)fabs(size.x) % 12;

					int nFeetLong = (int)fabs(size.y) / 12;
					int nInchesLong = (int)fabs(size.y) % 12;

					int nFeetHigh = (int)fabs(size.z) / 12;
					int nInchesHigh = (int)fabs(size.z) % 12;

					sprintf(pszBuf, " %d' %d\"w %d' %d\"l %d' %d\"h", nFeetWide, nInchesWide, nFeetLong, nInchesLong, nFeetHigh, nInchesHigh);
					break;
				}
			}
		}
	}
	else if ( m_TranslateMode == modeShear )
	{
		sprintf(pszBuf, " shear: %d %d %d ", (int)m_vTranslation.x, (int)m_vTranslation.y, (int)m_vTranslation.z );
	}
	else if ( m_TranslateMode == modeRotate )
	{
		int rotAxis = GetTransformationAxis();

		if ( rotAxis != -1  )
		{
			sprintf(pszBuf, " %.2f%c", m_vTranslation[abs(rotAxis+2)%3], 0xF8);
		}
		else
		{
			sprintf(pszBuf, " %.2f %.2f %.2f%c", m_vTranslation.x, m_vTranslation.y, m_vTranslation.z, 0xF8);
		}
	}
	else
	{
		Assert( 0 );
	}
	
}
Ejemplo n.º 26
0
void MVTemplatesView2PanelPrivate::setup_electrode_boxes(double W, double H)
{
    m_electrode_boxes.clear();

    int top_section_height = q->font().pixelSize();

    double W1 = W;
    double H1 = H - top_section_height - m_bottom_section_height;

    QList<QVector<double> > coords = m_electrode_geometry.coordinates;
    if (coords.isEmpty()) {
        int M = m_template.N1();
        int num_rows = qMax(1, (int)sqrt(M));
        int num_cols = ceil(M * 1.0 / num_rows);
        for (int m = 0; m < M; m++) {
            QVector<double> tmp;
            tmp << (m % num_cols) + 0.5 * ((m / num_cols) % 2) << m / num_cols;
            coords << tmp;
        }
    }
    if (coords.isEmpty())
        return;

    int D = coords[0].count();
    QVector<double> mins(D), maxs(D);
    for (int d = 0; d < D; d++) {
        mins[d] = maxs[d] = coords.value(0).value(d);
    }
    for (int m = 0; m < coords.count(); m++) {
        for (int d = 0; d < D; d++) {
            mins[d] = qMin(mins[d], coords[m][d]);
            maxs[d] = qMax(maxs[d], coords[m][d]);
        }
    }

    double spacing = estimate_spacing(coords);
    spacing = spacing * 0.75;

    //double W0 = maxs.value(0) - mins.value(0);
    //double H0 = maxs.value(1) - mins.value(1);
    double W0 = maxs.value(1) - mins.value(1);
    double H0 = maxs.value(0) - mins.value(0);

    double W0_padded = W0 + spacing * 4 / 3;
    double H0_padded = H0 + spacing * 4 / 3;

    double hscale_factor = 1;
    double vscale_factor = 1;

    if (W0_padded * H1 > W1 * H0_padded) {
        //limited by width
        if (W0_padded) {
            hscale_factor = W1 / W0_padded;
            vscale_factor = W1 / W0_padded;
        }
    }
    else {
        if (H0_padded)
            vscale_factor = H1 / H0_padded;
        if (W0_padded)
            hscale_factor = W1 / W0_padded;
    }

    double offset_x = (W1 - W0 * hscale_factor) / 2;
    double offset_y = top_section_height + (H1 - H0 * vscale_factor) / 2;
    for (int m = 0; m < coords.count(); m++) {
        QVector<double> c = coords[m];
        //double x0 = offset_x + (c.value(0) - mins.value(0)) * hscale_factor;
        //double y0 = offset_y + (c.value(1) - mins.value(1)) * vscale_factor;
        double x0 = offset_x + (c.value(1) - mins.value(1)) * hscale_factor;
        double y0 = offset_y + (c.value(0) - mins.value(0)) * vscale_factor;
        double radx = spacing * hscale_factor / 2;
        double rady = spacing * vscale_factor / 3.5;
        m_electrode_boxes << QRectF(x0 - radx, y0 - rady, radx * 2, rady * 2);
    }
}
Ejemplo n.º 27
0
SOrientedBoundingBox *
SOrientedBoundingBox::buildOBB(std::vector<SPoint3> &vertices)
{
#if defined(HAVE_MESH)

  int num_vertices = vertices.size();
  // First organize the data

  std::set<SPoint3> unique;
  unique.insert(vertices.begin(), vertices.end());

  num_vertices = unique.size();
  fullMatrix<double> data(3, num_vertices);

  fullVector<double> mean(3);
  fullVector<double> vmins(3);
  fullVector<double> vmaxs(3);

  mean.setAll(0);
  vmins.setAll(DBL_MAX);
  vmaxs.setAll(-DBL_MAX);

  size_t idx = 0;
  for(std::set<SPoint3>::iterator uIter = unique.begin(); uIter != unique.end();
      ++uIter) {
    const SPoint3 &pp = *uIter;
    for(int d = 0; d < 3; d++) {
      data(d, idx) = pp[d];
      vmins(d) = std::min(vmins(d), pp[d]);
      vmaxs(d) = std::max(vmaxs(d), pp[d]);
      mean(d) += pp[d];
    }
    idx++;
  }

  for(int i = 0; i < 3; i++) { mean(i) /= num_vertices; }

  // Get the deviation from the mean
  fullMatrix<double> B(3, num_vertices);
  for(int i = 0; i < 3; i++) {
    for(int j = 0; j < num_vertices; j++) { B(i, j) = data(i, j) - mean(i); }
  }

  // Compute the covariance matrix
  fullMatrix<double> covariance(3, 3);
  B.mult(B.transpose(), covariance);
  covariance.scale(1. / (num_vertices - 1));
  /*
  Msg::Debug("Covariance matrix");
  Msg::Debug("%f %f %f", covariance(0,0),covariance(0,1),covariance(0,2) );
  Msg::Debug("%f %f %f", covariance(1,0),covariance(1,1),covariance(1,2) );
  Msg::Debug("%f %f %f", covariance(2,0),covariance(2,1),covariance(2,2) );
  */
  for(int i = 0; i < 3; i++) {
    for(int j = 0; j < 3; j++) {
      if(std::abs(covariance(i, j)) < 10e-16) covariance(i, j) = 0;
    }
  }

  fullMatrix<double> left_eigv(3, 3);
  fullMatrix<double> right_eigv(3, 3);
  fullVector<double> real_eig(3);
  fullVector<double> img_eig(3);
  covariance.eig(real_eig, img_eig, left_eigv, right_eigv, true);

  // Now, project the data in the new basis.
  fullMatrix<double> projected(3, num_vertices);
  left_eigv.transpose().mult(data, projected);
  // Get the size of the box in the new direction
  fullVector<double> mins(3);
  fullVector<double> maxs(3);
  for(int i = 0; i < 3; i++) {
    mins(i) = DBL_MAX;
    maxs(i) = -DBL_MAX;
    for(int j = 0; j < num_vertices; j++) {
      maxs(i) = std::max(maxs(i), projected(i, j));
      mins(i) = std::min(mins(i), projected(i, j));
    }
  }

  // double means[3];
  double sizes[3];

  // Note:  the size is computed in the box's coordinates!
  for(int i = 0; i < 3; i++) {
    sizes[i] = maxs(i) - mins(i);
    // means[i] = (maxs(i) - mins(i)) / 2.;
  }

  if(sizes[0] == 0 && sizes[1] == 0) {
    // Entity is a straight line...
    SVector3 center;
    SVector3 Axis1;
    SVector3 Axis2;
    SVector3 Axis3;

    Axis1[0] = left_eigv(0, 0);
    Axis1[1] = left_eigv(1, 0);
    Axis1[2] = left_eigv(2, 0);
    Axis2[0] = left_eigv(0, 1);
    Axis2[1] = left_eigv(1, 1);
    Axis2[2] = left_eigv(2, 1);
    Axis3[0] = left_eigv(0, 2);
    Axis3[1] = left_eigv(1, 2);
    Axis3[2] = left_eigv(2, 2);

    center[0] = (vmaxs(0) + vmins(0)) / 2.0;
    center[1] = (vmaxs(1) + vmins(1)) / 2.0;
    center[2] = (vmaxs(2) + vmins(2)) / 2.0;

    return new SOrientedBoundingBox(center, sizes[0], sizes[1], sizes[2], Axis1,
                                    Axis2, Axis3);
  }

  // We take the smallest component, then project the data on the plane defined
  // by the other twos

  int smallest_comp = 0;
  if(sizes[0] <= sizes[1] && sizes[0] <= sizes[2])
    smallest_comp = 0;
  else if(sizes[1] <= sizes[0] && sizes[1] <= sizes[2])
    smallest_comp = 1;
  else if(sizes[2] <= sizes[0] && sizes[2] <= sizes[1])
    smallest_comp = 2;

  // The projection has been done circa line 161.
  // We just ignore the coordinate corresponding to smallest_comp.
  std::vector<SPoint2 *> points;
  for(int i = 0; i < num_vertices; i++) {
    SPoint2 *p = new SPoint2(projected(smallest_comp == 0 ? 1 : 0, i),
                             projected(smallest_comp == 2 ? 1 : 2, i));
    bool keep = true;
    for(std::vector<SPoint2 *>::iterator point = points.begin();
        point != points.end(); point++) {
      if(std::abs((*p)[0] - (**point)[0]) < 10e-10 &&
         std::abs((*p)[1] - (**point)[1]) < 10e-10) {
        keep = false;
        break;
      }
    }
    if(keep) { points.push_back(p); }
    else {
      delete p;
    }
  }

  // Find the convex hull from a delaunay triangulation of the points
  DocRecord record(points.size());
  record.numPoints = points.size();
  srand((unsigned)time(0));
  for(std::size_t i = 0; i < points.size(); i++) {
    record.points[i].where.h =
      points[i]->x() + (10e-6) * sizes[smallest_comp == 0 ? 1 : 0] *
                         (-0.5 + ((double)rand()) / RAND_MAX);
    record.points[i].where.v =
      points[i]->y() + (10e-6) * sizes[smallest_comp == 2 ? 1 : 0] *
                         (-0.5 + ((double)rand()) / RAND_MAX);
    record.points[i].adjacent = NULL;
  }

  try {
    record.MakeMeshWithPoints();
  } catch(const char *err) {
    Msg::Error("%s", err);
  }

  std::vector<Segment> convex_hull;
  for(int i = 0; i < record.numTriangles; i++) {
    Segment segs[3];
    segs[0].from = record.triangles[i].a;
    segs[0].to = record.triangles[i].b;
    segs[1].from = record.triangles[i].b;
    segs[1].to = record.triangles[i].c;
    segs[2].from = record.triangles[i].c;
    segs[2].to = record.triangles[i].a;

    for(int j = 0; j < 3; j++) {
      bool okay = true;
      for(std::vector<Segment>::iterator seg = convex_hull.begin();
          seg != convex_hull.end(); seg++) {
        if(((*seg).from == segs[j].from && (*seg).from == segs[j].to)
           // FIXME:
           // || ((*seg).from == segs[j].to && (*seg).from == segs[j].from)
        ) {
          convex_hull.erase(seg);
          okay = false;
          break;
        }
      }
      if(okay) { convex_hull.push_back(segs[j]); }
    }
  }

  // Now, examinate all the directions given by the edges of the convex hull
  // to find the one that lets us build the least-area bounding rectangle for
  // then points.
  fullVector<double> axis(2);
  axis(0) = 1;
  axis(1) = 0;
  fullVector<double> axis2(2);
  axis2(0) = 0;
  axis2(1) = 1;
  SOrientedBoundingRectangle least_rectangle;
  least_rectangle.center[0] = 0.0;
  least_rectangle.center[1] = 0.0;
  least_rectangle.size[0] = -1.0;
  least_rectangle.size[1] = 1.0;

  fullVector<double> segment(2);
  fullMatrix<double> rotation(2, 2);

  for(std::vector<Segment>::iterator seg = convex_hull.begin();
      seg != convex_hull.end(); seg++) {
    // segment(0) = record.points[(*seg).from].where.h -
    // record.points[(*seg).to].where.h;  segment(1) =
    // record.points[(*seg).from].where.v - record.points[(*seg).to].where.v;
    segment(0) = points[(*seg).from]->x() - points[(*seg).to]->x();
    segment(1) = points[(*seg).from]->y() - points[(*seg).to]->y();
    segment.scale(1.0 / segment.norm());

    double cosine = axis(0) * segment(0) + segment(1) * axis(1);
    double sine = axis(1) * segment(0) - segment(1) * axis(0);
    // double sine = axis(0)*segment(1) - segment(0)*axis(1);

    rotation(0, 0) = cosine;
    rotation(0, 1) = sine;
    rotation(1, 0) = -sine;
    rotation(1, 1) = cosine;

    // TODO C++11 std::numeric_limits<double>
    double max_x = -DBL_MAX;
    double min_x = DBL_MAX;
    double max_y = -DBL_MAX;
    double min_y = DBL_MAX;

    for(int i = 0; i < record.numPoints; i++) {
      fullVector<double> pnt(2);
      // pnt(0) = record.points[i].where.h;
      // pnt(1) = record.points[i].where.v;
      pnt(0) = points[i]->x();
      pnt(1) = points[i]->y();

      fullVector<double> rot_pnt(2);
      rotation.mult(pnt, rot_pnt);

      if(rot_pnt(0) < min_x) min_x = rot_pnt(0);
      if(rot_pnt(0) > max_x) max_x = rot_pnt(0);
      if(rot_pnt(1) < min_y) min_y = rot_pnt(1);
      if(rot_pnt(1) > max_y) max_y = rot_pnt(1);
    }

    /**/
    fullVector<double> center_rot(2);
    fullVector<double> center_before_rot(2);
    center_before_rot(0) = (max_x + min_x) / 2.0;
    center_before_rot(1) = (max_y + min_y) / 2.0;
    fullMatrix<double> rotation_inv(2, 2);

    rotation_inv(0, 0) = cosine;
    rotation_inv(0, 1) = -sine;
    rotation_inv(1, 0) = sine;
    rotation_inv(1, 1) = cosine;

    rotation_inv.mult(center_before_rot, center_rot);

    fullVector<double> axis_rot1(2);
    fullVector<double> axis_rot2(2);

    rotation_inv.mult(axis, axis_rot1);
    rotation_inv.mult(axis2, axis_rot2);

    if((least_rectangle.area() == -1) ||
       (max_x - min_x) * (max_y - min_y) < least_rectangle.area()) {
      least_rectangle.size[0] = max_x - min_x;
      least_rectangle.size[1] = max_y - min_y;
      least_rectangle.center[0] = (max_x + min_x) / 2.0;
      least_rectangle.center[1] = (max_y + min_y) / 2.0;
      least_rectangle.center[0] = center_rot(0);
      least_rectangle.center[1] = center_rot(1);
      least_rectangle.axisX[0] = axis_rot1(0);
      least_rectangle.axisX[1] = axis_rot1(1);
      //      least_rectangle.axisX[0] = segment(0);
      //      least_rectangle.axisX[1] = segment(1);
      least_rectangle.axisY[0] = axis_rot2(0);
      least_rectangle.axisY[1] = axis_rot2(1);
    }
  }
  // TODO C++11 std::numeric_limits<double>::min() / max()
  double min_pca = DBL_MAX;
  double max_pca = -DBL_MAX;
  for(int i = 0; i < num_vertices; i++) {
    min_pca = std::min(min_pca, projected(smallest_comp, i));
    max_pca = std::max(max_pca, projected(smallest_comp, i));
  }
  double center_pca = (max_pca + min_pca) / 2.0;
  double size_pca = (max_pca - min_pca);

  double raw_data[3][5];
  raw_data[0][0] = size_pca;
  raw_data[1][0] = least_rectangle.size[0];
  raw_data[2][0] = least_rectangle.size[1];

  raw_data[0][1] = center_pca;
  raw_data[1][1] = least_rectangle.center[0];
  raw_data[2][1] = least_rectangle.center[1];

  for(int i = 0; i < 3; i++) {
    raw_data[0][2 + i] = left_eigv(i, smallest_comp);
    raw_data[1][2 + i] =
      least_rectangle.axisX[0] * left_eigv(i, smallest_comp == 0 ? 1 : 0) +
      least_rectangle.axisX[1] * left_eigv(i, smallest_comp == 2 ? 1 : 2);
    raw_data[2][2 + i] =
      least_rectangle.axisY[0] * left_eigv(i, smallest_comp == 0 ? 1 : 0) +
      least_rectangle.axisY[1] * left_eigv(i, smallest_comp == 2 ? 1 : 2);
  }
  // Msg::Info("Test 1 : %f
  // %f",least_rectangle.center[0],least_rectangle.center[1]);
  // Msg::Info("Test 2 : %f
  // %f",least_rectangle.axisY[0],least_rectangle.axisY[1]);

  int tri[3];

  if(size_pca > least_rectangle.size[0]) {
    // P > R0
    if(size_pca > least_rectangle.size[1]) {
      // P > R1
      tri[0] = 0;
      if(least_rectangle.size[0] > least_rectangle.size[1]) {
        // R0 > R1
        tri[1] = 1;
        tri[2] = 2;
      }
      else {
        // R1 > R0
        tri[1] = 2;
        tri[2] = 1;
      }
    }
    else {
      // P < R1
      tri[0] = 2;
      tri[1] = 0;
      tri[2] = 1;
    }
  }
  else { // P < R0
    if(size_pca < least_rectangle.size[1]) {
      // P < R1
      tri[2] = 0;
      if(least_rectangle.size[0] > least_rectangle.size[1]) {
        tri[0] = 1;
        tri[1] = 2;
      }
      else {
        tri[0] = 2;
        tri[1] = 1;
      }
    }
    else {
      tri[0] = 1;
      tri[1] = 0;
      tri[2] = 2;
    }
  }

  SVector3 size;
  SVector3 center;
  SVector3 Axis1;
  SVector3 Axis2;
  SVector3 Axis3;

  for(int i = 0; i < 3; i++) {
    size[i] = raw_data[tri[i]][0];
    center[i] = raw_data[tri[i]][1];
    Axis1[i] = raw_data[tri[0]][2 + i];
    Axis2[i] = raw_data[tri[1]][2 + i];
    Axis3[i] = raw_data[tri[2]][2 + i];
  }

  SVector3 aux1;
  SVector3 aux2;
  SVector3 aux3;
  for(int i = 0; i < 3; i++) {
    aux1(i) = left_eigv(i, smallest_comp);
    aux2(i) = left_eigv(i, smallest_comp == 0 ? 1 : 0);
    aux3(i) = left_eigv(i, smallest_comp == 2 ? 1 : 2);
  }
  center = aux1 * center_pca + aux2 * least_rectangle.center[0] +
           aux3 * least_rectangle.center[1];
  // center[1] = -center[1];

  /*
  Msg::Info("Box center : %f %f %f",center[0],center[1],center[2]);
  Msg::Info("Box size : %f %f %f",size[0],size[1],size[2]);
  Msg::Info("Box axis 1 : %f %f %f",Axis1[0],Axis1[1],Axis1[2]);
  Msg::Info("Box axis 2 : %f %f %f",Axis2[0],Axis2[1],Axis2[2]);
  Msg::Info("Box axis 3 : %f %f %f",Axis3[0],Axis3[1],Axis3[2]);

  Msg::Info("Volume : %f", size[0]*size[1]*size[2]);
  */

  return new SOrientedBoundingBox(center, size[0], size[1], size[2], Axis1,
                                  Axis2, Axis3);
#else
  Msg::Error("SOrientedBoundingBox requires mesh module");
  return 0;
#endif
}
Ejemplo n.º 28
0
void Brush_ConstructPrism(Brush& brush, const AABB& bounds, std::size_t sides, int axis, const std::string& shader, const TextureProjection& projection)
{
  if(sides < c_brushPrism_minSides)
  {
    globalErrorStream() << c_brushPrism_name << ": sides " << sides << ": too few sides, minimum is " << c_brushPrism_minSides << "\n";
    return;
  }
  if(sides > c_brushPrism_maxSides)
  {
    globalErrorStream() << c_brushPrism_name << ": sides " << sides << ": too many sides, maximum is " << c_brushPrism_maxSides << "\n";
    return;
  }

  brush.clear();
  brush.reserve(sides+2);

  Vector3 mins(bounds.origin - bounds.extents);
  Vector3 maxs(bounds.origin + bounds.extents);

  float radius = max_extent_2d(bounds.extents, axis);
  const Vector3& mid = bounds.origin;
  Vector3 planepts[3];

  planepts[2][(axis+1)%3] = mins[(axis+1)%3];
  planepts[2][(axis+2)%3] = mins[(axis+2)%3];
  planepts[2][axis] = maxs[axis];
  planepts[1][(axis+1)%3] = maxs[(axis+1)%3];
  planepts[1][(axis+2)%3] = mins[(axis+2)%3];
  planepts[1][axis] = maxs[axis];
  planepts[0][(axis+1)%3] = maxs[(axis+1)%3];
  planepts[0][(axis+2)%3] = maxs[(axis+2)%3];
  planepts[0][axis] = maxs[axis];

  brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection);

  planepts[0][(axis+1)%3] = mins[(axis+1)%3];
  planepts[0][(axis+2)%3] = mins[(axis+2)%3];
  planepts[0][axis] = mins[axis];
  planepts[1][(axis+1)%3] = maxs[(axis+1)%3];
  planepts[1][(axis+2)%3] = mins[(axis+2)%3];
  planepts[1][axis] = mins[axis];
  planepts[2][(axis+1)%3] = maxs[(axis+1)%3];
  planepts[2][(axis+2)%3] = maxs[(axis+2)%3];
  planepts[2][axis] = mins[axis];

  brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection);
 
  for (std::size_t i=0 ; i<sides ; ++i)
  {
    double sv = sin (i*3.14159265*2/sides);
    double cv = cos (i*3.14159265*2/sides);

    planepts[0][(axis+1)%3] = static_cast<float>(floor(mid[(axis+1)%3]+radius*cv+0.5));
    planepts[0][(axis+2)%3] = static_cast<float>(floor(mid[(axis+2)%3]+radius*sv+0.5));
    planepts[0][axis] = mins[axis];

    planepts[1][(axis+1)%3] = planepts[0][(axis+1)%3];
    planepts[1][(axis+2)%3] = planepts[0][(axis+2)%3];
    planepts[1][axis] = maxs[axis];

    planepts[2][(axis+1)%3] = static_cast<float>(floor(planepts[0][(axis+1)%3] - radius*sv + 0.5));
    planepts[2][(axis+2)%3] = static_cast<float>(floor(planepts[0][(axis+2)%3] + radius*cv + 0.5));
    planepts[2][axis] = maxs[axis];

    brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection);
  }
}
Ejemplo n.º 29
0
static int FindGoalAASArea(edict_t *ent)
{
    AiAasWorld *aasWorld = AiAasWorld::Instance();
    if (!aasWorld->IsLoaded())
        return 0;

    Vec3 mins(ent->r.mins), maxs(ent->r.maxs);
    // Extend AABB XY dimensions
    ExtendDimension(mins.Data(), maxs.Data(), 0);
    ExtendDimension(mins.Data(), maxs.Data(), 1);
    // Z needs special extension rules
    float presentHeight = maxs.Z() - mins.Z();
    float playerHeight = playerbox_stand_maxs[2] - playerbox_stand_mins[2];
    if (playerHeight > presentHeight)
        maxs.Z() += playerHeight - presentHeight;


    // Find all areas in bounds
    int areas[16];
    // Convert bounds to absolute ones
    mins += ent->s.origin;
    maxs += ent->s.origin;
    const int numAreas = aasWorld->BBoxAreas(mins, maxs, areas, 16);

    // Find hub areas (or use cached)
    FindHubAreas();

    int bestArea = 0;
    int bestAreaReachCount = 0;
    AiAasRouteCache *routeCache = AiAasRouteCache::Shared();
    for (int i = 0; i < numAreas; ++i)
    {
        const int areaNum = areas[i];
        int areaReachCount = 0;
        for (const int hubAreaNum: hubAreas)
        {
            const aas_area_t &hubArea = aasWorld->Areas()[hubAreaNum];
            Vec3 hubAreaPoint(hubArea.center);
            hubAreaPoint.Z() = hubArea.mins[2] + std::min(24.0f, hubArea.maxs[2] - hubArea.mins[2]);
            // Do not waste pathfinder cycles testing for preferred flags that may fail.
            constexpr int travelFlags = Bot::ALLOWED_TRAVEL_FLAGS;
            if (routeCache->ReachabilityToGoalArea(hubAreaNum, hubAreaPoint.Data(), areaNum, travelFlags))
            {
                areaReachCount++;
                // Thats't enough, do not waste CPU cycles
                if (areaReachCount == 4)
                    return areaNum;
            }
        }
        if (areaReachCount > bestAreaReachCount)
        {
            bestArea = areaNum;
            bestAreaReachCount = areaReachCount;
        }
    }
    if (bestArea)
        return bestArea;

    // Fall back to a default method and hope it succeeds
    return aasWorld->FindAreaNum(ent);
}
Ejemplo n.º 30
0
int CreditCardProcessor::updateCCPay(int &pccpayid, ParameterList &pparams)
{
  if (DEBUG)
    qDebug("updateCCPay(%d, %d params)", pccpayid, pparams.size());

  QString sql;
  XSqlQuery ccq;

  bool valid;
  QVariant param;
  QString r_error;
  param = pparams.value("r_error", &valid);
  if (valid)
    r_error = param.toString();

  if (pccpayid > 0)
  {
    sql =  "UPDATE ccpay SET"
	   "<? if exists(\"fromcurr\") ?>"
	   "      ccpay_amount=ROUND(currToCurr(<? value(\"fromcurr\") ?>,"
	   "                                    <? value(\"tocurr\") ?>,"
	   "                                    <? value(\"amount\") ?>,"
	   "                                    CURRENT_DATE), 2),"
	   "       ccpay_curr_id=<? value(\"currid\") ?>,"
	   "<? else ?>"
	   "       ccpay_amount=ROUND(<? value(\"amount\") ?>, 2),"
	   "       ccpay_curr_id=<? value(\"currid\") ?>,"
	   "<? endif ?>"
	   "       ccpay_auth=<? value(\"auth\") ?>,"
	   "       ccpay_r_approved=<? value(\"approved\") ?>,"
	   "       ccpay_r_avs=<? value(\"avs\") ?>,"
	   "       ccpay_r_code=<? value(\"code\") ?>,"
	   "       ccpay_r_error=<? value(\"error\") ?>,"
	   "       ccpay_r_message=<? value(\"message\") ?>,"
	   "       ccpay_r_ordernum=<? value(\"ordernum\") ?>,"
	   "       ccpay_r_ref=<? value(\"ref\") ?>,"
	   "<? if exists(\"shipping\") ?>"
	   "       ccpay_r_shipping=<? value(\"shipping\") ?>,"
	   "<? endif ?>"
	   "<? if exists(\"score\") ?>"
	   "       ccpay_yp_r_score=<? value(\"score\") ?>,"
	   "<? endif ?>"
	   "<? if exists(\"tax\") ?>"
	   "       ccpay_r_tax=<? value(\"tax\") ?>,"
	   "<? endif ?>"
	   "<? if exists(\"tdate\") ?>"
	   "       ccpay_yp_r_tdate=<? value(\"tdate\") ?>,"
	   "<? endif ?>"
	   "<? if exists(\"time\") ?>"
	   "       ccpay_yp_r_time=<? value(\"time\")?>,"
	   "<? endif ?>"
	   "       ccpay_status=<? value(\"status\") ?>"
	   " WHERE (ccpay_id=<? value(\"ccpay_id\") ?>);" ;
  }
  else
  {
    ccq.exec("SELECT NEXTVAL('ccpay_ccpay_id_seq') AS ccpay_id;");
    if (ccq.first())
      pccpayid = ccq.value("ccpay_id").toInt();
    else if (ccq.lastError().type() != QSqlError::None && r_error.isEmpty())
    {
      _errorMsg = errorMsg(4).arg(ccq.lastError().databaseText());
      return 1;
    }
    else if (ccq.lastError().type() == QSqlError::None && r_error.isEmpty())
    {
      _errorMsg = errorMsg(4).arg(errorMsg(2));
      return 2;
    }
    else	// no rows found and YP reported an error
    {
      _errorMsg = errorMsg(-12).arg(r_error);
      return -12;
    }

    if (pparams.inList("ordernum") && pparams.value("ordernum").toInt() > 0)
    {
      QString maxs("SELECT MAX(COALESCE(ccpay_order_number_seq, -1)) + 1"
		   "       AS next_seq "
		   "  FROM ccpay "
		   " WHERE (ccpay_order_number=<? value(\"ordernum\") ?>);");
      MetaSQLQuery maxm(maxs);
      ccq = maxm.toQuery(pparams);
      if (ccq.first())
	pparams.append("next_seq", ccq.value("next_seq"));
      else
	pparams.append("next_seq", 0);
    }
    else
	pparams.append("next_seq", 0);

    sql =  "INSERT INTO ccpay ("
	   "    ccpay_id, ccpay_ccard_id, ccpay_cust_id,"
	   "    ccpay_type,"
	   "    ccpay_amount,"
	   "    ccpay_curr_id,"
	   "    ccpay_auth, ccpay_auth_charge,"
	   "    ccpay_order_number,"
	   "    ccpay_order_number_seq,"
	   "    ccpay_r_approved, ccpay_r_avs,"
	   "    ccpay_r_code,    ccpay_r_error,"
	   "    ccpay_r_message, ccpay_r_ordernum,"
	   "    ccpay_r_ref,"
	   "<? if exists(\"score\") ?>    ccpay_yp_r_score, <? endif ?>"
	   "<? if exists(\"shipping\") ?> ccpay_r_shipping, <? endif ?>"
	   "<? if exists(\"tax\") ?>      ccpay_r_tax,   <? endif ?>"
	   "<? if exists(\"tdate\") ?>    ccpay_yp_r_tdate, <? endif ?>"
	   "<? if exists(\"time\") ?>     ccpay_yp_r_time,  <? endif ?>"
	   "    ccpay_status"
	   ") SELECT <? value(\"ccpay_id\") ?>, ccard_id, cust_id,"
	   "    <? value(\"type\") ?>,"
	   "<? if exists(\"fromcurr\") ?>"
	   "    ROUND(currToCurr(<? value(\"fromcurr\") ?>,"
	   "                     <? value(\"tocurr\") ?>,"
	   "                     <? value(\"amount\") ?>,CURRENT_DATE), 2),"
	   "    <? value(\"tocurr\") ?>,"
	   "<? else ?>"
	   "    ROUND(<? value(\"amount\") ?>, 2),"
	   "    <? value(\"currid\") ?>,"
	   "<? endif ?>"
	   "    <? value(\"auth\") ?>,     <? value(\"auth_charge\") ?>,"
	   "    <? value(\"ordernum\") ?>,"
	   "    COALESCE(<? value(\"next_seq\") ?>, 1),"
	   "    <? value(\"approved\") ?>, <? value(\"avs\") ?>,"
	   "    <? value(\"code\") ?>,     <? value(\"error\") ?>,"
	   "    <? value(\"message\") ?>,  <? value(\"reforder\") ?>,"
	   "    <? value(\"ref\") ?>,"
	   "<? if exists(\"score\") ?>    <? value(\"score\") ?>,   <? endif ?>"
	   "<? if exists(\"shipping\") ?> <? value(\"shipping\") ?>,<? endif ?>"
	   "<? if exists(\"tax\") ?>      <? value(\"tax\") ?>,     <? endif ?>"
	   "<? if exists(\"tdate\") ?>    <? value(\"tdate\") ?>,   <? endif ?>"
	   "<? if exists(\"time\") ?>     <? value(\"time\") ?>,    <? endif ?>"
	   "    <? value(\"status\") ?>"
	   "  FROM ccard, custinfo"
	   "  WHERE ((ccard_cust_id=cust_id)"
	   "    AND  (ccard_id=<? value(\"ccard_id\") ?>));";
  }

  pparams.append("ccpay_id", pccpayid);

  MetaSQLQuery mql(sql);
  ccq = mql.toQuery(pparams);

  if (ccq.lastError().type() != QSqlError::None)
  {
    pccpayid = -1;
    _errorMsg = errorMsg(4).arg(ccq.lastError().databaseText());
    return 1;
  }

  return 0;
}