double Statistics::Max(Image& Source, int& outX, int& outY)
{
    Check1Channel(Source);

    PrepareCoords(Source);

    Kernel(max_coord, In(Source), Out(), *m_PartialResultBuffer, *m_PartialCoordBuffer, Source.Step(), Source.Width(), Source.Height());

    m_PartialResultBuffer->Read();
    m_PartialCoordBuffer->Read(true);

    return ReduceMax(m_PartialResult, m_PartialCoord, outX, outY);
}
Exemple #2
0
/**
 * 习题3.21,将中序表达式写成逆波兰式
 */
void RPN(SqStack &S1, SqStack &S2)
{
	char c;
	int temp;
	InitStack(S1);		//存储临时运算符
	InitStack(S2);		//存储逆波兰式
	Push(S1, '#');
	c = getchar();
	while (c != '#' || !StackEmpty(S1)) {
		if (!In(c)) {		//不是运算符,是操作数
			Push(S2, c);
			c = getchar();	//读入下一个字符
		} else {		//是运算符
			if ('(' == c) {
				Push(S1, c);
				c = getchar();	//读入下一个字符
			} else if (')' == c) {
				while (GetTop(S1) != '(') {
					Pop(S1, temp);
					Push(S2, temp);
				}
				if (GetTop(S1) == '(')
					Pop(S1, temp);
				c = getchar();
			} else {
				switch (Precede(GetTop(S1), c)) {
				case '<':
					Push(S1, c);
					c = getchar();
					break;
				case '>':
					while ('>' == Precede(GetTop(S1), c)) {
						Pop(S1, temp);
						Push(S2, temp);
					}
					Push(S1, c);
					c = getchar();
					break;
				}
			}
		}
		if ('#' == c) {
			while ('#' != GetTop(S1)) {
				Pop(S1, temp);
				Push(S2, temp);
			}
			Pop(S1, temp);
		}
	
	}
}
Exemple #3
0
LONG ModeSense(UWORD     PageCode,
                  UWORD     PageControl,
                  void     *Buffer,
                  UWORD     ParmLen)
{{{
  ParmLen = ParmLen
            + sizeof(tParmHead)       /* ParameterHeader                */
            + sizeof(tBlockDesc);     /* Block-Deskriptor               */

  SetCmd6(0x1A, 0, ParmLen);
  Cmd6.Adr = ((PageControl * 64 + PageCode) % 0x100)*0x100;

  return In(SetCmd((BYTE *)&Cmd6, 6, Buffer, ParmLen, DefTimeout));
}}}
bool GraphMatcher::CanMatch(int a, int b, vector<int>& matching) {
	if (b == -1) {
		if (ignore < 0 || ignore > 0)
			return true;
		else
			return false;
	} else {
		if (!In(b, used) && comparator->CanMatch(A, B, a, b, matching)) {
			return true;
		}
	}

	return false;
}
Exemple #5
0
// Histogram must be an array of at least 1024 elements
void Histogram::Histogram4C(Image& Source, uint * Histogram)
{
   const static int Length = 256 * 4;

   for (int i = 0; i < Length; i++)
      Histogram[i] = 0;

   Buffer Buffer(*m_CL, Histogram, Length);
   Buffer.Send();

   Kernel(histogram_4C, In(Source), Out(), Buffer);

   Buffer.Read(true);
}
Exemple #6
0
bool Sudoku::Load(std::string PathToFile)
{	
	std::ifstream In(PathToFile);
	if(!In.good())
	{
		return false;
	}

	// Read in board from file
	Board.push_back(std::vector<Cell>());
	char Temp;
	while(In.get(Temp))
	{
		if(Temp=='\n')
		{
			Board.push_back(std::vector<Cell>());
		}
		else
		{
			Board[Board.size()-1].push_back(atoi(&Temp));
			if(atoi(&Temp)>0)
			{
				// Filled value
				FilledCells++;
			}
		}
	}
	In.close();

	// Validate board
	if(Board.size()==0)
	{
		// Invalid board
		return false;
	}

	int Size=Board[0].size();
	for(unsigned int y=0; y<Board.size(); y++)
	{
		if(Board[y].size()!=Size)
		{
			// Not regularly shaped
			return false;
		}
	}

	TotalCells=Board.size()*Board[0].size();

	return true;
}
Exemple #7
0
static void GetIntersection(const struct LineClipping_Rectangle *r,
	const struct LineClipping_Segment *s,
	int outcode,
	double *x,
	double *y) /*sets (x, y) to the intersection point of s and an edge of r contained in `outcode'*/
{
	if (In(TOP, outcode)) {
		assert(s->y0 != s->y1);
		*x = s->x0 + (s->x1 - s->x0) * (r->yMax - s->y0) / (s->y1 - s->y0);
		*y = r->yMax;
	} else if (In(BOTTOM, outcode)) {
		assert(s->y0 != s->y1);
		*x = s->x0 + (s->x1 - s->x0) * (r->yMin - s->y0) / (s->y1 - s->y0);
		*y = r->yMin;
	} else if (In(RIGHT, outcode)) {
		assert(s->x0 != s->x1);
		*y = s->y0 + (s->y1 - s->y0) * (r->xMax - s->x0) / (s->x1 - s->x0);
		*x = r->xMax;
	} else if (In(LEFT, outcode)) {
		assert(s->x0 != s->x1);
		*y = s->y0 + (s->y1 - s->y0) * (r->xMin - s->x0) / (s->x1 - s->x0);
		*x = r->xMin;
	}
}
void Statistics::StdDev(Image& Source, double outVal[4], double outMean[4])
{
    Mean(Source, outMean);

    cl_float4 fmeans = {{float(outMean[0]), float(outMean[1]), float(outMean[2]), float(outMean[3])}};

    Kernel(reduce_stddev, In(Source), Out(), *m_PartialResultBuffer, Source.Step(), Source.Width(), Source.Height(), fmeans);

    m_PartialResultBuffer->Read(true);

    ReduceMean(m_PartialResult, Source.NbChannels(), outVal);

    for (uint i = 0; i < Source.NbChannels(); i++)
        outVal[i] = sqrt(outVal[i]);
}
void CSourcesListBox::LoadNetStream(wxString sName, wxString & sMainUrl,MusikSongIdArray * purlids )
{
	wxString sFilename = sName;
	SourcesToFilename( &sFilename ,MUSIK_SOURCES_NETSTREAM);

	if ( !wxFileExists( sFilename ) )
	{
		return ;
	}
	wxTextFile In( sFilename );
	In.Open();
	if ( !In.IsOpened() )
	{
		return;
	}
	if(In.GetLineCount() >= 1)
	{
		sMainUrl = ( In.GetLine(0) );
	}
	In.Close();

    if(purlids)
    {
        purlids->Clear();
        PLFile f(wxGetApp().Prefs.GetProxyServer());
        if(!f.Read(sMainUrl))
        {
            PLFileEntry e;
            e.File = sMainUrl;
            f.push_back(e);
        }
        for(size_t i = 0;i < f.size(); i++)
        {
            CMusikSong *pSong = new CMusikSong;
            if(f[i].Title.IsEmpty())
                pSong->MetaData.Title = ConvToUTF8(sName);
            else
                pSong->MetaData.Title = ConvToUTF8( f[i].Title );
            pSong->MetaData.nTracknum = i + 1;
            pSong->MetaData.Filename = f[i].File;
            pSong->MetaData.Artist = ConvToUTF8( sName );
            pSong->MetaData.eFormat = MUSIK_FORMAT_NETSTREAM;
            purlids->Add(MusikSongId(pSong));
        }
    }
	return;
}
//实际值-预测值-置信度
void CEvaluate::CalcChart(CDoubleMatrix &m, CPtrArray *pArr)
{
	int nValue = 0;
	int i=0, j=0, nSize=0, nRow=0;
	double fSum = 0;
	CDoubleVector v;
	
	m_fValCnt = 0;
	bool bString = m_pDecTree->m_TargetField.cFieldType == fString ? true : false;
	//转化非Hit值的置信度
	nRow = m.mrow();
	if (bString)
	{
		for (i=0; i<nRow; i++)
		{
		}
	}
	else
	{
		for (i=0; i<nRow; i++)
		{
			nValue = m(1)(i);//预测值
			if (In(nValue)) continue;
			m(2)(i) = 1-m(2)(i); //置信度
		}
	}
	//计算Value
	for (i=0; i<nRow; i++)
	{
		CalcConfidence(m(0)(i),m(2)(i),pArr);
	}
	//换算
	double fSX = 0, fSY=0;
	nSize = pArr->GetSize();
	for (i=nSize-1; i>=0; i--)
	{
		CEv *pEv = (CEv *)pArr->GetAt(i);
		fSX += pEv->fX;
		fSY += pEv->fY;
		pEv->fX = fSX;
		pEv->fY = fSY;
		pEv->fX /= nRow;             //转换为百分位数
		pEv->fY /= m_fValCnt;        //转换为Gain值
	}
}
Exemple #11
0
int main()
{
	BinaryTree <int>  BTT;
	BTT.input();
	LevelOrder<int> Level(BTT);
	//Level.Traverse();
	PostOrder<int> Post(BTT);
	//Post.Traverse();
	InOrder<int> In(BTT);
	//In.Traverse();
	PreOrder<int> Pre(BTT);
	//Pre.Traverse();
    cout<<"******************************"<<endl;   
	cout<<"*selet an item        "<<endl;
	cout<<"*levelorder traverse,enter'1' "   <<endl;
	cout<<"*preorder traverse,enter '2'  "<<endl;
	cout<<"*inorder traverse enter '3'    "<<endl;
    cout<<"*postorder traverse enter '3'    "<<endl;	
	cout<<"*quit,enter  '0'          "<<endl;
	cout<<"******************************"<<endl;
	int i;	
	
	do
	{   cin>>i;  
		cout<<"ÇëÊäÈëÄãµÄÑ¡Ôñ£º";
		cout<<"1---> levelorder traverse¡¢2----preorder traverse¡¢3----inorder traverse¡¢4--->postorder traverse¡¢0--->quit¡¢"<<endl;

	   switch(i)
	   { 
	      case 1:	  	
               Level.Traverse();        
			   break;
		   case 2: 	   	
               Pre.Traverse();
			   break;
		   case 3:	  
               In.Traverse();
			    break;
		   case 4:   
               Post.Traverse();
			   break;
	   }		   
	   }while(i!=0);
	return 1;
}
Exemple #12
0
void MATRIX::CreatePermutation(int min, int max) {

	int j;
	int newVal;

	for (j=0;j<width;j++)
		Set(0,j,min-1);

	for (j=0;j<width;j++) {

		newVal = RandInt(min,max);

		while ( In(newVal) )
			newVal = RandInt(min,max);

		Set(0,j,newVal);
	}
}
Exemple #13
0
SElemType EvaluateExpression() /* 算法3.4 */
{   /* 算术表达式求值的算符优先算法。设OPTR和OPND分别为运算符栈和运算数栈 */
    SqStack OPTR,OPND;
    SElemType a,b,c,x,theta;
    InitStack(&OPTR);
    Push(&OPTR,'#');
    InitStack(&OPND);
    c=getchar();
    GetTop(OPTR,&x);
    while(c!='#'||x!='#')
    {
        if(In(c)) /* 是7种运算符之一 */
            switch(Precede(x,c))
            {
            case'<':
                Push(&OPTR,c); /* 栈顶元素优先权低 */
                c=getchar();
                break;
            case'=':
                Pop(&OPTR,&x); /* 脱括号并接收下一字符 */
                c=getchar();
                break;
            case'>':
                Pop(&OPTR,&theta); /* 退栈并将运算结果入栈 */
                Pop(&OPND,&b);
                Pop(&OPND,&a);
                Push(&OPND,Operate(a,theta,b));
                break;
            }
        else if(c>='0'&&c<='9') /* c是操作数 */
        {
            Push(&OPND,c);
            c=getchar();
        }
        else /* c是非法字符 */
        {
            printf("ERROR4\n");
            exit(ERROR);
        }
        GetTop(OPTR,&x);
    }
    GetTop(OPND,&x);
    return x;
}
 void In(vector<string> &res,int *num,int index,string s)
 {
     if(index!=4)
     {
         int size=s.size();
         for(int i=0;i<(size>3?3:size);i++)
         {
             string cs=s;
             string sub=s.substr(0,i+1);
             if(sub[0]=='0' && sub.size()!=1)
               goto finish;
             num[index]=atoi(sub.c_str());
             cs.erase(0,i+1);
             if(!(i==3 && num[index]>255))
                 In(res,num,index+1,cs);
         }
         finish:;
     }
     else
     {
         
         if(!s.size())
         {
             string newstr="";
             for(int i=0;i<4;i++)
         {
             if(num[i]>255)
                {
                    goto end;//res.push_back("exceed");
                }
                else 
                {
                if(i!=3)
                newstr+=itoa(num[i])+".";
                else
                newstr+=itoa(num[i]);
                }
         }
         res.push_back(newstr);
         }
         end:;
     }
 }
wxString CSourcesListBox::LoadDynPlaylist( wxString sName )
{
	wxString sReturn;

	SourcesToFilename( &sName, MUSIK_SOURCES_PLAYLIST_DYNAMIC );

	if ( !wxFileExists( sName ) )
		return wxT( "" );

	wxTextFile In( sName );
	In.Open();
	if ( !In.IsOpened() )
		return wxT( "" );
	for ( size_t i = 0; i < In.GetLineCount(); i++ )
	{
		sReturn += In.GetLine( i );
	}
	return sReturn;
}
Exemple #16
0
char CEmailAddress::MPAtom(const CString& iStr, int& curPos){
	/*
	  atom = 1*<any CHAR except specials, SPACE and CTLs>
	*/

	if (curPos >= (int) iStr.GetLength()) {		
		return 0;
	}

	unsigned char c = (unsigned char) iStr[curPos];
	if (c <= 31) return 0;
	else if (c == 127) return 0;
	else if (c == ' ') return 0;
	else if (In(c, g_strRfc822EmailAddressSpecials)) return 0;
	else {
		curPos++;
		return c;
	}
}
Exemple #17
0
char CMail::MPAtom(const CString& iStr, int& curPos){
  /*
    atom =  1*<any CHAR except specials, SPACE and CTLs>
    */

#ifdef M_DEBUG
  cout << "MPAtom() - " << curPos << endl;
#endif

  char c = iStr[curPos];
  if ((c >= 0)&&(c <= 31)) return 0;
  else if (c == 127) return 0;
  else if (c == ' ') return 0;
  else if (In(c, Specials)) return 0;
  else {    
    curPos++;
    return c;
  }
}
Exemple #18
0
LONG ReadCapacity(BOOLEAN PMI, ULONG *BlockAdr, ULONG *BlockLen)
{{{
ULONG Data[2];
LONG ret;

  SetCmd10(0x25, *BlockAdr, 0);

  if (PMI)
    Cmd10.LenLow = 1;

  /* und rufen */
  ret = In(SetCmd((BYTE *)&Cmd10, 10, Data, sizeof(Data), DefTimeout));

  /* und Antwort, bitte */
  if (ret == 0)
  {
    *BlockAdr = Data[0];
    *BlockLen = Data[1];
  }

  return ret;
}}}
Exemple #19
0
void FiltersVector::GaussianBlur(ImageBuffer& Source, ImageBuffer& Dest, float Sigma)
{
   CheckCompatibility(Source, Dest);

   // Prepare mask
   int MaskSize = int(ceil(3 * Sigma));

   if (Sigma <= 0 || MaskSize > 31)
      throw cl::Error(CL_INVALID_ARG_VALUE, "Invalid sigma used with GaussianBlur - allowed : 0.01-10");

   uint NbElements = (MaskSize * 2 + 1 ) * (MaskSize * 2 + 1 );

   std::vector<float> Mask(NbElements);

   GenerateBlurMask(Mask, Sigma, MaskSize);
   // NOTE : Maybe we should generate the mask in the device to prevent having to send that buffer


   // Send mask to device
   ReadBuffer MaskBuffer(*m_CL, Mask.data(), NbElements);

   // Execute kernel
   Kernel(gaussian_blur, In(Source), Out(Dest), Source.Step(), Dest.Step(), Source.Height(), MaskBuffer, MaskSize);
}
Exemple #20
0
static rc_t CreateConfig(char* argv0) {
    const KFile* std_in = NULL;
    KDirectory* native = NULL;
    KDirectory* dir = NULL;
    rc_t rc = 0;
    char* location = NULL;
    char* mod = NULL;
    char* wmod = NULL;
    char* refseq = NULL;
    if (rc == 0) {
        rc = KDirectoryNativeDir(&native);
    }
    if (rc == 0) {
        const char* def = NULL;
        char cwd[PATH_MAX + 1] = "";
        const char* home = getenv("HOME");
        if (home)
        {   def = home; }
        else {
            rc = VPathGetCWD(cwd, sizeof cwd);
            if (rc == 0 && cwd[0])
            {   def = cwd; }
            else
            {   def = "."; }
        }
        while (rc == 0) {
            char buffer[PATH_MAX + 1];
            rc = In("Specify configuration files directory", def, &location);
            if (rc == 0) {
                rc = KDirectoryOpenDirUpdate(native, &dir, false, location);
                if (rc == 0) {
                    rc = KDirectoryVVisit
                        (dir, false, scan_config_dir, buffer, ".", NULL);
                    if (rc != 0) {
                        if (rc ==
                             RC(rcExe, rcDirectory, rcListing, rcFile, rcExists)
                            && buffer[0])
                        {
                            PLOGERR(klogErr, (klogErr, rc,
                                "Configuration file found: $(dir)/$(name)",
                                "dir=%s,name=%s", location, buffer));
                            rc = 0;
                            buffer[0] = '\0';
                            continue;
                        }
                        else {
                            PLOGERR(klogErr, (klogErr, rc, "$(dir)/$(name)",
                                "dir=%s,name=%s", location, buffer));
                        }
                    }
                    break;
                }
                else if (GetRCObject(rc) == rcPath &&
                (GetRCState(rc) == rcIncorrect || GetRCState(rc) == rcNotFound))
                {
                    PLOGERR(klogErr,
                        (klogErr, rc, "$(path)", "path=%s", location));
                    rc = 0;
                }
                else { DISP_RC(rc, location); }
            }
        }
    }
    while (rc == 0) {
        const KDirectory* dir = NULL;
        rc = In("Specify refseq installation directory", NULL, &refseq);
        if (rc != 0)
        {   break; }
        rc = KDirectoryOpenDirRead(native, &dir, false, refseq);
        if (rc == 0) {
            RELEASE(KDirectory, dir);
            break;
        }
        else if (GetRCObject(rc) == rcPath
              && GetRCState(rc) == rcIncorrect)
        {
            PLOGERR(klogErr,
                (klogErr, rc, "$(path)", "path=%s", refseq));
            rc = 0;
        }
        DISP_RC(rc, refseq);
    }
    if (rc == 0) {
        char buffer[512];
        const char path[] = "vdb-config.kfg";
        uint64_t pos = 0;
        KFile* f = NULL;
        rc = KDirectoryCreateFile(dir, &f, false, 0664, kcmCreate, path);
        DISP_RC(rc, path);
        if (rc == 0) {
            int n = snprintf(buffer, sizeof buffer,
                "refseq/servers = \"%s\"\n", refseq);
            if (n >= sizeof buffer) {
                rc = RC(rcExe, rcFile, rcWriting, rcBuffer, rcInsufficient);
            }
            else {
                size_t num_writ = 0;
                rc = KFileWrite(f, pos, buffer, strlen(buffer), &num_writ);
                pos += num_writ;
            }
        }
        if (rc == 0) {
            const char buffer[] = "refseq/volumes = \".\"\n";
            size_t num_writ = 0;
            rc = KFileWrite(f, pos, buffer, strlen(buffer), &num_writ);
            pos += num_writ;
        }
        if (rc == 0 && mod && mod[0]) {
            int n = snprintf(buffer, sizeof buffer,
                "vdb/module/paths = \"%s\"\n", mod);
            if (n >= sizeof buffer) {
                rc = RC(rcExe, rcFile, rcWriting, rcBuffer, rcInsufficient);
            }
            else {
                size_t num_writ = 0;
                rc = KFileWrite(f, pos, buffer, strlen(buffer), &num_writ);
                pos += num_writ;
            }
        }
        if (rc == 0 && wmod && wmod[0]) {
            int n = snprintf(buffer, sizeof buffer,
                "vdb/wmodule/paths = \"%s\"\n", wmod);
            if (n >= sizeof buffer) {
                rc = RC(rcExe, rcFile, rcWriting, rcBuffer, rcInsufficient);
            }
            else {
                size_t num_writ = 0;
                rc = KFileWrite(f, pos, buffer, strlen(buffer), &num_writ);
                pos += num_writ;
            }
        }
        RELEASE(KFile, f);
    }
    free(mod);
    free(wmod);
    free(refseq);
    free(location);
    RELEASE(KDirectory, dir);
    RELEASE(KDirectory, native);
    RELEASE(KFile, std_in);
    DestroyStdin();
    return rc;
}
Exemple #21
0
bool C_Mouse::InRect(RECT rc) {
    return (In(rc.left,rc.top,rc.left+rc.right,rc.top+rc.bottom));
}
Exemple #22
0
//Private methods
bool CtbzPlugin::Compress(const std::string& input, const std::string& output, IProgressbar* callback)
{
  bool Ret = false;
  FILE* Out = fopen(output.c_str(), "wb");

  // Open up the output file
  if(!Out)
  {
    std::cout << i8n("Error out file!") << '\n';
    Ret = false;
  }
  else
  {
    BZFILE* BZ = 0;
    int Err = 0;
    BZ = BZ2_bzWriteOpen(&Err, Out, 9, 0, 90);

    if(Err != BZ_OK)
    {
      std::cout << i8n("Error bzWriteOpen!") << '\n';
      Ret = false;
    }
    else
    {
      // Open up the input file
      std::ifstream In(input.c_str(), std::ios::in | std::ios::binary);

      if(!In.good())
      {
        std::cout << i8n("Error in file!") << '\n';
        Ret = false;
      }
      else
      {
        // Get the file size. (I hate C I/O, so don't use them :D )
        struct stat Info;
        double Total;
        //Try to stat file.
        if(stat(input.c_str(), &Info) == -1)
        {
          std::cout << i8n("Cannot stat ") << input.c_str() << '\n';
          Ret = false;
        }
        else
        {
          char Buffer[4096];
          memset(Buffer, 0, 4096);
          Total = Info.st_size;
          double Done = 0;
          do
          {
            In.read(Buffer, 4096);
            std::streamsize BytesRead = In.gcount();
            Done += BytesRead;
            int Result = static_cast<int>((Done*50)/Total)+50;
            std::string Mess(i8n("bz2 compression of\n"));
            std::stringstream DoneStr;
            DoneStr << (Result-50)*2;
            Mess += output + " :  " + DoneStr.str() + "%";
            bool Continue = callback->UpdateProgress(Mess, false, Result);
            if(!Continue)
              break;
            BZ2_bzWrite(&Err, BZ, Buffer, BytesRead);
          } while(In.good());

          if( In.bad() || !In.eof() )
            Ret = false;
          else
            Ret = true;

          In.close();
        }

        // Close up.
        BZ2_bzWriteClose(&Err, BZ, 0, 0, 0);
        fclose(Out);
        Out = 0;
      }
    }
  }

  return Ret;
}
Exemple #23
0
void ptRun(const gchar*     Name,
           gint       NrParameters,
           const GimpParam* Parameter,
           gint *nreturn_vals,
           GimpParam **return_vals) {
  printf("(%s,%d) '%s'\n",__FILE__,__LINE__,__PRETTY_FUNCTION__);
  printf("Name         : '%s'\n",Name);
  printf("NrParameters : %d\n",NrParameters);
  if (!strcmp(Name,"photivoSendToGimp")) {
    printf("RunMode      : %d\n",Parameter[0].data.d_int32);
    printf("FileName1    : '%s'\n",Parameter[1].data.d_string);
    printf("FileName2    : '%s'\n",Parameter[2].data.d_string);

    QFile GimpFile(Parameter[1].data.d_string);
    bool result = GimpFile.open(QIODevice::ReadOnly | QIODevice::Text);
    assert(result);

    QTextStream In(&GimpFile);

    QString ImageFileName = In.readLine();
    QString ExifFileName  = In.readLine();
    QString ICCFileName   = In.readLine();

    // Read image
    FILE *InputFile = fopen(ImageFileName.toLocal8Bit().data(),"rb");
    if (!InputFile) {
      ptLogError(1,ImageFileName.toLocal8Bit().data());
      return; // ptError_FileOpen;
    }

    short    Colors;
    unsigned short Width;
    unsigned short Height;
    unsigned short BitsPerColor;
    char     Buffer[128];

    // Extremely naive. Probably just enough for testcases.
    char *s = fgets(Buffer,127,InputFile);
    assert ( s );
    int n = sscanf(Buffer,"P%hd",&Colors);
    assert ( 1 == n );
    assert(Colors == 6 );
    do {
      s = fgets(Buffer,127,InputFile);
      assert ( s );
    } while (Buffer[0] == '#');
    sscanf(Buffer,"%hd %hd",&Width,&Height);
    s = fgets(Buffer,127,InputFile);
    assert ( s );
    sscanf(Buffer,"%hd",&BitsPerColor);
    assert(BitsPerColor == 0xffff);

    Colors = 3;

    unsigned short (* ImageForGimp)[3] =
      (unsigned short (*)[3]) CALLOC2(Width*Height,sizeof(*ImageForGimp));
    ptMemoryError(ImageForGimp,__FILE__,__LINE__);

    unsigned short*  PpmRow = (unsigned short *) CALLOC2(Width*Height,sizeof(*PpmRow));
    ptMemoryError(PpmRow,__FILE__,__LINE__);

    for (unsigned short Row=0; Row<Height; Row++) {
      size_t RV = fread(PpmRow,Colors*2,Width,InputFile);
      if (RV != (size_t) Width) {
        printf("ReadPpm error. Expected %d bytes. Got %d\n",Width,(int)RV);
        exit(EXIT_FAILURE);
      }
      if (htons(0x55aa) != 0x55aa) {
        swab((char *)PpmRow,(char *)PpmRow,Width*Colors*2);
      }
      for (unsigned short Col=0; Col<Width; Col++) {
        for (short c=0;c<3;c++) {
          ImageForGimp[Row*Width+Col][c] = PpmRow[Col*Colors+c];
        }
      }
    }

    FREE2(PpmRow);
    FCLOSE(InputFile);

    QFile ExifFile(ExifFileName);
    result = ExifFile.open(QIODevice::ReadOnly);
    assert(result);
    qint64 FileSize = ExifFile.size();
    QDataStream ExifIn(&ExifFile);
    char* ExifBuffer = (char *) MALLOC2(FileSize);
    ptMemoryError(ExifBuffer,__FILE__,__LINE__);
    unsigned ExifBufferLength = ExifIn.readRawData(ExifBuffer,FileSize);
    ExifFile.close();

    QFile ICCFile(ICCFileName);
    result = ICCFile.open(QIODevice::ReadOnly);
    assert(result);
    qint64 FileSize2 = ICCFile.size();
    QDataStream ICCIn(&ICCFile);
    char* ICCBuffer = (char *) MALLOC2(FileSize2);
    ptMemoryError(ICCBuffer,__FILE__,__LINE__);
    unsigned ICCBufferLength = ICCIn.readRawData(ICCBuffer,FileSize2);
    ICCFile.close();

    // And now copy to gimp.
    gint32 GimpImage = gimp_image_new(Width,
                                      Height,
                                      GIMP_RGB);
    assert (GimpImage != -1);
    gint32 GimpLayer = gimp_layer_new(GimpImage,
                                      "BG",
                                      Width,
                                      Height,
                                      GIMP_RGB_IMAGE,
                                      100.0,
                                      GIMP_NORMAL_MODE);
#if GIMP_MINOR_VERSION<=6
    gimp_image_add_layer(GimpImage,GimpLayer,0);
#else
    gimp_image_insert_layer(GimpImage,GimpLayer,0,0);
#endif
    GimpDrawable* Drawable = gimp_drawable_get(GimpLayer);
    GimpPixelRgn PixelRegion;
    gimp_pixel_rgn_init(&PixelRegion,
                        Drawable,
                        0,
                        0,
                        Drawable->width,
                        Drawable->height,
                        true,
                        false);
    unsigned short TileHeight = gimp_tile_height();
    for (unsigned short Row=0; Row<Height; Row+=TileHeight) {
      unsigned short NrRows = MIN(Height-Row, (int)TileHeight);
      guint8* Buffer = g_new(guint8,TileHeight*Width*3);
      for (unsigned short i=0; i<NrRows; i++) {
        for (unsigned short j=0; j<Width; j++) {
          for (short c=0;c<3;c++) {
            Buffer[3*(i*Width+j)+c] =
              ImageForGimp[(Row+i)*Width+j][c]>>8;
          }
        }
      }
      gimp_pixel_rgn_set_rect(&PixelRegion,
                              Buffer,
                              0,
                              Row,
                              Width,
                              NrRows);
      g_free(Buffer);
    }
    gimp_drawable_flush(Drawable);
    gimp_drawable_detach(Drawable);
    FREE2(ImageForGimp);
    GimpParasite* GimpExifData = gimp_parasite_new("exif-data",
                                                   GIMP_PARASITE_PERSISTENT,
                                                   ExifBufferLength,
                                                   ExifBuffer);
    gimp_image_parasite_attach(GimpImage,GimpExifData);
    gimp_parasite_free(GimpExifData);
    FREE2(ExifBuffer);

    GimpParasite* GimpICCData = gimp_parasite_new("icc-profile",
                                                   GIMP_PARASITE_PERSISTENT,
                                                   ICCBufferLength,
                                                   ICCBuffer);
    gimp_image_parasite_attach(GimpImage,GimpICCData);
    gimp_parasite_free(GimpICCData);
    FREE2(ICCBuffer);

    static GimpParam Values[2];
    *nreturn_vals = 2;
    *return_vals = Values;
    Values[0].type = GIMP_PDB_STATUS;
    Values[0].data.d_status = GIMP_PDB_SUCCESS;
    Values[1].type = GIMP_PDB_IMAGE;
    Values[1].data.d_image = GimpImage;

    QFile::remove(ImageFileName);
    QFile::remove(ExifFileName);
    QFile::remove(ICCFileName);
    QFile::remove(Parameter[1].data.d_string);

  }
Exemple #24
0
double initialize(double **data, double **centroids, int *ppp, int rank, int size, options opt) {
  MPI_Status status;
  double comm_time = 0.0;

  if(rank == 0) {
    #ifdef TIME_ALL
      timestamp_type comm_s, comm_e;  
    #endif
    int i, idx, owner;

    int *init = (int*) malloc(opt.n_centroids * sizeof(int));
    check(init);

    double *point = (double*) malloc(opt.dimensions * sizeof(double));
    check(point);
    double *tofree = point;

    for(i = 0; i < opt.n_centroids; i++){
        while(In(idx = randint(opt.n_points), init, i));
        init[i] = idx;
        owner = get_owner(&idx, ppp);
        if(owner != 0) {
          #ifdef TIME_ALL
            get_timestamp(&comm_s);
          #endif
          MPI_Send(&idx, 1, MPI_INT, owner, 999, MPI_COMM_WORLD);
          MPI_Recv(point, opt.dimensions, MPI_DOUBLE, owner, 999, MPI_COMM_WORLD, &status);
          #ifdef TIME_ALL
            get_timestamp(&comm_e);
            comm_time += timestamp_diff_in_seconds(comm_s, comm_e);
          #endif
        } 
        else{
          point = data[idx];
        }
        // printf("%d owned by %d at %d ", init[i], owner, idx);
        // print_vec(point, opt.dimensions);
        memcpy(centroids[i], point, opt.dimensions * sizeof(double));
        point = tofree;
    }
    idx = -1;
    #ifdef TIME_ALL
      get_timestamp(&comm_s);
    #endif
    for(i = 1; i < size; i++)
      MPI_Send(&idx, 1, MPI_INT, i, 999, MPI_COMM_WORLD);
    #ifdef TIME_ALL
      get_timestamp(&comm_e);
      comm_time += timestamp_diff_in_seconds(comm_s, comm_e);
    #endif

    free(init);
    free(tofree);
  }
  else {
    int get_point;
    while(1) {
      MPI_Recv(&get_point, 1, MPI_INT, 0, 999, MPI_COMM_WORLD, &status);
      if(get_point != -1)
        MPI_Send(data[get_point], opt.dimensions, MPI_DOUBLE, 0, 999, MPI_COMM_WORLD);
      else break;
    }
  }
  return comm_time;
}
Exemple #25
0
double EvaExpression()
{
	SqStack<int> OPTR;
	SqStack<double> OPND;
	
	int buffer;
	bool preIsDigit = false;
	bool hasDot = false; 
	int exp;
	
	double ans = 0;
	
	OPTR.Push(Index('#'));
	
	buffer = mGetchar();
	if (buffer == INPUT_VALID) return EvaExpression();

	while (buffer!='#' || OPTR.GetTop()!=Index('#'))
	{
		if (buffer == '.')
		{
			if (hasDot)
			{
				char tmp_s[1024];
				printf("您的输入有误,请确保输入的算术表达式合法!\n");
				if (buffer != '\n') gets(tmp_s);
				return EvaExpression();
			}
			hasDot = true;
			exp = 0;
			
			buffer = mGetchar();
			if (buffer == INPUT_VALID) return EvaExpression();
		}
		else if (In(buffer, DIGIT)) 
		{
			if (preIsDigit)
			{
				double number; 
				OPND.Pop(&number);
				
				if (hasDot)
				{
					exp--;
					number += E(buffer-'0', exp);
				}
				else
				{
					number *= 10;
					number += buffer-'0';
				}
				OPND.Push(number);
			}
			else
			{
				OPND.Push(buffer-'0');
				preIsDigit = true; 
			}
			
			buffer = mGetchar();
			if (buffer == INPUT_VALID) return EvaExpression();
		}
		else 
		{
			int toOperate, top;
			preIsDigit = false;
			hasDot = false;
			toOperate = Index(buffer);
			top = OPTR.GetTop();
			switch(cmp[top][toOperate])
			{
				case -1:
					OPTR.Push(toOperate);
					buffer = mGetchar();
					if (buffer == INPUT_VALID) return EvaExpression();
					break;
				case 0:
					int tmp;
					OPTR.Pop(&tmp);
					buffer = mGetchar();
					if (buffer == INPUT_VALID) return EvaExpression();
					break;
				case 1:
					int op;
					double a, b;
					if (OPTR.Pop(&op) != OK || OPND.Pop(&b) != OK || OPND.Pop(&a) != OK)
					{
						char tmp_s[1024];
						printf("您的输入有误,请确保输入的算术表达式合法!\n");
						if (buffer != '\n') gets(tmp_s);
						return EvaExpression();
					}
					ans = Operate(a, op, b);  
					OPND.Push(ans);
					break;
				case ERROR:
					char tmp_s[1024];
					printf("您的输入有误,请确保输入的算术表达式合法!\n");
					if (buffer != '\n') gets(tmp_s);
					return EvaExpression();
				default:
					exit(ERROR);
			}
		}
		
	}
	OPND.Pop(&ans);
	if (OPTR.IsEmpty() || OPND.IsEmpty() ) return ans;
	
	char tmp_s[1024];
	printf("您的输入有误,请确保输入的算术表达式合法!\n");
	if (buffer != '\n') gets(tmp_s);
	return EvaExpression();
}                
Exemple #26
0
LONG TestUnitReady(void)
{
  SetCmd6(0x00, 0, 0);
  return In(SetCmd((BYTE *)&Cmd6, 6, NULL, 0, DefTimeout));
}
    void PoissonReconstruction::PoissonRecon(int argc , char* argv[], const MagicDGP::Point3DSet* pPC, std::vector< PlyValueVertex< float > >& vertices, std::vector< std::vector< int > >& polygons)
    {
        cmdLineString
            In( "in" ) ,
            Out( "out" ) ,
            VoxelGrid( "voxel" ) ,
            XForm( "xForm" );

        cmdLineReadable
            Performance( "performance" ) ,
            ShowResidual( "showResidual" ) ,
            NoComments( "noComments" ) ,
            PolygonMesh( "polygonMesh" ) ,
            Confidence( "confidence" ) ,
            NonManifold( "nonManifold" ) ,
            ASCII( "ascii" ) ,
            Density( "density" ) ,
            Verbose( "verbose" );

        cmdLineInt
            Depth( "depth" , 8 ) ,
            SolverDivide( "solverDivide" , 8 ) ,
            IsoDivide( "isoDivide" , 8 ) ,
            KernelDepth( "kernelDepth" ) ,
            AdaptiveExponent( "adaptiveExp" , 1 ) ,
            MinIters( "minIters" , 24 ) ,
            FixedIters( "iters" , -1 ) ,
            VoxelDepth( "voxelDepth" , -1 ) ,
            MinDepth( "minDepth" , 5 ) ,
            MaxSolveDepth( "maxSolveDepth" ) ,
            BoundaryType( "boundary" , 1 ) ,
            Threads( "threads" , omp_get_num_procs() );

        cmdLineFloat
            SamplesPerNode( "samplesPerNode" , 1.f ) ,
            Scale( "scale" , 1.1f ) ,
            SolverAccuracy( "accuracy" , float(1e-3) ) ,
            PointWeight( "pointWeight" , 4.f );

        cmdLineReadable* params[] =
        {
            &In , &Depth , &Out , &XForm ,
            &SolverDivide , &IsoDivide , &Scale , &Verbose , &SolverAccuracy , &NoComments ,
            &KernelDepth , &SamplesPerNode , &Confidence , &NonManifold , &PolygonMesh , &ASCII , &ShowResidual , &MinIters , &FixedIters , &VoxelDepth ,
            &PointWeight , &VoxelGrid , &Threads , &MinDepth , &MaxSolveDepth ,
            &AdaptiveExponent , &BoundaryType ,
            &Density
        };

        cmdLineParse( argc , argv , sizeof(params)/sizeof(cmdLineReadable*) , params , 1 );
        /*if( Density.set ) 
            return Execute< 2 , PlyValueVertex< Real > , true  >(argc , argv, pPC);
        else       
            return Execute< 2 ,      PlyVertex< Real > , false >(argc , argv, pPC);*/
        //Execute
        int i;
        int paramNum = sizeof(params)/sizeof(cmdLineReadable*);
        int commentNum=0;
        char **comments;

        comments = new char*[paramNum + 7];
        for( i=0 ; i<paramNum+7 ; i++ ) comments[i] = new char[1024];

        //if( Verbose.set ) echoStdout=1;

        XForm4x4< Real > xForm , iXForm;
        if( XForm.set )
        {
            FILE* fp = fopen( XForm.value , "r" );
            if( !fp )
            {
                fprintf( stderr , "[WARNING] Could not read x-form from: %s\n" , XForm.value );
                xForm = XForm4x4< Real >::Identity();
            }
            else
            {
                for( int i=0 ; i<4 ; i++ ) for( int j=0 ; j<4 ; j++ ) fscanf( fp , " %f " , &xForm( i , j ) );
                fclose( fp );
            }
        }
        else xForm = XForm4x4< Real >::Identity();
        iXForm = xForm.inverse();

        //DumpOutput2( comments[commentNum++] , "Running Screened Poisson Reconstruction (Version 5.0)\n" , Degree );
        //char str[1024];
        //for( int i=0 ; i<paramNum ; i++ )
        //    if( params[i]->set )
        //    {
        //        params[i]->writeValue( str );
        //        if( strlen( str ) ) DumpOutput2( comments[commentNum++] , "\t--%s %s\n" , params[i]->name , str );
        //        else                DumpOutput2( comments[commentNum++] , "\t--%s\n" , params[i]->name );
        //    }

        double t;
        double tt=Time();
        Real isoValue = 0;

        //Octree< Degree , OutputDensity > tree;
        Octree< 2 , true > tree;
        tree.threads = Threads.value;
        //if( !In.set )
        //{
        //    ShowUsage(argv[0]);
        //    return 0;
        //}
        if( !MaxSolveDepth.set ) MaxSolveDepth.value = Depth.value;
        if( SolverDivide.value<MinDepth.value )
        {
            fprintf( stderr , "[WARNING] %s must be at least as large as %s: %d>=%d\n" , SolverDivide.name , MinDepth.name , SolverDivide.value , MinDepth.value );
            SolverDivide.value = MinDepth.value;
        }
        if( IsoDivide.value<MinDepth.value )
        {
	        fprintf( stderr , "[WARNING] %s must be at least as large as %s: %d>=%d\n" , IsoDivide.name , MinDepth.name , IsoDivide.value , IsoDivide.value );
	        IsoDivide.value = MinDepth.value;
        }
	
        OctNode< TreeNodeData< true > , Real >::SetAllocator( MEMORY_ALLOCATOR_BLOCK_SIZE );

        t=Time();
        int kernelDepth = KernelDepth.set ?  KernelDepth.value : Depth.value-2;

        tree.setBSplineData( Depth.value , BoundaryType.value );
        //if( kernelDepth>Depth.value )
        //{
        //    fprintf( stderr,"[ERROR] %s can't be greater than %s: %d <= %d\n" , KernelDepth.name , Depth.name , KernelDepth.value , Depth.value );
        //    return EXIT_FAILURE;
        //}
        //
        int pointNumber = pPC->GetPointNumber();
        std::vector<float> posList(pointNumber * 3);
        std::vector<float> norList(pointNumber * 3);
        for (int pIndex = 0; pIndex < pointNumber; pIndex++)
        {
            posList.at(3 * pIndex + 0) = pPC->GetPoint(pIndex)->GetPosition()[0];
            posList.at(3 * pIndex + 1) = pPC->GetPoint(pIndex)->GetPosition()[1];
            posList.at(3 * pIndex + 2) = pPC->GetPoint(pIndex)->GetPosition()[2];
            norList.at(3 * pIndex + 0) = pPC->GetPoint(pIndex)->GetNormal()[0];
            norList.at(3 * pIndex + 1) = pPC->GetPoint(pIndex)->GetNormal()[1];
            norList.at(3 * pIndex + 2) = pPC->GetPoint(pIndex)->GetNormal()[2];
        }
        //
        double maxMemoryUsage;
        t=Time() , tree.maxMemoryUsage=0;
        //int pointCount = tree.setTree( In.value , Depth.value , MinDepth.value , kernelDepth , Real(SamplesPerNode.value) , Scale.value , Confidence.set , PointWeight.value , AdaptiveExponent.value , xForm );
        int pointCount = tree.setTree( posList, norList, Depth.value , MinDepth.value , kernelDepth , Real(SamplesPerNode.value) , Scale.value , Confidence.set , PointWeight.value , AdaptiveExponent.value , xForm );
        tree.ClipTree();
        tree.finalize( IsoDivide.value );

        /*DumpOutput2( comments[commentNum++] , "#             Tree set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
        DumpOutput( "Input Points: %d\n" , pointCount );
        DumpOutput( "Leaves/Nodes: %d/%d\n" , tree.tree.leaves() , tree.tree.nodes() );
        DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) );*/

        maxMemoryUsage = tree.maxMemoryUsage;
        t=Time() , tree.maxMemoryUsage=0;
        tree.SetLaplacianConstraints();
        /*DumpOutput2( comments[commentNum++] , "#      Constraints set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
        DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage())/(1<<20) );*/
        maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );

        t=Time() , tree.maxMemoryUsage=0;
        tree.LaplacianMatrixIteration( SolverDivide.value, ShowResidual.set , MinIters.value , SolverAccuracy.value , MaxSolveDepth.value , FixedIters.value );
        /*DumpOutput2( comments[commentNum++] , "# Linear system solved in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
        DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) );*/
        maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );

        CoredFileMeshData< PlyValueVertex< Real > > mesh;

        if( Verbose.set ) tree.maxMemoryUsage=0;
        t=Time();
        isoValue = tree.GetIsoValue();
        //DumpOutput( "Got average in: %f\n" , Time()-t );
        //DumpOutput( "Iso-Value: %e\n" , isoValue );

        if( VoxelGrid.set )
        {
            double t = Time();
            FILE* fp = fopen( VoxelGrid.value , "wb" );
            if( !fp ) fprintf( stderr , "Failed to open voxel file for writing: %s\n" , VoxelGrid.value );
            else
            {
                int res;
                Pointer( Real ) values = tree.GetSolutionGrid( res , isoValue , VoxelDepth.value );
                fwrite( &res , sizeof(int) , 1 , fp );
                if( sizeof(Real)==sizeof(float) ) fwrite( values , sizeof(float) , res*res*res , fp );
                else
                {
                    float *fValues = new float[res*res*res];
                    for( int i=0 ; i<res*res*res ; i++ ) fValues[i] = float( values[i] );
                    fwrite( fValues , sizeof(float) , res*res*res , fp );
                    delete[] fValues;
                }
                fclose( fp );
                DeletePointer( values );
            }
            //DumpOutput( "Got voxel grid in: %f\n" , Time()-t );
        }

        if( Out.set )
        {
            t = Time() , tree.maxMemoryUsage = 0;
            tree.GetMCIsoTriangles( isoValue , IsoDivide.value , &mesh , 0 , 1 , !NonManifold.set , PolygonMesh.set );
            //if( PolygonMesh.set ) DumpOutput2( comments[commentNum++] , "#         Got polygons in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
            //else                  DumpOutput2( comments[commentNum++] , "#        Got triangles in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
            maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );
            //DumpOutput2( comments[commentNum++],"#             Total Solve: %9.1f (s), %9.1f (MB)\n" , Time()-tt , maxMemoryUsage );

            //if( NoComments.set )
            //{
            //    if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII         , NULL , 0 , iXForm );
            //    else            PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , NULL , 0 , iXForm );
            //}
            //else
            //{
            //    if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII         , comments , commentNum , iXForm );
            //    else            PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , comments , commentNum , iXForm );
            //}
            vertices.clear();
            polygons.clear();
            int incorePointNum = int( mesh.inCorePoints.size() );
            int outofcorePointNum = mesh.outOfCorePointCount();
            DebugLog << "incorePointNum: " << incorePointNum << std::endl;
            DebugLog << "outofcorePointNum: " << outofcorePointNum << std::endl;
            mesh.resetIterator();
            for(int pIndex = 0 ; pIndex < incorePointNum ; pIndex++ )
            {
                PlyValueVertex< Real > vertex = iXForm * mesh.inCorePoints[pIndex];
                vertices.push_back(vertex);
                //ply_put_element(ply, (void *) &vertex);
            }
            for(int pIndex = 0; pIndex < outofcorePointNum; pIndex++ )
            {
                PlyValueVertex< Real > vertex;
                mesh.nextOutOfCorePoint( vertex );
                vertex = iXForm * ( vertex );
                vertices.push_back(vertex);
                //ply_put_element(ply, (void *) &vertex);
            }
            int polyNum = mesh.polygonCount();
            DebugLog << "polyNum: " << polyNum << std::endl;
            for (int pIndex = 0; pIndex < polyNum; pIndex++)
            {
                std::vector< CoredVertexIndex > coreIndex;
                mesh.nextPolygon(coreIndex);
                std::vector< int > pureIndex;
                for (int ii = 0; ii < coreIndex.size(); ii++)
                {
                    if (coreIndex.at(ii).inCore)
                    {
                        pureIndex.push_back(coreIndex.at(ii).idx);
                    }
                    else
                    {
                        pureIndex.push_back(coreIndex.at(ii).idx + incorePointNum);
                    }
                }
                if (coreIndex.size() != 3)
                {
                    DebugLog << "Error: coreIndex.size: " << coreIndex.size() << std::endl;
                }
                polygons.push_back(pureIndex);
            }
            //just for test
            /*DebugLog << "Export inter object" << std::endl;
            std::ofstream fout("pc_inter.obj");
            for (int pIndex = 0; pIndex < vertices.size(); pIndex++)
            {
                PlyValueVertex< float > vert = vertices.at(pIndex);
                fout << "v " << vert.point[0] << " " << vert.point[1] << " " << vert.point[2] << std::endl;
            }
            for (int pIndex = 0; pIndex < polygons.size(); pIndex++)
            {
                fout << "f " << polygons.at(pIndex).at(0) + 1 << " " << polygons.at(pIndex).at(1) + 1 << " " << polygons.at(pIndex).at(2) + 1 << std::endl;
            }
            fout.close();*/
        }
    }
    MagicDGP::LightMesh3D* PoissonReconstruction::SurfaceTrimmer(int argc , char* argv[], std::vector< PlyValueVertex< float > >& vertices, std::vector< std::vector< int > >& polygons)
    {
        cmdLineString In( "in" ) , Out( "out" );
        cmdLineInt Smooth( "smooth" , 5 );
        cmdLineFloat Trim( "trim" ) , IslandAreaRatio( "aRatio" , 0.001f );
        cmdLineFloatArray< 2 > ColorRange( "color" );
        cmdLineReadable PolygonMesh( "polygonMesh" );

        cmdLineReadable* params[] =
        {
            &In , &Out , &Trim , &PolygonMesh , &ColorRange , &Smooth , &IslandAreaRatio
        };

        int paramNum = sizeof(params)/sizeof(cmdLineReadable*);
        cmdLineParse( argc , argv, paramNum , params , 0 );

        float min , max;
        //std::vector< PlyValueVertex< float > > vertices;
        //std::vector< std::vector< int > > polygons;

        //int ft , commentNum = paramNum+2;
        //char** comments;
        //bool readFlags[ PlyValueVertex< float >::Components ];
        //PlyReadPolygons( In.value , vertices , polygons , PlyValueVertex< float >::Properties , PlyValueVertex< float >::Components , ft , &comments , &commentNum , readFlags );
        //if( !readFlags[3] ){ fprintf( stderr , "[ERROR] vertices do not have value flag\n" ) ; return EXIT_FAILURE; }

        for( int i=0 ; i<Smooth.value ; i++ ) SmoothValues( vertices , polygons );

        min = max = vertices[0].value;
        for( size_t i=0 ; i<vertices.size() ; i++ ) min = std::min< float >( min , vertices[i].value ) , max = std::max< float >( max , vertices[i].value );
        printf( "Value Range: [%f,%f]\n" , min , max );


        if( Trim.set )
        {
            hash_map< long long , int > vertexTable;
            std::vector< std::vector< int > > ltPolygons , gtPolygons;
            std::vector< bool > ltFlags , gtFlags;

            /*for( int i=0 ; i<paramNum+2 ; i++ ) comments[i+commentNum]=new char[1024];
            sprintf( comments[commentNum++] , "Running Surface Trimmer (V5)" );
            if(              In.set ) sprintf(comments[commentNum++],"\t--%s %s" , In.name , In.value );
            if(             Out.set ) sprintf(comments[commentNum++],"\t--%s %s" , Out.name , Out.value );
            if(            Trim.set ) sprintf(comments[commentNum++],"\t--%s %f" , Trim.name , Trim.value );
            if(          Smooth.set ) sprintf(comments[commentNum++],"\t--%s %d" , Smooth.name , Smooth.value );
            if( IslandAreaRatio.set ) sprintf(comments[commentNum++],"\t--%s %f" , IslandAreaRatio.name , IslandAreaRatio.value );
            if(     PolygonMesh.set ) sprintf(comments[commentNum++],"\t--%s" , PolygonMesh.name );*/

            double t=Time();
            for( size_t i=0 ; i<polygons.size() ; i++ ) SplitPolygon( polygons[i] , vertices , &ltPolygons , &gtPolygons , &ltFlags , &gtFlags , vertexTable , Trim.value );
            if( IslandAreaRatio.value>0 )
            {
                std::vector< std::vector< int > > _ltPolygons , _gtPolygons;
                std::vector< std::vector< int > > ltComponents , gtComponents;
                SetConnectedComponents( ltPolygons , ltComponents );
                SetConnectedComponents( gtPolygons , gtComponents );
                std::vector< double > ltAreas( ltComponents.size() , 0. ) , gtAreas( gtComponents.size() , 0. );
                std::vector< bool > ltComponentFlags( ltComponents.size() , false ) , gtComponentFlags( gtComponents.size() , false );
                double area = 0.;
                for( size_t i=0 ; i<ltComponents.size() ; i++ )
                {
                    for( size_t j=0 ; j<ltComponents[i].size() ; j++ )
                    {
                        ltAreas[i] += PolygonArea( vertices , ltPolygons[ ltComponents[i][j] ] );
                        ltComponentFlags[i] = ( ltComponentFlags[i] || ltFlags[ ltComponents[i][j] ] );
                    }
                    area += ltAreas[i];
                }
                for( size_t i=0 ; i<gtComponents.size() ; i++ )
                {
                    for( size_t j=0 ; j<gtComponents[i].size() ; j++ )
                    {
                        gtAreas[i] += PolygonArea( vertices , gtPolygons[ gtComponents[i][j] ] );
                        gtComponentFlags[i] = ( gtComponentFlags[i] || gtFlags[ gtComponents[i][j] ] );
                    }
                    area += gtAreas[i];
                }
                for( size_t i=0 ; i<ltComponents.size() ; i++ )
                {
                    if( ltAreas[i]<area*IslandAreaRatio.value && ltComponentFlags[i] ) for( size_t j=0 ; j<ltComponents[i].size() ; j++ ) _gtPolygons.push_back( ltPolygons[ ltComponents[i][j] ] );
                    else                                                               for( size_t j=0 ; j<ltComponents[i].size() ; j++ ) _ltPolygons.push_back( ltPolygons[ ltComponents[i][j] ] );
                }
                for( size_t i=0 ; i<gtComponents.size() ; i++ )
                {
                    if( gtAreas[i]<area*IslandAreaRatio.value && gtComponentFlags[i] ) for( size_t j=0 ; j<gtComponents[i].size() ; j++ ) _ltPolygons.push_back( gtPolygons[ gtComponents[i][j] ] );
                    else                                                               for( size_t j=0 ; j<gtComponents[i].size() ; j++ ) _gtPolygons.push_back( gtPolygons[ gtComponents[i][j] ] );
                }
                ltPolygons = _ltPolygons , gtPolygons = _gtPolygons;
            }
            if( !PolygonMesh.set )
            {
                {
                    std::vector< std::vector< int > > polys = ltPolygons;
                    Triangulate( vertices , ltPolygons , polys ) , ltPolygons = polys;
                }
                {
                    std::vector< std::vector< int > > polys = gtPolygons;
                    Triangulate( vertices , gtPolygons , polys ) , gtPolygons = polys;
                }
            }

            RemoveHangingVertices( vertices , gtPolygons );

            MagicDGP::LightMesh3D* pExportMesh = new MagicDGP::LightMesh3D;
            for (int pIndex = 0; pIndex < vertices.size(); pIndex++)
            {
                PlyValueVertex< float > vert = vertices.at(pIndex);
                MagicMath::Vector3 vertPos(vert.point[0], vert.point[1], vert.point[2]);
                pExportMesh->InsertVertex(vertPos);
            }
            for (int pIndex = 0; pIndex < gtPolygons.size(); pIndex++)
            {
                MagicDGP::FaceIndex faceIdx;
                for (int k = 0; k < 3; k++)
                {
                    faceIdx.mIndex[k] = gtPolygons.at(pIndex).at(k);
                }
                pExportMesh->InsertFace(faceIdx);
            }
            pExportMesh->UpdateNormal();
            
            return pExportMesh;
        }
        else
        {
            //if( ColorRange.set ) min = ColorRange.values[0] , max = ColorRange.values[1];
            //std::vector< PlyColorVertex< float > > outVertices;
            //ColorVertices( vertices , outVertices , min , max );
            ////if( Out.set ) PlyWritePolygons( Out.value , outVertices , polygons , PlyColorVertex< float >::Properties , PlyColorVertex< float >::Components , ft , comments , commentNum );
            //if( Out.set ) PlyWritePolygons( Out.value , outVertices , polygons , PlyColorVertex< float >::Properties , PlyColorVertex< float >::Components , 1 , NULL , 0 );
        }

        return NULL;
    }
Exemple #29
0
 static T InOut(T normalizedTime)
 {
     constexpr auto half = T(1) / 2;
     return (time < half) ? half * In(normalizedTime * 2)
         : half + half * Out(normalizedTime * 2 - 1);
 }
Exemple #30
0
bool Settings::Load()
{
	Print("Loading settings.");
	std::ifstream In(FilePath.c_str());
	if(!In.good())
	{
		return false;
	}

	unsigned int SettingsLoaded=0;
	std::string Line;
	while(std::getline(In, Line))
	{
		if(Line.size()>0)
		{
			std::vector<std::string> Parts=Split(Line, ": ");
			if(Parts.size()==4)
			{
				if(Parts[0]=="SelectedColour")
				{
					SettingsLoaded++;
					SelectedColour.a=255;
					SelectedColour.r=atoi(Parts[1].c_str());
					SelectedColour.g=atoi(Parts[2].c_str());
					SelectedColour.b=atoi(Parts[3].c_str());
				}
				else if(Parts[0]=="UnselectedColour")
				{
					SettingsLoaded++;
					UnselectedColour.a=255;
					UnselectedColour.r=atoi(Parts[1].c_str());
					UnselectedColour.g=atoi(Parts[2].c_str());
					UnselectedColour.b=atoi(Parts[3].c_str());
				}
			}
			else if(Parts.size()==2)
			{
				if(Parts[0]=="TileWidth")
				{
					TileWidth=atoi(Parts[1].c_str());
				}
				else if(Parts[0]=="TileHeight")
				{
					TileHeight=atoi(Parts[1].c_str());
				}
			}
		}
	}

	In.close();

	if(SettingsLoaded!=2)
	{
		Print("Failed to load settings.");
		return false;
	}
	else
	{
		Print("Loaded settings succesfully.");
		return true;
	}
}