Beispiel #1
0
 vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {
     int m = nums1.size(), n = nums2.size();
     vector<int> res(k, 0);
     for (int i=max(0, k-n); i<=min(k, m); i++) {
         auto v1 = maxV(nums1, i);
         auto v2 = maxV(nums2, k-i);
         auto tmp = merge(v1, v2, k);
         if (compare(tmp, 0, res, 0)) res = tmp;
     }
     return res;
 }
Beispiel #2
0
void CameraManager::updateCurrent_(float dt) {
    glm::vec3 dx = target_ - current_;
    glm::vec3 maxV(getParam("camera.maxVx"),
                   getParam("camera.maxVy"),
                   getParam("camera.maxVz"));
    // If we're trying to move faster than we're allowed,
    // clip our velocity in that direction.
    if (fabs(dx.x) > maxV.x * dt) {
        dx.x = dx.x < 0 ? 
            -1 * maxV.x * dt : 
                 maxV.x * dt;
    }
    if (fabs(dx.y) > maxV.y * dt) {
        dx.y = dx.y < 0 ? 
            -1 * maxV.y * dt :
                 maxV.y * dt;
    }
    if (fabs(dx.z) > maxV.z * dt)
    {
        dx.z = dx.z < 0 ?
            -1 * maxV.z * dt :
                 maxV.z * dt;
    }

    current_ = current_ + dx;
    setCamera(current_);

}
 int maximumGap(vector<int> &num) {
     
     int n = num.size();
     
     if( n < 2 ) return 0;
     if( n == 2 ) return abs( num[0] - num[1] );
     
     int Min = *min_element( num.begin() , num.end() );
     int Max = *max_element( num.begin() , num.end() );
     
     double d = double( Max - Min ) / ( n - 1 );
     
     vector< int > maxV( n - 1 , -1 );
     vector< int > minV( n - 1 , -1 );
     
     for( int x : num ) {
         int hop = ( x == Max ? n-2 : double( x - Min ) / d );
         maxV[hop] = max( maxV[hop] , x );
         if( minV[hop] == -1 || minV[hop] > x ) minV[hop] = x;
     }
     
     n--;
     int i = 0, ret = 0;
     while( i < n && minV[i] == -1 ) i++;
     while( i < n ) {
         int j = i+1;
         while( j < n && minV[j] == -1 ) j++;
         if( j == n ) break;
         ret = max( ret , minV[j] - maxV[i] );
         i = j;
     }
     
     return ret;
 }
Beispiel #4
0
GlReplicateAddOn::GlReplicateAddOn()
		: inherited(SZI[SZI_arp], GL_REPLICATE_KEY, SZ(SZ_Combine), SZ(SZ_Replicate), 1, 0)
{
	GlRelAbs		minV(0, 0), maxV(1, 256);
	
//	mDepth =	AddParamType(new GlFloatParamType(_DEPTH_KEY, "Depth", 0, 1, 0.5, 0.01));
	AddParamType(new GlRelAbsParamType(_DEPTH_KEY, SZ(SZ_Depth), minV, maxV, gInit, 0.01f));
}
/* Aplica o modelo de iluminação para o cálculo da cor do vértice corrente.
 *
 *   Argumentos de entrada:
 *     'vertex_ec'         : Localização do vértice representada no sistema de coordenadas da câmera (eye coordinates, EC).
 *     'unit_normal_ec'    : Vetor normal à superfície representado no sistema de coordenadas da câmera (EC). Assume-se que
 *                           a norma deste vetor é igual a 1.0f.
 *     'base_color'        : Cor base para o vértice. Utilizada quando a iluminação está desabilitada.
 *     'lighting_enabled'  : Indica se a iluminação está habilitada.
 *     'material_ambient'  : Cor da componente ambiente do material.
 *     'material_diffuse'  : Cor da componente difusa do material.
 *     'material_specular' : Cor da componente especular do material.
 *     'material_shininess': Expoente que define o tamanho do brilho especular do material.
 *     'light_ec'          : Localização da fonte de luz no sistema de coordenadas da câmera (EC).
 *     'light_ambient'     : Intensidade da componente ambiente da fonte de luz.
 *     'light_diffuse'     : Intensidade da componente difusa da fonte de luz.
 *     'light_specular'    : Intensidade da componente especular da fonte de luz.
 *
 *   Argumentos de saída:
 *     'vertex_color'      : Cor do vértice corrente. É igual a 'base_color' caso a iluminação esteja desabilitada ou é
 *                           calculada por meio de modelo de reflexão de Blin-Phong, caso contrário.
 */
void vertex_lighting(const location_struct &vertex_ec, const direction_struct &unit_normal_ec, const color_struct &base_color, bool lighting_enabled, const color_struct &material_ambient, const color_struct &material_diffuse, const color_struct &material_specular, float material_shininess, const location_struct &light_ec, const color_struct &light_ambient, const color_struct &light_diffuse, const color_struct &light_specular, color_struct &vertex_color) {
    // Calcular 'vertex_color'.
	direction_struct S = direction_struct();
	direction_struct V = direction_struct();
	direction_struct H = direction_struct();

	if(lighting_enabled) {
		//Diffuse		
		S.x = light_ec.x - vertex_ec.x;
		S.y = light_ec.y - vertex_ec.y;
		S.z = light_ec.z - vertex_ec.z;

		normalize(S);
		float dotProductDiffuse = dotProduct (S, unit_normal_ec);

		color_struct lightDiffuse = color_struct();
		lightDiffuse.r = light_diffuse.r * material_diffuse.r * maxV(dotProductDiffuse, 0.0f);
		lightDiffuse.g = light_diffuse.g * material_diffuse.g * maxV(dotProductDiffuse, 0.0f);
		lightDiffuse.b = light_diffuse.b * material_diffuse.b * maxV(dotProductDiffuse, 0.0f);
		lightDiffuse.a = light_diffuse.a * material_diffuse.a * maxV(dotProductDiffuse, 0.0f);

		//Specular
		V.x = - vertex_ec.x;
		V.y = - vertex_ec.y;
		V.z = - vertex_ec.z;
		normalize(V);

		H.x = S.x + V.x;
		H.y =  S.y + V.y;
		H.z = S.z + V.z;
		normalize(H);
		float dotProductSpecular = dotProduct(H, unit_normal_ec);

		color_struct lightSpecular = color_struct();
		lightSpecular.r = light_specular.r * material_specular.r * pow(maxV(dotProductSpecular, 0.0f), material_shininess);
		lightSpecular.g = light_specular.g * material_specular.g * pow(maxV(dotProductSpecular, 0.0f), material_shininess);
		lightSpecular.b = light_specular.b * material_specular.b * pow(maxV(dotProductSpecular, 0.0f), material_shininess);
		lightSpecular.a = light_specular.a * material_specular.a * pow(maxV(dotProductSpecular, 0.0f), material_shininess);

		//Ambient
		color_struct lightAmbient = color_struct();
		lightAmbient.r = light_ambient.r * material_ambient.r;
		lightAmbient.g = light_ambient.g * material_ambient.g;
		lightAmbient.b = light_ambient.b * material_ambient.b;
		lightAmbient.a = light_ambient.a * material_ambient.a;

		//Result
		vertex_color = color_struct(lightDiffuse.r + lightSpecular.r + lightAmbient.r, 
			lightDiffuse.g + lightSpecular.g + lightAmbient.g, 
			lightDiffuse.b + lightSpecular.b + lightAmbient.b, 
			1.0f);
	} else {
		vertex_color = color_struct(base_color);
	}
}
Beispiel #6
0
int uniquePaths(int m, int n) {  
	 vector<int> maxV(n,0);  
	 maxV[0]=1;  
	 for(int i =0; i< m; i++)  
	 {  
		  for(int j =1; j<n; j++)  
		  {  
			   maxV[j] = maxV[j-1] + maxV[j];  
		  }  
	 }  
	 return maxV[n-1];  
}  
ProductVersion ProductVersions::FindMax(ProductVersion const &v, bool devel) const
{
	ProductVersion maxV(v);
	for(int i = 0; i < GetCount(); i++)
	{
		if(!devel && operator[](i).IsDevel())
			continue;
		if(operator[](i) > maxV)
			maxV = operator[](i);
	}
	return maxV;
}
Beispiel #8
0
void ITKImplicit::init(void)
{
	
	//init from surface
	//Via dynamic cast we test whether the surface type allows for a transformation
	//into an ITKImplicit
	if (!surface)
		return;
	
	//init default image, this can still be overwritten
	myImage = ImageType::New();
	
	SurfaceMesh * mesh=dynamic_cast<SurfaceMesh*>(surface);
	if (mesh)
	{
		mesh->computeBoundingBox();
		gmVector3 maxV(mesh->bbox_max[0], mesh->bbox_max[1], mesh->bbox_max[2]);
		gmVector3 minV(mesh->bbox_min[0], mesh->bbox_min[1], mesh->bbox_min[2]);
		initScalingAndOriginFromBoundingBox(minV,maxV);

		//we have a special surface, a mesh surface
		initFromSurfaceMesh(mesh);
	}
	//surface could be an implicit
	Implicit * imp=dynamic_cast<Implicit*>(surface);
	if (imp)
	{
		//if we have an implicit we want to check whether the particle bounding box is set.
		//if so, we adjust the image 
		if (bbox)
		{
			//we have a bounding box, so we use it to evaluate the
			//values.
			initScalingAndOriginFromBoundingBox(bbox->min, bbox->max);
		}
		else
		{
			initScalingAndOriginFromBoundingBox(gmVector3(-0.5,-0.5,-0.5),
												gmVector3(0.5,0.5,0.5));
		}
		initFromImplicit(imp);
	}

	originalSpacing = myImage->GetSpacing();
	originalOrigin = myImage->GetOrigin();

	//we apply eventual transformations 
	//and init the spline interpolator
	//we refit the particles bounding box
	applyParameterChanges();
}
    void PhysicsManager::addLevelGeometry( Ogre::Entity* levelEntity, const std::vector<OgreNewt::CollisionPtr> &collisions)
    {
        RlAssert1(levelEntity);
        RlAssert1(levelEntity->getParentSceneNode());

        SceneNode* node = levelEntity->getParentSceneNode();
        //Level entity has to be attached to a scene node.
        

        // try one compound collision for the entity if there are several collisions
        OgreNewt::CollisionPtr collision;
        switch( collisions.size() )
        {
            case 0:
                break;
            case 1:
                collision = collisions[0];
                break;
            default:
                collision = OgreNewt::CollisionPtr(new OgreNewt::CollisionPrimitives::CompoundCollision(mWorld, collisions, 0));
                break;
        }

        if( collision )
        {
            OgreNewt::Body* body = new OgreNewt::Body(mWorld, collision );


            body->attachNode(node);
            body->setPositionOrientation(node->_getDerivedPosition(),
                node->_getDerivedOrientation());
            body->setMaterialGroupID(getMaterialID("level"));

            mLevelBodiesQuadTree.add(body);
            //mLevelBodies.push_back(body);
        }

        // adjust worldAABB
        Vector3 minV(mWorldAABB.getMinimum());
        Vector3 maxV(mWorldAABB.getMaximum());

        AxisAlignedBox entityAABB = levelEntity->getWorldBoundingBox(true);
        minV.makeFloor(entityAABB.getMinimum());
        maxV.makeCeil(entityAABB.getMaximum());
        mWorldAABB.setMinimum(minV - Vector3(50, 50, 50));
        mWorldAABB.setMaximum(maxV + Vector3(50, 50, 50));

        mWorld->setWorldSize(mWorldAABB);
    }
 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
     int max = maxV(p, q), min = minV(p, q);
     if(root == NULL) return NULL;
     TreeNode* temp = root;
     while(temp != NULL) {
         if(temp->val == max || temp->val == min) return temp;
         if(temp->val > max) {
             temp = temp->left;
         }
         else if(temp->val < min) {
             temp = temp->right;
         }
         else return temp;
     }
 }
  bool brightRGB::getMax(const image& img,dvector& dest) const{

    // image empty?
    if (img.empty()) {
      setStatusString("image empty");
      dest.resize(0);
      return false;
    }

    const rgbPixel transColor = getParameters().transColor;
    ivector maxV(3,-1);
    image::const_iterator it = img.begin();
    if(getParameters().transparent) {
      while(it != img.end()) {
	if(*it != transColor) {
	  if((*it).getRed() > maxV.at(0))
	    maxV.at(0) = (*it).getRed();
	  if((*it).getGreen() > maxV.at(1))
	    maxV.at(1) = (*it).getGreen();
	  if((*it).getBlue() > maxV.at(2))
	    maxV.at(2) = (*it).getBlue();
	}
	it++;
      }
      // only transparent pixels?
      if (maxV.at(0)==-1) {
        setStatusString("only transparent pixels");
        dest.resize(0);
        return false;
      }
    } else { // no transparent color
      while(it != img.end()) {
	if((*it).getRed() > maxV.at(0))
	  maxV.at(0) = (*it).getRed();
	if((*it).getGreen() > maxV.at(1))
	  maxV.at(1) = (*it).getGreen();
	if((*it).getBlue() > maxV.at(2))
	  maxV.at(2) = (*it).getBlue();
	it++;
      }
    }
    if(maxV.at(0) == -1)
      return false;
    dest.castFrom(maxV);
    // normalize to 0..1
    dest.divide(255);
    return true;
  };
// CREATEPLHKPHYSICALFROMMESHEASY
// Convenience function for getting from a max node to a plHKPhysical and the requisite
// Havok objects.
// The node and the scene object don't have to correspond to the same Max object.
// If the sAltNode is supplied, the node will be moved into the coordinate system of the
bool plMaxMeshExtractor::Extract(plMaxMeshExtractor::NeutralMesh& mesh, plMaxNode* node, bool makeAABB, plMaxNode* sOwningNode)
{
    mesh.fNumVerts = mesh.fNumFaces = 0;
    mesh.fVerts = nil;
    mesh.fFaces = nil;

    // if an alternate node was supplied, get its scene object. otherwise don't...
    plMaxNode* masterNode = sOwningNode ? sOwningNode : node;

    mesh.fL2W = masterNode->GetLocalToWorld44();

    //
    // Create the arrays of verts and faces
    //
    bool isDummy = (node->EvalWorldState(0).obj->ClassID() == Class_ID(DUMMY_CLASS_ID,0));
    if (isDummy)
    {
        hsMatrix44 w2l = masterNode->GetWorldToLocal44();
        MakeDummyMesh(node, mesh);
        // Localize the verts
        //for (int i = 0; i < mesh.fNumVerts; i++)
        //  mesh.fVerts[i] = w2l * mesh.fVerts[i];
    }
    else
    {
        // only get the max world-to-local transform if the node is moveable or instanced. otherwise verts stay global.
        Matrix3 w2l = masterNode->GetWorldToLocal();
//      Matrix3 *localizer = nil;
//      if (masterNode->IsMovable() || masterNode->GetForceLocal() || masterNode->GetInstanced())
//          localizer = &w2l;

        if (!MakeNormalMesh(node, mesh, &w2l))
            return false;

        if (makeAABB)
        {
            hsPoint3 minV(FLT_MAX, FLT_MAX, FLT_MAX), maxV(-FLT_MAX, -FLT_MAX, -FLT_MAX);
            MeshMinMax(minV, maxV, mesh.fNumVerts, mesh.fVerts);
            MakeBoxMesh(node, mesh, minV, maxV);
        }
    }

    return true;
}
 int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {  
     int m = obstacleGrid.size();  
     if(m == 0)
         return 0;  
     int n = obstacleGrid[0].size();  
     if(n == 0 || obstacleGrid[0][0] == 1)
         return 0;  
     vector<int> maxV(n, 0);  
     maxV[0] =1;  
     for(int i = 0; i < m; i++){
         for(int j = 0; j < n; j++){  
             if(obstacleGrid[i][j] ==1)  
                 maxV[j] = 0;  
             else if(j >0)  
                 maxV[j] = maxV[j-1] + maxV[j];  //dp[i][j] = dp[i][j-1] + dp[i-1][j]
         }  
     }  
     return maxV[n-1];  
 } 
 int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
     // Note: The Solution object is instantiated only once and is reused by each test case.
     int m = obstacleGrid.size();
     if(m ==0) return 0;
     int n = obstacleGrid[0].size();
     if (obstacleGrid[0][0] == 1) return 0;
     vector<int> maxV(n,0);
     maxV[0] = 1;
     for (int i = 0; i < m; ++i)
     {
         for (int j = 0; j < n; ++j)
         {
             if (obstacleGrid[i][j]==1)
                 maxV[j] = 0;
             else if (j > 0)
                 maxV[j] = maxV[j-1] + maxV[j];
         }
     }
     return maxV[n-1];
 }
Beispiel #15
0
 /**
  * Print some informations concerning the object in a std::string and does a cleanup of the
  * memory.
  *
  * @return  A std::string.
 **/
 std::string stats()
 {
     std::string s;
     s += "*****************************************************\n";
     s += "BitGraphZ2 object statistics\n\n";
     s += "- memory used         : " + toString(memory()) + "Mb\n";
     s += "- lattice represented : [ " + toString(minV()) + " , " + toString(maxV()) + " ]^2\n";
     s += "- Main grid size      : [ " + toString(-LL) + " , " + toString(LL-1) + " ]^2 (" + toString((4*sizeof(int32)*LL*LL)/(1024*1024)) + "Mb)\n";
     s += "- Size of a subsquare : " + toString(N*8) + " x " + toString(N*8) + " (" + toString(sizeof(_MSQ)) + "b each)\n";
     s += "- Number of subsquare : " + toString(VV) + " (" + toString(((int64)VV)*sizeof(_MSQ) /(1024*1024)) + "Mb)\n\n";
     s += "Number of point set : " + toString(nbSet()) + "\n";
     s += "Surrounding square : ";
     if (minX() != LLONG_MAX) {
     s += "[ " + toString(minX()) + " , " + toString(maxX()) + " ] x [ " + toString(minY()) + " , " + toString(maxY()) + " ]\n";
     } else {s += "No point set yet !\n";}
     s += "Memory used before cleanup\t" + toString(v) + "/" + toString(VV) + " (" + toString((int)(100*(((double)v)/((double)VV))))+ "%)\n";
     cleanup();
     s += "Memory used after cleanup\t" + toString(v) + "/" + toString(VV) + " (" + toString((int)(100*(((double)v)/((double)VV))))+ "%)\n";
     s += "*****************************************************\n";
     return s;            
 }
BoundingBox3D Triangle3D::getBoundingBox()
{
	float minX, minY, minZ;
	float maxX, maxY, maxZ;

	minX = minY = minZ = 10000000.0;
	maxX = maxY = maxZ = -10000000.0;

	for (int i = 0; i<3; i++) {
		if (minX > this->v[i].x()) minX = this->v[i].x();
		if (minY > this->v[i].y()) minY = this->v[i].y();
		if (minZ > this->v[i].z()) minZ = this->v[i].z();

		if (maxX < this->v[i].x()) maxX = this->v[i].x();
		if (maxY < this->v[i].y()) maxY = this->v[i].y();
		if (maxZ < this->v[i].z()) maxZ = this->v[i].z();
	}

	EigenVector3 minV(minX, minY, minZ);
	EigenVector3 maxV(maxX, maxY, maxZ);
	return BoundingBox3D(minV, maxV);
}
Beispiel #17
0
	bool BoundingCircle::isInside2D(const BoundingObject2D& bounding_obj) const {

		switch (bounding_obj.getObjectType()) {
			case BOX:
				return (
					bounding_obj.minU() <= minU() && bounding_obj.maxU() >= maxU() &&
					bounding_obj.minV() <= minV() && bounding_obj.maxV() >= maxV()
					);

			case CIRCLE:
				return (
					(position.distance(bounding_obj.centroid())+
					((const BoundingCircle&)bounding_obj).getRadius()) <= radius
					);

			default:
				break;
		}

		return false;


	}
Beispiel #18
0
// ----------------------------------------------------------------------- //
//
//	ROUTINE:	CDebugLineFX::OnServerMessage
//
//	PURPOSE:	Read an update message from the server.
//
// ----------------------------------------------------------------------- //
LTBOOL CDebugLineFX::OnServerMessage(ILTMessage_Read * pMsg)
{

	// Read the number of lines.
	const int num_lines = pMsg->Readuint16();

	// Set the new maximum number of lines
	m_nMaxLines = pMsg->Readuint32();

	// See if the server is telling us to clear our old lines.
	m_bClearOldLines = (pMsg->Readuint8() != 0);

#ifdef DEBUGLINEFX_DEBUG 
		g_pLTClient->CPrint("Reading %d lines, clear lines is %s.",
			num_lines, m_bClearOldLines ? "true" : "false");
#endif

	// If we don't have any lines, we want to clear our old lines
	// so that the object will be re-positioned correctly.
	if( lines.empty() )
		m_bClearOldLines = true;

	// Clear the lines from memory.  The lines will be removed from
	// the line system in Update.
	if( m_bClearOldLines )
	{
#ifdef DEBUGLINEFX_DEBUG 
		g_pLTClient->CPrint("Clearing %d lines.", lines.size());
#endif

		lines.clear();
	}

	// Read each line.
	DebugLine new_line;
	LT_LINEF  new_linef;
	LTVector maxV(0.0f,0.0f,0.0f);
	LTVector minV(0.0f,0.0f,0.0f);
	bool first = true;
	for(int i = 0; i < num_lines; ++i)
	{
		pMsg->ReadType(&new_line);

		new_linef.verts[0].x = new_line.vSource.x;
		new_linef.verts[0].y = new_line.vSource.y;
		new_linef.verts[0].z = new_line.vSource.z;

		new_linef.verts[1].x = new_line.vDest.x;
		new_linef.verts[1].y = new_line.vDest.y;
		new_linef.verts[1].z = new_line.vDest.z;

		new_linef.rgba.r = new_line.rgba.r;
		new_linef.rgba.g = new_line.rgba.g;
		new_linef.rgba.b = new_line.rgba.b;
		new_linef.rgba.a = new_line.rgba.a;

		lines.push_back( new_linef );

		if (first)
		{
			first = false;
			maxV.x = Max(new_line.vSource.x,new_line.vDest.x);
			maxV.y = Max(new_line.vSource.y,new_line.vDest.y);
			maxV.z = Max(new_line.vSource.z,new_line.vDest.z);

			minV.x = Min(new_line.vSource.x,new_line.vDest.x);
			minV.y = Min(new_line.vSource.y,new_line.vDest.y);
			minV.z = Min(new_line.vSource.z,new_line.vDest.z);

		}
		else
		{
			maxV.x = Max(maxV.x,new_line.vSource.x);
			maxV.y = Max(maxV.y,new_line.vSource.y);
			maxV.z = Max(maxV.z,new_line.vSource.z);
			maxV.x = Max(maxV.x,new_line.vDest.x);
			maxV.y = Max(maxV.y,new_line.vDest.y);
			maxV.z = Max(maxV.z,new_line.vDest.z);

			minV.x = Min(minV.x,new_line.vSource.x);
			minV.y = Min(minV.y,new_line.vSource.y);
			minV.z = Min(minV.z,new_line.vSource.z);
			minV.x = Min(minV.x,new_line.vDest.x);
			minV.y = Min(minV.y,new_line.vDest.y);
			minV.z = Min(minV.z,new_line.vDest.z);

		}
	}

	char szDebugString[256];
	pMsg->ReadString(szDebugString,sizeof(szDebugString));
	m_pStr->SetText(szDebugString);

	if (num_lines)
	{
		vStrPos = (maxV + minV) / 2.0f;
		vStrPos.y += 16.0f;
		uint32 color = SET_ARGB(new_linef.rgba.a,new_linef.rgba.r,new_linef.rgba.g,new_linef.rgba.b);
		m_pStr->SetColor(color);
	}

	// Make sure the lines get updated.
	m_bUpdateLines = true;

	return LTTRUE;
}
float UCBVHaarSingleStumpLearner::run()
{
    if ( UCBVHaarSingleStumpLearner::_numOfCalling == 0 ) {
        init();
    }

    UCBVHaarSingleStumpLearner::_numOfCalling++;
    //cout << "Num of iter:\t" << UCBVHaarSingleStumpLearner::_numOfCalling << " " << this->getTthSeriesElement( UCBVHaarSingleStumpLearner::_numOfCalling ) << flush << endl;
    const int numClasses = _pTrainingData->getNumClasses();

    // set the smoothing value to avoid numerical problem
    // when theta=0.
    setSmoothingVal( 1.0 / (float)_pTrainingData->getNumExamples() * 0.01 );

    vector<sRates> mu(numClasses); // The class-wise rates. See BaseLearner::sRates for more info.
    vector<float> tmpV(numClasses); // The class-wise votes/abstentions

    float tmpThreshold;
    float tmpAlpha;

    float bestEnergy = numeric_limits<float>::max();
    float tmpEnergy;

    HaarData* pHaarData = static_cast<HaarData*>(_pTrainingData);

    // get the whole data matrix
    //const vector<int*>& intImages = pHaarData->getIntImageVector();

    // The data matrix transformed into the feature's space
    vector< pair<int, float> > processedHaarData(_pTrainingData->getNumExamples());

    // I need to prepare both type of sampling

    StumpAlgorithm<float> sAlgo(numClasses);
    sAlgo.initSearchLoop(_pTrainingData);

    float halfTheta;
    if ( _abstention == ABST_REAL || _abstention == ABST_CLASSWISE )
        halfTheta = _theta/2.0;
    else
        halfTheta = 0;

    // The declared features types
    vector<HaarFeature*>& loadedFeatures = pHaarData->getLoadedFeatures();

    // for every feature type
    vector<HaarFeature*>::iterator ftIt;
    //vector<HaarFeature*>::iterator maxftIt;

    vector<float> maxV( loadedFeatures.size() );
    vector<int> maxKey( loadedFeatures.size() );
    vector<int> maxNum( loadedFeatures.size() );

    //claculate the Bk,s,t of the randomly chosen features
    int key = getKeyOfMaximalElement();
    int featureIdx = (int) (key / 10);
    int featureType = (key % 10);

    //for (i = 0, ftIt = loadedFeatures.begin(); ftIt != loadedFeatures.end(); i++ ++ftIt)
    //*ftIt = loadedFeatures[ featureType ];

    // just for readability
    //HaarFeature* pCurrFeature = *ftIt;
    HaarFeature* pCurrFeature = loadedFeatures[ featureType ];
    if (_samplingType != ST_NO_SAMPLING)
        pCurrFeature->setAccessType(AT_RANDOM_SAMPLING);

    // Reset the iterator on the configurations. For random sampling
    // this clear the visited list
    pCurrFeature->loadConfigByNum( featureIdx );


    if (_verbose > 1)
        cout << "Learning type " << pCurrFeature->getName() << ".." << flush;

    // transform the data from intImages to the feature's space
    pCurrFeature->fillHaarData( _pTrainingData->getExamples(), processedHaarData );
    //pCurrFeature->fillHaarData(intImages, processedHaarData);

    // sort the examples in the new space by their coordinate
    sort( processedHaarData.begin(), processedHaarData.end(),
          nor_utils::comparePair<2, int, float, less<float> >() );

    // find the optimal threshold
    tmpThreshold = sAlgo.findSingleThresholdWithInit(processedHaarData.begin(),
                   processedHaarData.end(),
                   _pTrainingData, halfTheta, &mu, &tmpV);

    tmpEnergy = getEnergy(mu, tmpAlpha, tmpV);


    // Store it in the current weak hypothesis.
    // note: I don't really like having so many temp variables
    // but the alternative would be a structure, which would need
    // to be inheritable to make things more consistent. But this would
    // make it less flexible. Therefore, I am still undecided. This
    // might change!
    _alpha = tmpAlpha;
    _v = tmpV;

    // I need to save the configuration because it changes within the object
    _selectedConfig = pCurrFeature->getCurrentConfig();
    // I save the object because it contains the informations about the type,
    // the name, etc..
    _pSelectedFeature = pCurrFeature;
    _threshold = tmpThreshold;

    bestEnergy = tmpEnergy;

    float edge = 0.0;
    for( vector<sRates>::iterator itR = mu.begin(); itR != mu.end(); itR++ ) edge += ( itR->rPls - itR->rMin );
    //need to set the X value
    updateKeys( key, edge * edge );

    if (!_pSelectedFeature)
    {
        cerr << "ERROR: No Haar Feature found. Something must be wrong!" << endl;
        exit(1);
    }
    else
    {
        if (_verbose > 1)
            cout << "Selected type: " << _pSelectedFeature->getName() << endl;
    }

    return bestEnergy;
}
Beispiel #20
0
robot::robot(std::string filename,bool hideCollisionLinks,bool hideJoints,bool convexDecomposeNonConvexCollidables,bool createVisualIfNone,bool showConvexDecompositionDlg,bool centerAboveGround,bool makeModel,bool noSelfCollision,bool positionCtrl): filenameAndPath(filename)
{
	printToConsole("URDF import operation started.");
	openFile();
	readJoints();
	readLinks();
	readSensors();
	createJoints(hideJoints,positionCtrl);
	createLinks(hideCollisionLinks,convexDecomposeNonConvexCollidables,createVisualIfNone,showConvexDecompositionDlg);
	createSensors();

	std::vector<int> parentlessObjects;
	std::vector<int> allShapes;
	std::vector<int> allObjects;
	std::vector<int> allSensors;
	for (int i=0;i<int(vLinks.size());i++)
	{
        if (simGetObjectParent(vLinks[i]->nLinkVisual)==-1)
            parentlessObjects.push_back(vLinks[i]->nLinkVisual);
        allObjects.push_back(vLinks[i]->nLinkVisual);
        allShapes.push_back(vLinks[i]->nLinkVisual);

		if (vLinks[i]->nLinkCollision!=-1)
		{
			if (simGetObjectParent(vLinks[i]->nLinkCollision)==-1)
				parentlessObjects.push_back(vLinks[i]->nLinkCollision);
			allObjects.push_back(vLinks[i]->nLinkCollision);
			allShapes.push_back(vLinks[i]->nLinkCollision);
		}
	}
	for (int i=0;i<int(vJoints.size());i++)
	{
		if (vJoints[i]->nJoint!=-1)
		{
			if (simGetObjectParent(vJoints[i]->nJoint)==-1)
				parentlessObjects.push_back(vJoints[i]->nJoint);
			allObjects.push_back(vJoints[i]->nJoint);
		}
	}
	for (int i=0;i<int(vSensors.size());i++)
	{
		if (vSensors[i]->nSensor!=-1)
		{
			if (simGetObjectParent(vSensors[i]->nSensor)==-1)
				parentlessObjects.push_back(vSensors[i]->nSensor);
			allObjects.push_back(vSensors[i]->nSensor);
			allSensors.push_back(vSensors[i]->nSensor);
		}
		if (vSensors[i]->nSensorAux!=-1)
		{
			allObjects.push_back(vSensors[i]->nSensorAux);
			allSensors.push_back(vSensors[i]->nSensorAux);
		}
	}

	// If we want to alternate respondable mask:
	if (!noSelfCollision)
	{
		for (int i=0;i<int(parentlessObjects.size());i++)
			setLocalRespondableMaskCummulative_alternate(parentlessObjects[i],true);
	}

	// Now center the model:
	if (centerAboveGround)
	{
		bool firstValSet=false;
		C3Vector minV,maxV;
		for (int shNb=0;shNb<int(allShapes.size());shNb++)
		{
			float* vertices;
			int verticesSize;
			int* indices;
			int indicesSize;
			if (simGetShapeMesh(allShapes[shNb],&vertices,&verticesSize,&indices,&indicesSize,NULL)!=-1)
			{
				C7Vector tr;
				simGetObjectPosition(allShapes[shNb],-1,tr.X.data);
				C3Vector euler;
				simGetObjectOrientation(allShapes[shNb],-1,euler.data);
				tr.Q.setEulerAngles(euler);
				for (int i=0;i<verticesSize/3;i++)
				{
					C3Vector v(vertices+3*i);
					v*=tr;
					if (!firstValSet)
					{
						minV=v;
						maxV=v;
						firstValSet=true;
					}
					else
					{
						minV.keepMin(v);
						maxV.keepMax(v);
					}
				}
				simReleaseBuffer((char*)vertices);
				simReleaseBuffer((char*)indices);
			}
		}

		C3Vector shiftAmount((minV+maxV)*-0.5f);
		shiftAmount(2)+=(maxV(2)-minV(2))*0.5f;
		for (int i=0;i<int(parentlessObjects.size());i++)
		{
			C3Vector p;
			simGetObjectPosition(parentlessObjects[i],-1,p.data);
			p+=shiftAmount;
			simSetObjectPosition(parentlessObjects[i],-1,p.data);
		}
	}

	// Now create a model bounding box if that makes sense:
	if ((makeModel)&&(parentlessObjects.size()==1))
	{
		int p=simGetModelProperty(parentlessObjects[0]);
		p|=sim_modelproperty_not_model;
		simSetModelProperty(parentlessObjects[0],p-sim_modelproperty_not_model);

		for (int i=0;i<int(allObjects.size());i++)
		{
			if (allObjects[i]!=parentlessObjects[0])
			{
				int p=simGetObjectProperty(allObjects[i]);
				simSetObjectProperty(allObjects[i],p|sim_objectproperty_selectmodelbaseinstead);
			}
		}

		for (int i=0;i<int(allSensors.size());i++)
		{
			if (allSensors[i]!=parentlessObjects[0])
			{
				int p=simGetObjectProperty(allSensors[i]);
				simSetObjectProperty(allSensors[i],p|sim_objectproperty_dontshowasinsidemodel); // sensors are usually large and it is ok if they do not appear as inside of the model bounding box!
			}
		}

	}

	// Now select all new objects:
	simRemoveObjectFromSelection(sim_handle_all,-1);
	for (int i=0;i<int(allObjects.size());i++)
		simAddObjectToSelection(sim_handle_single,allObjects[i]);
	printToConsole("URDF import operation finished.\n\n");
}
Beispiel #21
0
void remesh(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F, const Eigen::VectorXi &M,
            Eigen::MatrixXd &Vout, Eigen::MatrixXi &Fout, Eigen::VectorXi &Mout,
            double e_length) {
  // The boundary vertices.
  double zmin = 1e10;
  double zmax = -1e10;
  for (int i = 0; i < V.rows(); i++) {
    zmin = std::min(zmin, V(i, 2));
    zmax = std::max(zmax, V(i, 2));
  }
  Eigen::VectorXd minV = V.colwise().minCoeff(),
       maxV = V.colwise().maxCoeff();

  // Compute average edge length.
  if (e_length <= 0) {
    e_length = avg_edgeLength(V, F, M);
  }

  // Convert to OpenMesh.
  TriangleMesh tri;
  IGLToOpenMesh(V, F, tri);
  // Do some more setup.
  tri.update_face_normals();
  tri.update_vertex_normals();
  tri.request_vertex_status();
  tri.request_edge_status();
  tri.request_face_status();

  // Check all edges to see if they're protected or not.
  TriangleMesh::EIter e_it;
  for (e_it = tri.edges_begin(); e_it != tri.edges_end(); ++e_it) {
    // Get both vertices.
    TriangleMesh::VHandle v0 = tri.to_vertex_handle(tri.halfedge_handle(*e_it, 0));
    TriangleMesh::VHandle v1 = tri.to_vertex_handle(tri.halfedge_handle(*e_it, 1));
    // See if both are nonoriginal
    if (M(tri.data(v0).getOriginalIndex()) != GLOBAL::nonoriginal_marker &&
        M(tri.data(v1).getOriginalIndex()) != GLOBAL::nonoriginal_marker) {
      tri.data(*e_it).setProtected(true);
    }
    // Also set vertices if they're original.
    if (M(tri.data(v0).getOriginalIndex()) != GLOBAL::nonoriginal_marker) {
      tri.data(v0).setProtected(true);
    }
    if (M(tri.data(v1).getOriginalIndex()) != GLOBAL::nonoriginal_marker) {
      tri.data(v1).setProtected(true);
    }
  }
  
  /*
  // Check for bad vertices.
  for (int i = 0; i < tri.n_vertices(); ++i) {
    TriangleMesh::VertexHandle vv = TriangleMesh::VertexHandle(i);
    const TriangleMesh::Point &pt = tMesh.point(vv);

    // Set statitonary if original marker set.
    if (M(tri.data(vv).getOriginalIndex()) == GLOBAL::original_marker) {
      
    }
  }
  */

  // Then, do the remeshing--but only split long edge, collapse short edges, 
  // and equalize valences.
  IsotropicRemeshing ir(e_length);
  //int types = ISOTROPIC_REMESHING_TYPES::SPLIT_LONG_EDGES |
              //ISOTROPIC_REMESHING_TYPES::COLLAPSE_SHORT_EDGES |
              //ISOTROPIC_REMESHING_TYPES::EQUALIZE_VALENCES |
              //ISOTROPIC_REMESHING_TYPES::AREA_EQUALIZATION;
  ir.setBoundingBox(TriangleMesh::Point(maxV(0), maxV(1), maxV(2)),
                    TriangleMesh::Point(minV(0), minV(1), minV(2)));
  int types = ISOTROPIC_REMESHING_TYPES::EQUALIZE_VALENCES |
      ISOTROPIC_REMESHING_TYPES::AREA_EQUALIZATION;
  ir.remesh(&tri, 1, types);

  // Then, copy it all back.
  Eigen::VectorXi origIdx;
  OpenMeshToIGL(tri, Vout, Fout, origIdx);
  // Set the new markers as well.
  Mout.resize(Vout.rows());
  for (int i = 0; i < Vout.rows(); ++i) {
    // If it doesn't correspond to a previous vertex, it's a "nonoriginal".
    if (origIdx(i) == -1) {
      Mout(i) = GLOBAL::nonoriginal_marker;
    } else {
      // Otherwise, it's the same marker as it was before.
      Mout(i) = M(origIdx(i));
      int oidx = origIdx(i);
      double moved = ( V.row(oidx) - Vout.row(i) ).norm();
      if ( moved > GLOBAL::EPS && M(oidx) != GLOBAL::nonoriginal_marker) {
        printf("point %d(m:%d new:%d) moved by %lf\n", oidx, M(oidx), i, moved);
        Mout(i) = 10;
      }
    }
    int oidx = origIdx(i);
    if (Vout(i, 2) - zmin < 0 || 
        zmax - Vout(i, 2) < 0) {
      printf("point %d(%d) moved out of bounds! by %lf vs %lf,%lf (%le,%le)\n",
             oidx, M(oidx), Vout(i, 2), zmin, zmax,
             Vout(i,2) - zmin, zmax - Vout(i,2));
      exit(1);
    }
  }
}
Beispiel #22
0
void MVListBase::selectNext(uint direction,int count,ulong modifiers,
    ibool toTop)
/****************************************************************************
*
* Function:     MVListBase::selectNext
* Parameters:   direction   - Flags indicating the direction to move
*               count       - Number of cells to move down
*               modifiers   - Keyboard shift modifiers
*               toTop       - True if the cell should be moved to the top
*
* Description:  Adjusts the selection by the specified number of cells in
*               the specified direction. If the shift modifiers are set,
*               then the selection is extended.
*
****************************************************************************/
{
    MVPoint oldCursor(cursor);
    int maxv = maxV(),minv = minV();
    int maxh = maxH(),minh = minH();

    if (direction & lsBelow)
        if ((cursor.y += count) > maxv)
            cursor.y = maxv;
    if (direction & lsAbove)
        if ((cursor.y -= count) < minv)
            cursor.y = minv;
    if (direction & lsRight)
        if ((cursor.x += count) > maxh)
            cursor.x = maxh;
    if (direction & lsLeft)
        if ((cursor.x -= count) < minh)
            cursor.x = minh;

    if (cursor != oldCursor || (flags & lsExtending)) {
        if ((flags & lsMultipleSelect) && (modifiers & mdShift)) {
            if (cursor == oldCursor)
                return;

            if (direction & lsLeft) {
                if (flags & lsExtendRight) {
                    // We are currently extending in the opposite direction,
                    // so clear all of the cells from the old cursor position
                    // to one above the new cursor position. If the selection
                    // is only one high, then turn off the extending flags.
                    if (cursor.x <= selection.left()) {
                        flags &= ~lsExtendHoriz;
                        selection.right() = selection.left()+1;
                        selection.left() = cursor.x;
                        if (selection.left() != selection.right()-1) {
                            flags |= lsExtendLeft;
                            selectRange(selection);
                            }
                        }
                    else
                        selection.right() = cursor.x+1;
                    clearRange(selection.right(),selection.top(),
                        oldCursor.x+1,selection.bottom());
                    }
                else {
                    // We are currently extending the selection in the same
                    // direction, or have just started to extend the selection
                    flags |= lsExtendLeft;
                    selection.left() = cursor.x;
                    selectRange(cursor.x,selection.top(),
                        oldCursor.x,selection.bottom());
                    }
                }

            if (direction & lsRight) {
                if (flags & lsExtendLeft) {
                    if (cursor.x >= selection.right()-1) {
                        flags &= ~lsExtendHoriz;
                        selection.left() = selection.right()-1;
                        selection.right() = cursor.x+1;
                        if (selection.left() != selection.right()-1) {
                            flags |= lsExtendRight;
                            selectRange(selection);
                            }
                        }
                    else
                        selection.left() = cursor.x;
                    clearRange(oldCursor.x,selection.top(),
                        selection.left(),selection.bottom());
                    }
                else {
                    flags |= lsExtendRight;
                    selection.right() = cursor.x+1;
                    selectRange(oldCursor.x+1,selection.top(),
                        cursor.x+1,selection.bottom());
                    }
                }

            if (direction & lsAbove) {
                if (flags & lsExtendDown) {
                    if (cursor.y <= selection.top()) {
                        flags &= ~lsExtendVert;
                        selection.bottom() = selection.top()+1;
                        selection.top() = cursor.y;
                        if (selection.top() != selection.bottom()-1) {
                            flags |= lsExtendUp;
                            selectRange(selection);
                            }
                        }
                    else
                        selection.bottom() = cursor.y+1;
                    clearRange(selection.left(),selection.bottom(),
                        selection.right(),oldCursor.y+1);
                    }
                else {
                    flags |= lsExtendUp;
                    selection.top() = cursor.y;
                    selectRange(selection.left(),cursor.y,
                        selection.right(),oldCursor.y);
                    }
                }

            if (direction & lsBelow) {
                if (flags & lsExtendUp) {
                    if (cursor.y >= selection.bottom()-1) {
                        flags &= ~lsExtendVert;
                        selection.top() = selection.bottom()-1;
                        selection.bottom() = cursor.y+1;
                        if (selection.top() != selection.bottom()-1) {
                            flags |= lsExtendDown;
                            selectRange(selection);
                            }
                        }
                    else
                        selection.top() = cursor.y;
                    clearRange(selection.left(),oldCursor.y,
                        selection.right(),selection.top());
                    }
                else {
                    flags |= lsExtendDown;
                    selection.bottom() = cursor.y+1;
                    selectRange(selection.left(),oldCursor.y+1,
                        selection.right(),cursor.y+1);
                    }
                }
            dirtyCell(oldCursor);
            }
        else {
            // The selection is not being extended, so clear any previous
            // selection and turn extending off, and reselect the cell
            // under the cursor.
            flags &= ~lsExtending;
            if (!(flags & lsDisjointSelect)) {
                clearSelection();
                selectCell(cursor);
                }
            else {
                dirtyCell(oldCursor);
                dirtyCell(cursor);
                }
            }

        MV_message(owner,evBroadcast,cmListCursorChanged,this);
        refresh();
        }
    focusCurrent(toTop);
}