Beispiel #1
0
bool TextBuffer::save (const QString &filename)
{
  // codec must be set!
  Q_ASSERT (m_textCodec);

  /**
   * construct correct filter device and try to open
   */
  QIODevice *file = KFilterDev::deviceForFile (filename, m_mimeTypeForFilterDev, false);
  if (!file->open (QIODevice::WriteOnly)) {
    delete file;
    return false;
  }

  /**
   * construct stream + disable Unicode headers
   */
  QTextStream stream (file);
  stream.setCodec (QTextCodec::codecForName("UTF-16"));

  // set the correct codec
  stream.setCodec (m_textCodec);

  // generate byte order mark?
  stream.setGenerateByteOrderMark (generateByteOrderMark());

  // our loved eol string ;)
  QString eol = "\n"; //m_doc->config()->eolString ();
  if (endOfLineMode() == eolDos)
    eol = QString ("\r\n");
  else if (endOfLineMode() == eolMac)
    eol = QString ("\r");

  // just dump the lines out ;)
  for (int i = 0; i < m_lines; ++i)
  {
    // get line to save
    Kate::TextLine textline = line (i);

    // strip trailing spaces
    if (m_removeTrailingSpaces)
    {
      int lastChar = textline->lastChar();
      if (lastChar > -1)
      {
        stream << textline->text().left (lastChar+1);
      }
    }
    else // simple, dump the line
      stream << textline->text();

    // append correct end of line string
    if ((i+1) < m_lines)
      stream << eol;
  }

  // flush stream
  stream.flush ();

  // close and delete file
  file->close ();
  delete file;

#ifndef Q_OS_WIN
  // ensure that the file is written to disk
  // we crete new qfile, as the above might be wrapper around compression
  QFile syncFile (filename);
  syncFile.open (QIODevice::ReadOnly);

#ifdef HAVE_FDATASYNC
  fdatasync (syncFile.handle());
#else
  fsync (syncFile.handle());
#endif
#endif

  // did save work?
  bool ok = stream.status() == QTextStream::Ok;

  // remember this revision as last saved if we had success!
  if (ok)
    m_history.setLastSavedRevision ();

  // report CODEC + ERRORS
  kDebug (13020) << "Saved file " << filename << "with codec" << m_textCodec->name()
    << (ok ? "without" : "with") << "errors";

  if (ok)
    markModifiedLinesAsSaved();

  // emit signal on success
  if (ok)
    emit saved (filename);

  // return success or not
  return ok;
}
Beispiel #2
0
void SingleStrokeTemplate::AddLine(const Point2F& from, const Point2F& to, uint sampleCount)
{
	Line2F line(from, to);
	mPath.AddRange(line.SampleWithoutBeginEnd(sampleCount));
}
Beispiel #3
0
void Slicer::slicing(QList<Triangle3D> *model)
{
    int n = 0;
  //  qDebug() << "Start Slicing\n";

    if(drawOutline)
    {
        if(!outsideOutline && !insideOutline)
        {
            QMessageBox::about(0, "Ошибка", "Укажите параметр внешней обводки");
            return;
        }
    }

    double currHeight = 0.0;

    while(currHeight <= height)
    {
        slice_byLine->clear();
        /*
        qDebug() << "Slice at " << currHeight << height << ":\n";
        qDebug() << "size(slice)" << slice->size() * sizeof(Point2D);
        qDebug() << "size(slice_byLine)" << slice_byLine->size() * sizeof(Line2D);
        qDebug() << "size(points)" << points->size() * sizeof(Point2D);
        qDebug() << "size(one_level)" << one_level->size() * sizeof(poid);
        qDebug() << "size(model)" << model->size() * sizeof(Triangle3D);*/
        GCodeOutStream << "Slice at " << currHeight << ":\r\n";

        for(int i = 0; i < model->size(); i++)
        {
            points->clear();

            if(points->isEmpty())
            {
                solveRelation(model->at(i).vertexes_p1, model->at(i).vertexes_p2, currHeight);
                solveRelation(model->at(i).vertexes_p2, model->at(i).vertexes_p3, currHeight);
                solveRelation(model->at(i).vertexes_p3, model->at(i).vertexes_p1, currHeight);

                if(points->size() == 2)
                {
                    Line2D line(points->at(0), points->at(1));
                    *slice_byLine += line;
                }
            }
            else
            {
                qDebug() << "********";
            }
        }

        if(slice_byLine->isEmpty())
        {
            break;
        }

        removeEqual();
        removeRepeated();
        removeReverseRepeated();

        while(!slice_byLine->isEmpty())
        {
        //    qDebug() << "1";
            start = findMin();
            slice->clear();
            buildOrder();

            if(!slice->at(0).isBiggerCorner(slice->at(slice->size() - 1)))
            {
                reverseDirection();
            }
        //    qDebug() << "size slice =" << sizeof(slice);

            if(slice->size() > 1)
            {
                if(drawOutline)
                {
                    if(insideOutline)
                    {
                        GCodeOutStream << "\tOutline shading - inside option:\r\n";
                        edgeShading(lineWidth, true, currHeight, impulse);
                    }
                    else if(outsideOutline)
                    {
                        GCodeOutStream << "\tOutline shading - outside option:\r\n";
                        edgeShading(lineWidth, false, currHeight, impulse);
                    }
                }
            }

            if(slice->size() > 2)
            {
                if(drawInline)
                {
                    GCodeOutStream << "\tInner shading:\r\n";
                    maxY = findMaxY();
                    innerShading(currHeight, impulse, scale);
                }
            }
        }

        currHeight += step_Z;
    }

    GCodeOut.close();
    QMessageBox::about(0, "Прогресс", "Печать прошла успешно!");
}
Beispiel #4
0
void beamtest::readfile1()
{



QString filename = QFileDialog::getOpenFileName ( this,
                                                                                         tr("Import File"),
                                                                                        "",
                                                                                         tr( "All point cloud formats (*.ptx);;"
                                                                                             "XYZ (*.xyz *XYZ);;"
                                                                                       "PTX (*.ptx *.PTX)"));


int count =0;
int debugcount = 0;
char buf[1024];
QFile file(filename);
qint64 lineLength=0;
QStringList linelist;
double x,y,z;
TopoDS_Shape point;

QString filename2 = QFileDialog::getSaveFileName(this, tr("SaveTopology"), " ",tr("csv (*.csv "));

        QFile file2(filename2);
        if (!file2.open(QIODevice::WriteOnly | QIODevice::Text))
    return;





 if (file.open(QFile::ReadOnly)) {
        do {

    lineLength = file.readLine(buf, sizeof(buf));
    if (lineLength != -1) {
        QString line(buf);


                //qDebug() << line;

        linelist = line.split(tr(" "));

        if (linelist.size() == 4)
        {
           count++;
               debugcount++;
               if (debugcount > 100000){ qDebug() << count << ","  << line; debugcount = 0;}

               QString index = linelist.at(0) + "," + linelist.at(1) + "," +
linelist.at(2) +"\n" ;
               file2.write(index.toAscii().data());
               //x = linelist.at(0).toDouble();
               //y = linelist.at(1).toDouble();
               //z = linelist.at(2).toDouble();
               //
               ////QString index = linelist.at(0) + linelist.at(1) + linelist.at(2) ;

               ////double intensity = linelist.at(3).toDouble();

               //point =hsf::AddNewPoint(gp_Pnt(x,y,z));
               //vis(point)





        }

       // if (count > 10000) {file2.close(); break;}




    }
        }while (lineLength != -1);
 }



file2.close();






}
void Link::updatePosition()
{
    QLineF line(mapFromItem(myStartItem, 0, 0), mapFromItem(myEndItem, 0, 0));
    setLine(line);
}
Beispiel #6
0
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RigEquil RigEquil::parseString(const QString& keywordData)
{
    double datumDepth                       = 0.0;
    double datuDepthPressure                = 0.0;
    double waterOilContactDepth             = 0.0;
    double waterOilContactCapillaryPressure = 0.0;
    double gasOilContactDepth               = 0.0;
    double gasOilContactCapillaryPressure   = 0.0;
    bool   liveOilInitConstantRs            = false;
    bool   wetGasInitConstantRv             = false;
    int    initializationTargetAccuracy     = -5;

    QString line(keywordData);
    line.replace("\t", " ");

    QStringList items = line.split(" ");
    if (items.size() > 0)
    {
        datumDepth = items.at(0).toDouble();
    }

    if (items.size() > 1)
    {
        datuDepthPressure = items.at(1).toDouble();
    }
    if (items.size() > 2)
    {
        waterOilContactDepth = items.at(2).toDouble();
    }
    if (items.size() > 3)
    {
        waterOilContactCapillaryPressure = items.at(3).toDouble();
    }
    if (items.size() > 4)
    {
        gasOilContactDepth = items.at(4).toDouble();
    }
    if (items.size() > 5)
    {
        gasOilContactCapillaryPressure = items.at(5).toDouble();
    }
    if (items.size() > 6)
    {
        liveOilInitConstantRs = items.at(6).toInt() > 0 ? true : false;
    }
    if (items.size() > 7)
    {
        wetGasInitConstantRv = items.at(7).toInt() > 0 ? true : false;
    }
    if (items.size() > 8)
    {
        initializationTargetAccuracy = items.at(8).toInt();
    }

    return RigEquil(datumDepth,
                    datuDepthPressure,
                    waterOilContactDepth,
                    waterOilContactCapillaryPressure,
                    gasOilContactDepth,
                    gasOilContactCapillaryPressure,
                    liveOilInitConstantRs,
                    wetGasInitConstantRv,
                    initializationTargetAccuracy);
}
Beispiel #7
0
void beamtest::writebinarytochunkswithcolor()
	{
QFileInfo fileInfo;

QString filename = QFileDialog::getOpenFileName ( this,tr("Import File"),
												 "",tr( "All point cloud formats (*.ptx);;"
												 "XYZ (*.xyz *XYZ);;"
												 "PTX (*.ptx *.PTX)"));



	
		 int chunk = 2000000;
		 //int numfiles = floor((double) shapecount / (double) chunk);
		 int shapecounter=0;
		 int filecounter = 0;

double chunksize= 2000000;
int count =0;
int debugcount = 0;
char buf[1024];
QFile file(filename);
qint64 lineLength=0;
QStringList linelist;

QString filename2 = QFileDialog::getSaveFileName(this, tr("SaveBinary"), " ",tr("dat (*.dat "));
QFile file2(filename2);
 file2.open(QIODevice::WriteOnly);
 QDataStream out(&file2);   // we will serialize the data into the file

 	fileInfo.setFile(filename2);

	QString dirname = fileInfo.absoluteDir().absolutePath();
	filename = fileInfo.fileName();
	QString basename = fileInfo.baseName();
	QString bundlename = fileInfo.bundleName();

 if (file.open(QFile::ReadOnly)) {
        do {

    lineLength = file.readLine(buf, sizeof(buf));
    if (lineLength != -1) {
        QString line(buf);

        linelist = line.split(tr(" "));

        if (linelist.size() == 4)
        {
			
			double x = linelist.at(0).toDouble();
            double y = linelist.at(1).toDouble();
            double z = linelist.at(2).toDouble();
			double intensity= linelist.at(3).toDouble();
			if(x != 0 && y != 0 && z != 0 )
			{
			count++;
			shapecounter++;
				if(shapecounter == chunk)
					{
					
					shapecounter = 0;
					filecounter++;
					QString curfilename = dirname + tr("/") + basename + QString::number(filecounter) + tr(".data");
					file2.close();
					file2.setFileName(curfilename);
					file2.open(QFile::WriteOnly);
					
			
					}


			if (count % 100000 == 0) qDebug() << count;

			out << x << y << z << intensity;
			}

        }

   //if (count > 10000) break;


    }
        }while (lineLength != -1);
 }


if(file2.isOpen()) file2.close();






	}
void ScanlineSeedFill(int Sx,int Sy,int boundarycolor,int fillcolor)
{                           /* 扫描线种子填充 */

    int x_Now,y_Now,x0,y0,Rx,Lx,OldRx,OldLx;
    int RightFlag,LeftFlag; /* 是否到达最右非边界点标志 */
    int i;                  /* 循环控制变量 */
    push(Sx,Sy);           /* 种子点入栈 */

    while(head1!=NULL)         /* 当栈不为空时,做以下事情 */
    {
      pop(&x_Now,&y_Now);        /* 头结点出栈 */

      x0=x_Now+1;
      while(getpixel(x0,y_Now)!=boundarycolor)  /* 找最右边的非边界点! */
          x0++;

      Rx=x0-1;
      OldRx=Rx;                     /* 保存最右点,以便在下一条扫描线时 */
     x0=x_Now-1;

  while(getpixel(x0,y_Now)!=boundarycolor) /*  找最左边的非边界点 */
       x0--;


    Lx=x0+1;
   setcolor(fillcolor);
   setwritemode(OR_PUT);
   line(Lx,y_Now,Rx,y_Now);          /* 填充当前扫描线所在行 */
   setwritemode(XOR_PUT);
   OldLx=Lx;                  /* 保存最左点,以便在下一条扫描线时用 */

   y0=y_Now+1;               /* 扫描线向上扫描 */

   RightFlag=FALSE;

  while(Lx<=Rx &&RightFlag==FALSE)/* 查找上一条线的最右值,并记录为Rx */
  {
   if(getpixel(Rx,y0)==boundarycolor)

       Rx--;
       else
   RightFlag=TRUE;                      /* 如果找到最右值,则置最右标志为真 */
  }



  LeftFlag=FALSE;
  while(Lx<=Rx && LeftFlag==FALSE) /* 查找上一条线的最左值,并记录为Lx */
  {
   if(getpixel(Lx,y0)==boundarycolor)
          Lx++;
   else
          LeftFlag=TRUE;                          /* 如果找到最左值,则置最左标志为真 */
  }

if(RightFlag==TRUE&&LeftFlag==TRUE && getpixel(Rx,y0)!=boundarycolor &&
              (getpixel(Rx,y0)!=fillcolor || getpixel(Lx,y0)!=fillcolor))
   {                                /* 如果找到了最左值和最右值,则执行下面的语句 */
     push(Rx,y0);           /* 将上一条线上的最右点作为种子点入栈 */
     for(i=Lx;i<Rx;i++)      /* 在LX到RX间找每一像素段的最右像素作为种子压入栈 */
        if(getpixel(i,y0)==boundarycolor && getpixel(i-1,y0)!=boundarycolor)
            push(i-1,y0);
    }


  y0=y_Now-1;              /* 扫描线向下扫描 */

  Rx=OldRx;
  Lx=OldLx;

  RightFlag=FALSE;
  while(Lx<=Rx && RightFlag==FALSE)/* 查找下一条线的最右值,并记录为RX */
  {
   if(getpixel(Rx,y0)==boundarycolor)
        Rx--;
   else
        RightFlag=TRUE;             /* 如果找到最右值,则置最右标志为真 */
  }

  LeftFlag=FALSE;
  while( Lx<=Rx &&LeftFlag==FALSE) /* 查找下一条线的最左值,并记录为LX */
  {

    if(getpixel(Lx,y0)==boundarycolor)
         Lx++;
    else
         LeftFlag=TRUE;      /* 如果找到最左值,则置最左标志为真 */
  }

  if(RightFlag==TRUE&&LeftFlag==TRUE && getpixel(Rx,y0)!=boundarycolor &&
       (getpixel(Rx,y0)!=fillcolor || getpixel(Lx,y0)!=fillcolor))
   {                         /* 如果找到了最左值和最右值,则执行下面的语句 */
       push(Rx,y0);            /* 将下一条线上的最右点作为种子点压入栈 */

       for(i=Lx;i<Rx;i++)      /* 在LX到RX间找每一像素段的最右像素作为种子压入栈 */
        if(getpixel(i,y0)==boundarycolor && getpixel(i-1,y0)!=boundarycolor)
            push(i-1,y0);
    }
 }        /* end while(head1!=null) */
}        /* end scanlineseedfill */
Beispiel #9
0
void DisplayScreen()
{	setcolor(15);
	rectangle(156,26,478,452);                                      //for border of play box
	rectangle(158,28,476,450);					//for play box
	DrawBox(488,300,620,450, YELLOWBR, YELLOW, YELLOWDR);		//for next brick bar
	DrawBox(488,28,620,290, YELLOWBR, YELLOW, YELLOWDR);		//for information bar
	DrawBox(10,255,150,450, YELLOWBR, YELLOW, YELLOWDR);		//for instruction bar
	setcolor(PURPLE);
	settextstyle(0,0,1);
	outtextxy(500,310, "Next");
	outtextxy(538,310,"Brick");
	setcolor(PURPLE);
	outtextxy(500,40, "Score");
	setcolor(GREEN);
	rectangle(500,50,608,70);                       //for score box
	setcolor(PURPLE);
	settextstyle(0,0,1);
	outtextxy(500,100, "Level");
	setcolor(GREEN);
	rectangle(500,110,608,130);                     //for level box
	setcolor(PURPLE);
	outtextxy(500,160, "Speed");
	setcolor(GREEN);
	rectangle(500,170,608,190);                     //for speed box
	setcolor(PURPLE);
	outtextxy(500,220, "Lines");
	outtextxy(547,220,"Cleared");
	setcolor(GREEN);
	rectangle(500,230,608,250);			//for line cleared box
	PrintScore();                                   //Display scorecard
	PrintSpeed();                                   //Display speed
	PrintLevel();                                   //Display level
	PrintLinesCleared();                            //Display lines cleared
	setcolor(REDBR);
	settextstyle(10,1,4);
	outtextxy(0,30, "Aguntuk");				//for name
	outtextxy(60,60, "Bricks");
	setcolor(GREEN);
	settextstyle(8,0,2);
	outtextxy(20,255,"KEYS:");
	settextstyle(0,0,1);
	setcolor(PURPLE);
	outtextxy(20,290,"Left");
	setlinestyle(0,0,2);
	line(100,293,103,290);                          //for left arrow's \
	line(100,293,103,296);                          //for left arrow's /
	line(100,293,109,293);				//for left arrow's hyphen
	outtextxy(20,310,"Right");
	line(109,313,106,310);                          //for right arrow's \
	line(100,313,109,313);                          //for right arrow's hyphen
	line(109,313,106,316);                          //for right arrow's /
	outtextxy(20,330,"Rotate");
	outtextxy(100,330,"^");
	line(103,330, 103, 340);			//for up arrow's hyphen
	outtextxy(20,350,"Drop");
	line(103,350, 103, 360);			//for down arrow's hyphen
	line(100,357, 103, 360);			//for down arrow's \
	line(106,357, 103, 360);			//for down arrow's /
	outtextxy(20,370,"Pause");
	outtextxy(100,370,"P");
	outtextxy(20,390,"Sound");
	outtextxy(100,390,"S");
	outtextxy(20,410,"About");
	outtextxy(100,410,"A");
	outtextxy(20,430,"Exit");
	outtextxy(100,430,"Esc");
	setcolor(GREEN);
}
Beispiel #10
0
void c_entity::draw_allegro(c_drawtarget &drawtarget, c_layer &layer_any) {
	auto layer = dynamic_cast<c_layer_allegro &>(layer_any);
	BITMAP *frame = layer.m_frame;
	const auto & gui = * drawtarget.m_gui;
	const int vx = gui.view_x(m_x), vy = gui.view_y(m_y); // position in viewport - because camera position

	if (layer.m_layer_nr == e_layer_nr_gui_bgr) {
		auto selected_object = gui.m_selected_object; // iterator
		_UNUSED(selected_object);

        if (m_selected) { // if I am the selected object
			circle(frame, vx, vy, 50 - 5, makecol(255, 128, 32));
		}

//        if (target_object) { // if I am the target object
//            circle(frame, vx, vy, 50 - 15, makecol(104, 71, 79));
//        }

//        if (source_object) {
//            circle(frame, vx, vy, 50 - 15, makecol(246, 83, 86));
//        }


        if (m_target) { // if I am the target object
			circle(frame, vx, vy, 50 - 15, makecol(104, 71, 79));
		}

        if (m_source) {
            circle(frame, vx, vy, 50 - 15, makecol(246, 83, 86));
        }
//		if (this == source_object.get()) {
//			circle(frame, vx, vy, 50 - 15, makecol(246, 83, 86));
//		}
	}
	if (layer.m_layer_nr == e_layer_nr_gui) {
		//auto selected_object = gui.m_selected_object;
		if (m_selected) { // if I am the selected object
			//_dbg3("draw select");
			const int r1 = 50 - 8, r2 = 50;
			const auto col1 = makecol(192, 192, 192), col2 = makecol(255, 128, 32);
			int nr = 0;
			for (double angle = 0; angle < M_PI * 2; angle += (M_PI * 2) / 16) {
				++nr;
				line(frame,
				     vx + sin(angle) * r1,
				     vy + cos(angle) * r1, vx + sin(angle) * r2, vy + cos(angle) * r2, (nr % 2 ? col1 : col2));
			}
		}
	}
	
	int color = makecol(255,128,0); // color1
	if (layer.m_layer_nr == e_layer_nr_object) {
		line(frame, vx - 2, vy - 2, vx + 2, vy + 2, color);
		line(frame, vx - 2, vy + 2, vx + 2, vy - 2, color);
		circle(frame, vx, vy, 10, color);
	}
    if (layer.m_layer_nr == e_layer_nr_object_extra) {
		textout_ex(frame, font, m_name.c_str(), vx - 20, vy - 35, color, -1);

	}
}
main()
{
 int X,Y,m_state,y,a,b,i,j;


  Initgr();                        /* BGI初始化 */

  setcolor(WHITE);

 setwritemode(XOR_PUT);      /* 设定输入模式为异或模式 */
 MouseInit(0,X_max,0,Y_max);  /* 初始化鼠标 */
 a=X_max;b=Y_max;
 m_state=0;                   /* 初始化鼠标状态为移动状态 */
 DrawCursor(a,b);
 while(m_state!=2)             /* 如果没有点击右键 */
 {
   MouseState(&X,&Y,&m_state);     /* 获取鼠标当前状态与坐标值 */
   DrawCursor(a,b);                /* 通过异或输入模式删除之前的鼠标指针 */
   if(m_state==1)                   /* 如果鼠标左键点击 */
    {
       LineDrawFlag=TRUE;            /* 将跟随鼠标画线标志置为真 */
       if(0==PointNum)               /* 如果是第一次点击左键 */
         {
          x_Origin=a; y_Origin=b;
          x_Old=a;    y_Old=b;
          x_New=a;    y_New=b;
         }
         else                         /* 如果不是第一次点击鼠标左键 */
         {
          x_Old=x_New;
          y_Old=y_New;
          x_New=a;
          y_New=b;
          }


         PointNum++;               /* 记录鼠标左键点击次数,以便确定是否要跟随鼠标画线 */

         if((x_Origin-x_New) > -10 && (x_Origin-x_New) < 10 && (y_Origin-y_New) > -10
          && (y_Origin-y_New) < 10 &&  ((x_Origin-x_New)!=0 || (y_Origin-y_New)!=0))
           {                      /* 如果线画到离初始点足够近的地方 */

             LineDrawFlag=FALSE;     /* 将跟随鼠标画线标志置为假 */
             PointNum=0;              /* 鼠标点击次数清零 */
             x_New=x_Origin; y_New=y_Origin;    /* 将初始点的坐标值赋给当前点 */
           }

           setwritemode(OR_PUT);
           line(x_Old,y_Old,x_New,y_New);       /*  从前一点到当前点画线 */
           setwritemode(XOR_PUT);
    }

   DrawCursor(X,Y);   /* 在当前位置画鼠标指针 */
   a=X;
   b=Y;
}

  DrawCursor(X,Y);
  ScanlineSeedFill(X,Y,WHITE,12);

 getch();
closegraph();
}
Beispiel #12
0
inline void Console::handle_input (HANDLE in, ConsoleScreenBuffer & buffer) {

    DWORD num;
    INPUT_RECORD ir;
    if (!ReadConsoleInputW(
                in,
                &ir,
                1,
                &num
            )) Raise();

    //	Nothing was read
    if (num==0) return;

    //	If a resize event was read,
    //	handle and return
    if (ir.EventType==WINDOW_BUFFER_SIZE_EVENT) {

        buffer.Resize();

        return;

    }

    //	We're only concerned with key
    //	press events besides resize
    //	events
    if (!(
                (ir.EventType==KEY_EVENT) &&
                (ir.Event.KeyEvent.bKeyDown)
            )) return;

    //	Loop for the number of times
    //	this key press was repeated
    for (WORD i=0; i<ir.Event.KeyEvent.wRepeatCount; ++i) {

        //	Switch depending on the key
        //	pressed
        switch (ir.Event.KeyEvent.wVirtualKeyCode) {

        case VK_RETURN: {

            //	Enter was pressed

            //	Get line from the screen
            String line(buffer.Return());
            //	Dispatch callback (if applicable)
            if (callback) callback(std::move(line));

        }
        break;

        case VK_HOME:

            //	Home was pressed

            //	Fire appropriate event
            //	depending on whether CTRL
            //	is pressed or not
            if (ctrl_pressed(ir)) buffer.CtrlHome();
            else buffer.Home();

            break;

        case VK_END:

            //	End was pressed

            //	Fire appropriate event
            //	depending on whether
            //	CTRL is pressed or not
            if (ctrl_pressed(ir)) buffer.CtrlEnd();
            else buffer.End();

            break;

        case VK_RIGHT:

            //	Right was pressed

            buffer.Right();

            break;

        case VK_LEFT:

            //	Left was pressed

            buffer.Left();

            break;

        case VK_DELETE:

            //	Delete was pressed

            buffer.Delete();

            break;

        case VK_BACK:

            //	Backspace was pressed

            buffer.Backspace();

            break;

        case VK_PRIOR:

            //	Page Up was pressed

            buffer.PageUp();

            break;

        case VK_NEXT:

            //	Page Down was pressed

            buffer.PageDown();

            break;

        default:

            if (ir.Event.KeyEvent.uChar.UnicodeChar!=0) buffer.Add(
                    static_cast<CodePoint>(
                        ir.Event.KeyEvent.uChar.UnicodeChar
                    )
                );

            break;

        }

    }

}
Beispiel #13
0
int speed()
{
int a,dd,xxx=99+(50*4),ii,count;
char *stt;
	setpos(0,0);
	viewport();
	count=zzz;
	xxx=99+(count*4);
	settextstyle(3,0,3);
	setcolor(14);
	outtextxy(100,100,"Speed Level");
	status("  Increment : [->]           Decrement : [<-]         Accept : [Enter key]");
	rectangle(99,249,500,276);
	setfillstyle(SOLID_FILL,4);
	bar(100,250,xxx,275);
	goto df;
   cd: while(1)
	{
		if(kbhit())
		{
		      dd=getch();
		      switch(dd)
		      {
			case 77:
				if(count==100)
				     continue;
				count++;
				for(ii=0;ii<=3;ii++)
				{
					setcolor(4);
					xxx++;
					line(xxx,250,xxx,275);
				}
				break;
			case 75:
				if(count==0)
					continue;
					count--;
				for(ii=0;ii<=3;ii++)
				{
					setcolor(0);
					line(xxx,250,xxx,275);
					xxx--;
				}
				break;
			case 13:
				zzz=count;
				bb=(count/10)+1;
				a=450-(count*4);
				return a;
			}
		    df:	settextstyle(3,0,3);
			 itoa(count,stt,10);

			setfillstyle(SOLID_FILL,0);
			bar(200,180,300,240);
			setcolor(2);
			outtextxy(240,200,stt);
			goto cd;
		}

	}
       //	getch();
}
Beispiel #14
0
int Manual(int argc, unsigned char **argv)
{
  /* Serial port initialization */
  fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
  if (fd == -1) {
    perror("open_port: Unable to open /dev/ttyS0 - ");
    return 1;
  } else {
    fcntl(fd, F_SETFL, 0);
  }
  getbaud(fd);
  initport(fd);


  int PVi, k;
	K= uatof(Gain);
  /* Things will be drawn more quickly if you always acquire the screen before
     trying to draw onto it. */
  acquire_screen();
  
  Graphics();	/* Call to graphics from a different function to avoid messy code */
  
  RLE_SPRITE *rle;
 
//            sCmd[0]= 'H';
//            writeport(fd, sCmd);

  PVi= 0;  k= 100;  M=0;
  while (!key[KEY_ESC])	/* Only pressing ESC can Exit */
    {
	char ValveState;
//	if(ValveState=='O')

/*	if(5!=6)
	{
            sCmd[0]= 'H';
            writeport(fd, sCmd);
	}
	if(ValveState=='C')
	{
            sCmd[0]= 'C';
            writeport(fd, sCmd);
	} */

      /* This line reads data from the interfase which is
	 the process variable(measured variable) of the system 
	 readport(fd,sResult);  */
      sCmd[0]= 'H';
      if(!writeport(fd, sCmd))
	return 1;
      usleep(500);
      if(!read(fd,sResult,254))
	return 1;
      Value1= (int)sResult[0];
      usleep(500); 
      sCmd[0]= 'L';
      if(!writeport(fd, sCmd))
	return 1;
      usleep(500);
      if(!read(fd,sResult,254))
	return 1;
      Value2= (int)sResult[0];
      usleep(500);
      
      Value1=  Value1 << 8;
      Value1+= Value2;
      PV= PVi=Value1;

//      PV=900;
     
      if(PV<=40)
	{
	  PV= 51;
	  system("festival --tts messages/Disconnected&");
	  blit(Disconnected, screen, 0, 0, 70, 290, 887, 52);   
	} 
      
      if(PV<=204)		// 200 is ~1/5th of 1024
        PVi= 204;
	


      M++;
      /* Check if user needs some help */
      if(key[KEY_F1])
	Help();

      k++;
      i= 897;
      
      Captura = create_sub_bitmap(screen, 72, 350, 898, 368);
      rle = get_rle_sprite(Captura);
      destroy_bitmap(Captura);
      draw_rle_sprite(screen, rle, 71, 350);
      destroy_rle_sprite(rle);

      /* This line reads data from the interfase which is
	 the process variable(measured variable) of the system */
//	  readport(fd,sResult);
//	  PVi= (int) *sResult;
//	  PV= PVi;      
	  PVi= PV;
/*
      if(PVi<=40)
	{
	  PV= 51;
	  system("festival --tts Messages/Disconnected&");
	  blit(Disconnected, screen, 0, 0, 70, 290, 887, 52);   
	}
   */   
      if(PV<=48)
        PVi= 51;
      
	PV= (PV-240)*0.3593;
//      PV= 1.794117647*(PVi-51);
      SP= PV;
      
      if(key[KEY_RIGHT])
	{
          //fd = close("/dev/parport0");	
	  Simulator();
        }
      if(key[KEY_PGUP])
	OP= (OP+46);
      
      if(key[KEY_PGDN])
	OP= (OP-46);
      
	if(key[KEY_UP])
	OP= OP+3.66;

      if(key[KEY_DOWN])
	{
	  //if(SP>=1)
	    OP= OP-3.66;
	}
      
      if(key[KEY_PRTSCR])
	{
          Captura = create_sub_bitmap(screen, 0, 0, 1024, 768);
          save_bitmap("images/User/Captura.pcx", Captura, pal);
          destroy_bitmap(Captura);
        }
      
      Timer++;
      
      if(OP<=0)
	OP= 0;
      
      K= uatof(Gain);
            float K, BIAS, Ti,Td;   K=-2; BIAS=184; Ti=1;  Td=50;
            K=(K/368)*100;
	 //OP= ((((PV/368)-(SP/368))*100)*K)+OP;      
//	OP= ((OP/368)*K);
      
//      if (PV>=40)
//	{
	  textprintf_ex(screen, font, 230, 297, BLACK, WHITE, "%3.1f", (PV/368)*100);	// Medición  76.46%   2.7826   0.3593
	  textprintf_ex(screen, font, 450, 297, BLACK, WHITE, "%3.1f", (SP/368)*100);	// SP
	  textprintf_ex(screen, font, 710, 297, BLACK, WHITE, "%3.1f", (OP/368)*100);	// Controlador
//	}
      
      if(k>=100)
	{
 	  k= 0;
	  vline(screen, 967, 351, 717, GRAY);
          blit(Clean, screen, 0, 0, 968, 350, 2, 368);
	}
      
      int Recorder;
      Recorder++;
      if(Recorder>=900)
	{
 	  Recorder= 0;
	  Captura = create_sub_bitmap(screen, 258, 350, 715, 368);
	}
      
      Captura = create_sub_bitmap(screen, 248, 350, 705, 368);
      
      
      if(PV>=362) PV= 365;
      if(OP>=367) OP= 365;
      
      if(PV<=0) PV= 0;
      if(OP<=0)
	 OP= 1;
/*
      sCmd[0]= 'M';
      if(!writeport(fd, sCmd))
	return 1;
      usleep(500);
      //OPi= fixtoi(itofix((OP*0.69234783)/255*100));
      OPi= fixtoi(itofix(((OP/368)*100)*1.55));
      sCmd[0]= (unsigned char)OPi+50;
//      sCmd[0]= sCmd[0]+0.00;

      writeport(fd, sCmd);
*/
//     textprintf_ex(screen, font, 30, 297, BLACK, WHITE, "%i - %s - %3.1f", PVi, sResult, PV);	// Medición      

      /* Draw the behaviour of the PV, SP and OP over time */
      line(screen, 71+i, 717-PV, 71+i, 717-PVj, RED);	
      PVj= PV;    /* Flag for line y2 as a precedent state */
      line(screen, 71+i, 717-OP, 71+i, 717-OPj, BLUE);	
      OPj= OP;    /* Flag for line y2 as a precedent state */
      
      fprintf(outfile,"%i\t %f\t %f\t %f\t %f\t \n", M, ((PV/368)*100), ((SP/368)*100), ((OP/368)*100), SP);
      //fclose(outfile);
      rest(Delay);
    }
  int ScreenWide;
  RLE_SPRITE *rle0, *rle1;
  BITMAP *Screen3;

  Screen3 = load_bitmap("images/Close/Base.pcx", pal);
  system("mp3blaster /home/mentesuprema/Residencia/sounds/swing2.wav &");
  rest(5);

  rle0= get_rle_sprite(Screen2);
  rle1= get_rle_sprite(Screen3);
  
  for(ScreenWide=0;ScreenWide<=768;ScreenWide=ScreenWide+5)
    {
      draw_rle_sprite(screen, rle0, 0, 768);
      draw_rle_sprite(screen, rle1, 0, -768+ScreenWide);
    }

  destroy_rle_sprite(rle0);  
  destroy_rle_sprite(rle1);    
  destroy_bitmap(Screen2);
  destroy_bitmap(Screen3);
  destroy_bitmap(Clean);
  destroy_bitmap(Disconnected);
  release_screen();
  Close();
  exit(0);
} 
Beispiel #15
0
// ---
// drawGrid() - draws the overlay grid lines
// ---
void MapItem::drawGrid(QPainter* painter)
{
   // smaller font for easy viewing
   QFont font(painter->font());
   font.setPointSize(10);
   painter->setFont(font);

   QFontMetrics fm = painter->fontMetrics();
   // setup our pen
   // the color of our pen will be the complement of the strength of our intensity
   QPen pen(Qt::white, 2.0f);
   painter->setPen(pen);

   if (heading > 0 && !northUp) {
       setRotation(heading);
   }

   // get the nearest starting lat and lon lines to draw
   const int centerLat = oe::base::nint(refLat);
   const int centerLon = oe::base::nint(refLon);

   // calculate the number of latitude lines
   const int numLinesLat = (range / 60.0) + 1;

   // calculate EW range
   double rangeEW(1.0);
   if (northUp) {
      rangeEW = (bRect.width() * pixWERes);
   } else {
      rangeEW = (bRect.width() * pixWERes / cosineLatReference);
   }
   const int numLinesLon = (rangeEW / 60.0) + 1;

   int startLat = centerLat - (numLinesLat / 2);
   int endLat = centerLat + (numLinesLat / 2);
   // top side (or bottom, depending on hemisphere)
   double py = 0.0;
   double px = 0.0;
   const int wid = bRect.width();
   const int hei = bRect.height();
   if (endLat >= 90)     { endLat = 90;     }
   if (startLat <= -90)  { startLat = -90;  }

   QVector<QLine> lines;

   for (int i = startLat; i <= endLat; i++) {
      llToPixels(i, 0, py, px);
      QLine line(-wid/2, py, wid, py);
      //painter->drawLine(-wid/2, py, wid, py);
      lines << line;
   }

   painter->drawLines(lines);
   lines.clear();

   const int startLon = centerLon - (numLinesLon / 2);
   const int endLon = centerLon + (numLinesLon / 2);
   // top side (or bottom, depending on hemisphere)
   for (int i = startLon; i <= endLon; i++) {
      llToPixels(0, i, py, px);
      QLine line(px, -hei / 2, px, hei / 2);
      //painter->drawLine(px, -hei / 2, px, hei / 2);
      lines << line;
   }

   painter->drawLines(lines);
   lines.clear();

   // now for the text
   QString string;
   double adjustHeight = fm.height();
   std::ostringstream stream;
   for (int i = startLat; i <= endLat; i++) {
      string.clear();
      stream.str("");
      int aI = abs(i);
      llToPixels(i, 0, py, px);

      if (i > 0)          { stream << "N" << aI;  }
      else if (i < 0)     { stream << "S" << aI;  }
      else                { stream << aI;         }

      string = stream.str().c_str();
      // Lee - have to use the unicode code for a degree symbol
      string.append(0x00B0);
      const double adjustWidth = fm.width(string);
      painter->drawText(-(wid/2) + 5, py - adjustHeight, adjustWidth, adjustHeight, 0, string);
   }

   for (int i = startLon; i <= endLon; i++) {
      string.clear();
      stream.str("");
      llToPixels(0, i, py, px);
      int aI = std::abs(i);

      if (i > 180)         { aI = (180 - i) + 180; }
      else if (i < -180)   { aI = (180 + i) + 180; }

      if (i != 0 && i != 180 && i != -180) {
         if (i > 0 || i < -180)       { stream << "E" << aI;  }
         else if (i < 0 || i > 180)   { stream << "W" << aI;  }
         else                         { stream << aI;         }
      }
      string = stream.str().c_str();
      // Lee - have to use the unicode code for a degree symbol
      string.append(0x00B0);
      const double adjustWidth = fm.width(string);
      painter->drawText(px + 5, -hei/2, adjustWidth, adjustHeight, 0, string);
   }
}
Beispiel #16
0
	bool INIFile::read()
	{
		// destroy all datastructures - we make a new start
		// we only keep the filename...
		clear();

		// If the filename is empty, there's no point in opening it...
		if (filename_ == "")
		{
			return false;
		}

		// try to open the file
		ifstream infile(filename_.c_str());

		// if we couldn't open the file: abort
		if (!infile)
		{
			return false;
		}

		list<Section>::iterator	section_it(sections_.begin());

		// read all lines from the file
		std::vector<char> buffer(MAX_LINE_LENGTH);
		while (infile.getline(&(buffer[0]), MAX_LINE_LENGTH))
		{
			// remove leading blanks
			String line(&(buffer[0]));
			line.trimLeft();

			// check for comment lines or empty line
			if (line.empty()     || (line[0] == '!') ||
			   (line[0] == ';')  || (line[0] == '#'))
			{
				section_it->lines_.push_back(&(buffer[0]));
				continue;
			}

			// check for start of section
			if (line[0] == '[')
			{	
				if (!appendSection(line))
				{
					return false;
				}

				section_it++;
				
				continue;
			}
			
			// this is neither a comment line nor a section start
			// line still has to be added
			if (!appendLine("", line))
			{
				return false;
			}
		}
		
		// close the file
		infile.close();

		// done.
		valid_ = true;
		return true;
	}
Beispiel #17
0
// Hexadecimal view of an object added to the logfile
bool    
LogAnalysis::AnalysisHex(const char* p_function,CString p_name,void* p_buffer,unsigned long p_length,unsigned p_linelength /*=16*/)
{
  // Only dump in the logfile, not to the MS-Windows event log
  if(!m_file || m_logLevel < HLL_TRACEDUMP)
  {
    return false;
  }

  // Check parameters
  if(p_linelength > LOGWRITE_MAXHEXCHARS)
  {
    p_linelength = LOGWRITE_MAXHEXCHARS;
  }
  if(p_length > LOGWRITE_MAXHEXDUMP)
  {
    p_length = LOGWRITE_MAXHEXDUMP;
  }

  // Multi threaded protection
  AutoCritSec lock(&m_lock);

  // Name of the object
  AnalysisLog(p_function,LogType::LOG_TRACE,true,"Hexadecimal view of: %s. Length: %d",p_name.GetString(),p_length);

  unsigned long  pos    = 0;
  unsigned char* buffer = static_cast<unsigned char*>(p_buffer);

  while(pos < p_length)
  {
    unsigned len = 0;
    CString hexadLine;
    CString asciiLine;

    // Format one hexadecimal view line
    while(pos < p_length && len < p_linelength)
    {
      // One byte at the time
      hexadLine.AppendFormat("%2.2X ",*buffer);
      if(*buffer)
      {
        asciiLine += *buffer;
      }
      // Next byte in the buffer
      ++buffer;
      ++pos;
      ++len;
    }

    // In case of an incomplete last line
    while(len++ < p_linelength)
    {
      hexadLine += "   ";
    }
    asciiLine.Replace("\r","#");
    asciiLine.Replace("\n","#");

    // Add to the list buffer
    CString line(hexadLine + asciiLine + "\n");
    m_list.push_back(line);
  }
  // Large object now written to the buffer. Force write it
  ForceFlush();

  return true;
}
void line_dan()
{
   int x1=0,y1=0,x2=0,y2=0;
    setbkcolor(0);
    //randomize();

/////////////////////////////////////////////////////////////////////////////
/////////                                                          //////////
///////// LOOP TO SLIDE LINES OVER  __ X-AXES __ ......            //////////
/////////                                                          //////////
/////////////////////////////////////////////////////////////////////////////

for(int i=0; i<2; ++i)
{
 setcolor(BLACK);
 x1=0,y1=0,x2=0,y2=0;

 for(; x1<=640; ++x1,--x2)
 {
   int xmax, ymax;

   randomize();
   if(i==0) if(x1==0) setcolor(GREEN);
   xmax = getmaxx();
   ymax = getmaxy();

   /* draw a diagonal line */
   line(0+x1, 0+y1, xmax+x2, ymax+y2);
   delay(3);
 }

/////////////////////////////////////////////////////////////////////////////
//////// Loop to slide on x-axes ends                          //////////////
/////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////////////
/////////                                                          //////////
/////////    LOOP TO THE LINES OVER  Y- AXES ............          //////////
/////////                                                          //////////
/////////////////////////////////////////////////////////////////////////////

 for(; y1<=480; ++y1,--y2)
 {
   int xmax, ymax;

   randomize();
   if(i==0) if(y1==0) setcolor(CYAN);
   xmax = getmaxx();
   ymax = getmaxy();

   line(0+x1, 0+y1, xmax+x2, ymax+y2);

   delay(3);
 }
/////////////////////////////////////////////////////////////////////////////
//////// Loop to slide on y-axes ends                          //////////////
/////////////////////////////////////////////////////////////////////////////
}
delay(250);
cleardevice();
}
Beispiel #19
0
int main(int argc, char* argv[])
{
    int port;
    int expiration;
    char* targetURI;
    char* eventType;
    char* contentType;
    char* realm;
    char* user;
    char* password;

   // Initialize logging.
   OsSysLog::initialize(0, "test");
   OsSysLog::setOutputFile(0, "log");
   OsSysLog::setLoggingPriority(PRI_DEBUG);
   OsSysLog::setLoggingPriorityForFacility(FAC_SIP_INCOMING_PARSED, PRI_ERR);

   if (!parseArgs(argc, argv, &port, &expiration,
                  &targetURI, &eventType, &contentType,
                  &realm, &user, &password))
   {
       usage(argv[0]);
       exit(1);
   }

   // The domain name to call myself, obtained from the gethostname()
   // system call.
   char buffer[100];
   memset(buffer, 0, sizeof (buffer));
   // Do not allow gethostname to write over the last NUL in buffer[].
   gethostname(buffer, (sizeof (buffer)) - 1);
   UtlString myDomainName(buffer, strlen(buffer));
   // Use "example.com" if gethostname() failed.
   if (myDomainName.isNull())
   {
      myDomainName = "example.com";
   }

   UtlString fromString = "sip:dialogwatch@" + myDomainName;
   Url fromUri(fromString, TRUE);

   // Create the SIP Subscribe Client

   SipLineMgr lineMgr;

   // Add credentials if they were specified.
   if (realm)
   {
      UtlString id;
      id += "sip:";
      id += user;
      id += "@";
      id += realm;
      Url identity(id, TRUE);

      SipLine line( fromUri  // user entered url
                   ,identity // identity url
                   ,user     // user
                   ,TRUE     // visible
                   ,SipLine::LINE_STATE_PROVISIONED
                   ,TRUE     // auto enable
                   ,FALSE    // use call handling
         );

      lineMgr.addLine(line);

      UtlString cred_input;
      UtlString cred_digest;

      cred_input.append(user);
      cred_input.append(":");
      cred_input.append(realm);
      cred_input.append(":");
      cred_input.append(password);

      NetMd5Codec::encode(cred_input.data(), cred_digest);

      fprintf(stderr,
              "Adding identity '%s': user='******' realm='%s' password='******' H(A1)='%s'\n",
              identity.toString().data(), user, realm, password, cred_digest.data()
         );

      assert(lineMgr.addCredentialForLine(identity, realm, user, cred_digest,
                                          HTTP_DIGEST_AUTHENTICATION));
   }

   SipUserAgent* pSipUserAgent =
      new SipUserAgent(port, port, PORT_NONE,
                       NULL,
                       NULL,
                       NULL,
                       NULL,
                       NULL,
                       NULL,
                       NULL,
                       NULL,
                       NULL,
                       NULL,
                       &lineMgr);
   // Add the 'eventlist' extension, so dialogwatch can subscribe to
   // event lists.
   pSipUserAgent->allowExtension("eventlist");
   if (!pSipUserAgent->isOk())
   {
       fprintf(stderr, "Unable to bind to port %d\n", port);
       exit(1);
   }

   SipDialogMgr dialogManager;

   SipRefreshManager refreshMgr(*pSipUserAgent, dialogManager);
   refreshMgr.start();

   SipSubscribeClient sipSubscribeClient(*pSipUserAgent, dialogManager,
                                         refreshMgr);
   sipSubscribeClient.start();

   // Construct a name-addr from targetURI, in case it contains parameters.
   UtlString toUri;
   toUri = "<";
   toUri += targetURI;
   toUri += ">";
   UtlString earlyDialogHandle;

   fprintf(stderr,
           "resourceId '%s' fromString '%s' toUri '%s' event '%s' content-type '%s' port=%d expiration=%d\n",
           targetURI, fromString.data(), toUri.data(), eventType, contentType,
           port, expiration);

   UtlBoolean status =
      sipSubscribeClient.addSubscription(targetURI,
                                         eventType,
                                         contentType,
                                         fromString.data(),
                                         toUri.data(),
                                         NULL,
                                         expiration,
                                         (void *) NULL,
                                         subscriptionStateCallback,
                                         notifyEventCallback,
                                         earlyDialogHandle);

   if (!status)
   {
      fprintf(stderr, "Subscription attempt failed.\n");
      exit(1);
   }
   else
   {
      fprintf(stderr, "Subscription attempt succeeded.  Handle: '%s'\n",
              earlyDialogHandle.data());
   }

   while (1)
   {
      sleep(1000);
   }
}
bool cOutResult::outFile_DI(void)
{
    bool fOk = false;
    long int pos = 0;

    string fn_index = tmpDir +"/"+DI_idx;
    string fn_tmp = tmpDir +"/"+DI_tmp;
    string fn_DI;
    string fn_DI_dupl;

    try
    {
        ifstream inFileDItmp((fn_tmp).c_str());
        ifstream inFile_index(fn_index.c_str(), ios::in | ios::binary);
        if (!inFileDItmp.is_open())
            return false;
        ofstream outFile_DI;
        ofstream outFile_DI_dupl;
        {
            //формирование имени
            ostringstream sout("");
            sout  <<Dir <<"/" <<fileNamePrefix  <<DI <<"-" <<(countFiles) <<".txt";
            fn_DI = sout.str();
            outFile_DI.open(fn_DI.c_str(), ios::out | ios::app);
        }
        {
            //формирование имени
            ostringstream sout("");
            sout  <<Dir <<"/" <<fileNamePrefix  <<DI_dupl <<"-" <<(countFiles) <<".txt";
            fn_DI_dupl = sout.str();
            outFile_DI_dupl.open(fn_DI_dupl.c_str(), ios::out | ios::app);
        }


        string line("");
        while ( inFileDItmp.good() )
        {
            inFileDItmp >>pos;
            line="";
            getline(inFileDItmp, line, '\n');
            line = ltrim(line);

            if(line.empty())
                continue; // пустая строка

            cDIindex dii;

            //найти нужный файл, позицию и прочесть
            if(pos == -1)
            {
                outFile_DI  <<line <<'\t'
                            <<0 <<'\t'
                            <<0 <<'\t'
                            <<0 <<endl;
            }
            else
            {
                inFile_index.seekg(pos, ios::beg);
                inFile_index.read(reinterpret_cast<char*>(&dii), sizeof(class cDIindex) );
                outFile_DI  <<line <<'\t'
                            <<dii.duplGenomeDel <<'\t'
                            <<dii.duplGenomeInv <<'\t'
                            <<dii.duplGenomeDelInv <<endl;
                outFile_DI_dupl <<line <<'\t'
                                <<dii.duplGenomeDel <<'\t'
                                <<dii.duplGenomeInv <<'\t'
                                <<dii.duplGenomeDelInv <<endl;

            }
            recCout++;
        }
        outFile_DI.close();
        outFile_DI_dupl.close();
        inFileDItmp.close();
        inFile_index.close();
        remove_tmp_files(); //убить временные
    }
    catch(...)
    {
        cout <<endl <<"ERROR add to '" <<fn_DI <<"'!!!" <<endl;
        fOk = false;
    }
    return fOk;

}
Beispiel #21
0
void beamtest::writebinary()
	{

QString filename = QFileDialog::getOpenFileName ( this,tr("Import File"),
												 "",tr( "All point cloud formats (*.ptx);;"
												 "XYZ (*.xyz *XYZ);;"
												 "PTX (*.ptx *.PTX)"));

double chunksize= 5000000;
int count =0;
int debugcount = 0;
char buf[1024];
QFile file(filename);
qint64 lineLength=0;
QStringList linelist;

QString filename2 = QFileDialog::getSaveFileName(this, tr("SaveBinary"), " ",tr("dat (*.dat "));
QFile file2(filename2);
 file2.open(QIODevice::WriteOnly);
 QDataStream out(&file2);   // we will serialize the data into the file


 if (file.open(QFile::ReadOnly)) {
        do {

    lineLength = file.readLine(buf, sizeof(buf));
    if (lineLength != -1) {
        QString line(buf);

        linelist = line.split(tr(" "));

        if (linelist.size() == 4)
        {
			
			double x = linelist.at(0).toDouble();
            double y = linelist.at(1).toDouble();
            double z = linelist.at(2).toDouble();
			if(x != 0 && y != 0 && z != 0 )
			{
			count++;

			if (count % 100000 == 0) qDebug() << count;

			out << x << y << z;
			}

        }

   //if (count > 10000) break;


    }
        }while (lineLength != -1);
 }



file2.close();






	}
void VoronoiDiagramGenerator::clip_line(struct Edge *e)
{
	struct Site *s1, *s2;
	double x1=0,x2=0,y1=0,y2=0/*, temp = 0;*/;

	x1 = e->reg[0]->coord.x;
	x2 = e->reg[1]->coord.x;
	y1 = e->reg[0]->coord.y;
	y2 = e->reg[1]->coord.y;

	//if the distance between the two points this line was created from is less than 
	//the square root of 2, then ignore it
	if(sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))) < minDistanceBetweenSites)
	{
		return;
	}
	pxmin = borderMinX;
	pxmax = borderMaxX;
	pymin = borderMinY;
	pymax = borderMaxY;

	if(e -> a == 1.0 && e ->b >= 0.0)
	{	
		s1 = e -> ep[1];
		s2 = e -> ep[0];
	}
	else 
	{
		s1 = e -> ep[0];
		s2 = e -> ep[1];
	};
	
	if(e -> a == 1.0)
	{
		y1 = pymin;
		if (s1!=(struct Site *)NULL && s1->coord.y > pymin)
		{
			y1 = s1->coord.y;
		}
		if(y1>pymax) 
		{
		//	printf("\nClipped (1) y1 = %f to %f",y1,pymax);
			y1 = pymax;
			//return;
		}
		x1 = e -> c - e -> b * y1;
		y2 = pymax;
		if (s2!=(struct Site *)NULL && s2->coord.y < pymax) 
			y2 = s2->coord.y;

		if(y2<pymin) 
		{
			//printf("\nClipped (2) y2 = %f to %f",y2,pymin);
			y2 = pymin;
			//return;
		}
		x2 = (e->c) - (e->b) * y2;
		if (((x1> pxmax) & (x2>pxmax)) | ((x1<pxmin)&(x2<pxmin))) 
		{
			//printf("\nClipLine jumping out(3), x1 = %f, pxmin = %f, pxmax = %f",x1,pxmin,pxmax);
			return;
		}
		if(x1> pxmax)
		{	x1 = pxmax; y1 = (e -> c - x1)/e -> b;};
		if(x1<pxmin)
		{	x1 = pxmin; y1 = (e -> c - x1)/e -> b;};
		if(x2>pxmax)
		{	x2 = pxmax; y2 = (e -> c - x2)/e -> b;};
		if(x2<pxmin)
		{	x2 = pxmin; y2 = (e -> c - x2)/e -> b;};
	}
	else
	{
		x1 = pxmin;
		if (s1!=(struct Site *)NULL && s1->coord.x > pxmin) 
			x1 = s1->coord.x;
		if(x1>pxmax) 
		{
			//printf("\nClipped (3) x1 = %f to %f",x1,pxmin);
			//return;
			x1 = pxmax;
		}
		y1 = e -> c - e -> a * x1;
		x2 = pxmax;
		if (s2!=(struct Site *)NULL && s2->coord.x < pxmax) 
			x2 = s2->coord.x;
		if(x2<pxmin) 
		{
			//printf("\nClipped (4) x2 = %f to %f",x2,pxmin);
			//return;
			x2 = pxmin;
		}
		y2 = e -> c - e -> a * x2;
		if (((y1> pymax) & (y2>pymax)) | ((y1<pymin)&(y2<pymin))) 
		{
			//printf("\nClipLine jumping out(6), y1 = %f, pymin = %f, pymax = %f",y2,pymin,pymax);
			return;
		}
		if(y1> pymax)
		{	y1 = pymax; x1 = (e -> c - y1)/e -> a;};
		if(y1<pymin)
		{	y1 = pymin; x1 = (e -> c - y1)/e -> a;};
		if(y2>pymax)
		{	y2 = pymax; x2 = (e -> c - y2)/e -> a;};
		if(y2<pymin)
		{	y2 = pymin; x2 = (e -> c - y2)/e -> a;};
	};
	
	//printf("\nPushing line (%f,%f,%f,%f)",x1,y1,x2,y2);
	line(x1,y1,x2,y2);
}
std::vector<RigidBodyConstraint*> CartesianTrajectoryPlannerModule::buildIKConstraints(vigir_planning_msgs::RequestDrakeCartesianTrajectory &request_message, CartesianTrajectoryPlannerModule::Waypoint *start_waypoint, CartesianTrajectoryPlannerModule::Waypoint *target_waypoint, Eigen::VectorXd &q0) {
    std::vector<RigidBodyConstraint*> constraints;

    Vector2d t_span_total;
    t_span_total << start_waypoint->waypoint_time, target_waypoint->waypoint_time;
    Vector2d t_span_target;
    t_span_target << target_waypoint->waypoint_time, target_waypoint->waypoint_time;

    // avoid self-collisions
    if ( request_message.check_self_collisions ) {
            constraints.push_back( new AllBodiesClosestDistanceConstraint(getRobotModel(), 0.01, 1e10, std::vector<int>(), std::set<std::string>(), t_span_total) );
            //constraints.push_back( new MinDistanceConstraint(getRobotModel(), 0.001, std::vector<int>(), std::set<std::string>(), t_span) );
    }

    // keep torso more or less upright
    int torso_body_idx = getRobotModel()->findLinkId("utorso");
    Vector3d axis;
    axis << 0.0, 0.0, 1.0;
    constraints.push_back(new WorldGazeDirConstraint(getRobotModel(), torso_body_idx, axis, axis, 0.1, t_span_total));

    // fixed foot placement
    int l_foot_id = this->getRobotModel()->findLinkId("l_foot");
    int r_foot_id = this->getRobotModel()->findLinkId("r_foot");

    Vector4d hom_foot_pts;
    hom_foot_pts << 0.0,0.0,0.0,1.0;
    Vector3d foot_pts;
    foot_pts << 0.0,0.0,0.0;

    VectorXd v = VectorXd::Zero(this->getRobotModel()->num_velocities);
    this->getRobotModel()->doKinematicsNew(q0, v);
    Vector7d l_foot_pos = this->getRobotModel()->forwardKinNew(foot_pts, l_foot_id, 0, 2, 0).value();
    Vector7d r_foot_pos = this->getRobotModel()->forwardKinNew(foot_pts, r_foot_id, 0, 2, 0).value();

    constraints.push_back( new WorldPositionConstraint(this->getRobotModel(), l_foot_id, hom_foot_pts, l_foot_pos.block<3,1>(0,0), l_foot_pos.block<3,1>(0,0)) );
    constraints.push_back( new WorldPositionConstraint(this->getRobotModel(), r_foot_id, hom_foot_pts, r_foot_pos.block<3,1>(0,0), r_foot_pos.block<3,1>(0,0)) );
    constraints.push_back( new WorldQuatConstraint(this->getRobotModel(), l_foot_id, l_foot_pos.block<4,1>(3,0), 0.0));
    constraints.push_back( new WorldQuatConstraint(this->getRobotModel(), r_foot_id, l_foot_pos.block<4,1>(3,0), 0.0));

    // add quasi static constraint
    MatrixXd l_foot_contact_pts = getRobotModel()->bodies[l_foot_id]->contact_pts;
    MatrixXd r_foot_contact_pts = getRobotModel()->bodies[r_foot_id]->contact_pts;
    QuasiStaticConstraint *quasi_static_constraint = new QuasiStaticConstraint(this->getRobotModel());
    quasi_static_constraint->addContact(1, &l_foot_id, &l_foot_contact_pts);
    quasi_static_constraint->addContact(1, &r_foot_id, &r_foot_contact_pts);
    quasi_static_constraint->setActive(true);
    quasi_static_constraint->setShrinkFactor(0.9);
    constraints.push_back( quasi_static_constraint );

    // add waypoint constraints
    Vector3d goal_position_vec, target_link_axis_vec;
    Vector4d eef_pts, goal_orientation_quat;
    eef_pts << 0.0, 0.0, 0.0, 1.0;
    for ( int target_waypoint_idx = 0; target_waypoint_idx < target_waypoint->target_link_names.size(); target_waypoint_idx++ ) {
        int start_waypoint_idx = -1;
        for ( int j = 0; j < start_waypoint->target_link_names.size(); j++ ) {
            if ( start_waypoint->target_link_names[j].find( target_waypoint->target_link_names[j]) != std::string::npos ) {
                start_waypoint_idx = j;
                break;
            }
        }

        std::string target_link_name = target_waypoint->target_link_names[target_waypoint_idx];

        // get endeffector body ids and points
        int eef_body_id = getRobotModel()->findLinkId(target_link_name);

        // goal position constraint        
        goal_position_vec << target_waypoint->poses[target_waypoint_idx].position.x, target_waypoint->poses[target_waypoint_idx].position.y, target_waypoint->poses[target_waypoint_idx].position.z;
        constraints.push_back( new WorldPositionConstraint(getRobotModel(), eef_body_id, eef_pts, goal_position_vec, goal_position_vec, t_span_target) );

        // goal orientation constraint and straight line between start and target constraint
        if ( start_waypoint_idx >= 0 && start_waypoint->keep_line_and_orientation[start_waypoint_idx] == true ) {
            goal_orientation_quat << start_waypoint->poses[start_waypoint_idx].orientation.w, start_waypoint->poses[start_waypoint_idx].orientation.x, start_waypoint->poses[start_waypoint_idx].orientation.y, start_waypoint->poses[start_waypoint_idx].orientation.z;
            target_link_axis_vec << start_waypoint->target_link_axis[start_waypoint_idx].x, start_waypoint->target_link_axis[start_waypoint_idx].y, start_waypoint->target_link_axis[start_waypoint_idx].z;
        }
        else if ( target_waypoint->keep_line_and_orientation[target_waypoint_idx] == true ) {
            goal_orientation_quat << target_waypoint->poses[target_waypoint_idx].orientation.w, target_waypoint->poses[target_waypoint_idx].orientation.x, target_waypoint->poses[target_waypoint_idx].orientation.y, target_waypoint->poses[target_waypoint_idx].orientation.z;
            target_link_axis_vec << target_waypoint->target_link_axis[target_waypoint_idx].x, target_waypoint->target_link_axis[target_waypoint_idx].y, target_waypoint->target_link_axis[target_waypoint_idx].z;
        }

        if ( request_message.target_orientation_type == vigir_planning_msgs::ExtendedPlanningOptions::ORIENTATION_FULL ) {
           constraints.push_back( new WorldQuatConstraint(getRobotModel(), eef_body_id, goal_orientation_quat, 0, t_span_target));
        }
        else if ( request_message.target_orientation_type == vigir_planning_msgs::ExtendedPlanningOptions::ORIENTATION_AXIS_ONLY ) { // goal axis orientation constraint
           constraints.push_back( new WorldGazeOrientConstraint(getRobotModel(), eef_body_id, target_link_axis_vec, goal_orientation_quat, 0.01, M_PI, t_span_target ));
        }

        if ( start_waypoint_idx >= 0 && start_waypoint->keep_line_and_orientation[start_waypoint_idx] == true ) {
            // line segment
            Vector4d line_start_vec, line_end_vec;
            line_start_vec << start_waypoint->poses[start_waypoint_idx].position.x, start_waypoint->poses[start_waypoint_idx].position.y, start_waypoint->poses[start_waypoint_idx].position.z, 1.0;
            line_end_vec   << target_waypoint->poses[target_waypoint_idx].position.x, target_waypoint->poses[target_waypoint_idx].position.y, target_waypoint->poses[target_waypoint_idx].position.z, 1.0;

            Matrix4Xd line(4,2);
            line << line_start_vec, line_end_vec;

            constraints.push_back( new Point2LineSegDistConstraint(getRobotModel(),eef_body_id,eef_pts,0,line,0.0,0.02,t_span_total) );
        }

    }

    return constraints;
}
Beispiel #24
0
void Map::calcLine()
{
   #if 0
    /*デバッグ用,txtファイルから読み込み*/
    //txtファイルから読み込む
    std::ifstream inFile_Location2("./test/obstacle_list.txt");
	if(!inFile_Location2.is_open())
	{
        std::cout<<"could not open the file \"obstacle_list.txt\"\n";
        std::cout<<"program terminating!\n";
		exit(EXIT_FAILURE);
	}
    
    std::string str1,str2;
    int num_Location2=0;
    std::ifstream fin;//打开文本
    
    fin.open("./test/obstacle_list.txt");
    while(getline(fin,str2))
        ++num_Location2;
    fin.close(); //关闭文本
    Location *obstacle_list = new Location[num_Location2];
    if(inFile_Location2.is_open())
    {
        for(int i=0;i<num_Location2;i++)
        {
            Coordinate tmp_wall;
            inFile_Location2 >> obstacle_list[i].number  >> obstacle_list[i].X >> obstacle_list[i].Y;
            std::cout << obstacle_list[i].number <<"  "<< obstacle_list[i].X << "  " << obstacle_list[i].Y << std::endl;
            
            tmp_wall.x = (obstacle_list[i].X+1000)/10;
            tmp_wall.y = (obstacle_list[i].Y+1000)/10;
            
            wall.push_back(tmp_wall);
        }
    }
   #endif
    /*********************************/
    
    /*競技プログラム用,Mapが保持しているobstacle_point_listから読み込み*/   
     for(int i=0;i<this->wall_point_list.size();i++)
     {
     Coordinate tmp_wall;
     tmp_wall.x = (this->wall_point_list[i].x+1000)/10;
     tmp_wall.y = (this->wall_point_list[i].y+1000)/10;
     wall.push_back(tmp_wall);
     }
     /*********************************/
    
    std::vector<float> a(LINE_NUM);
    std::vector<float> b(LINE_NUM);
    
	for(int i = 0; i < LINE_NUM; i++)
	{
		RANSAC_y_Ax_B(wall, RANSAC_A[i], RANSAC_B[i], RANSAC_C[i], outliers, inliers, xflag);

        if (!xflag) {
            if (RANSAC_A[i]>0 && RANSAC_B[i]<0) {
                a[i]=RANSAC_A[i];
                b[i]=RANSAC_B[i];
            }
            else if (RANSAC_A[i]>0 && RANSAC_B[i]>0){
                a[i]=RANSAC_A[i];
                b[i]=RANSAC_B[i];
            }
            else if (RANSAC_A[i]<0 && RANSAC_B[i]>400){
                a[i]=RANSAC_A[i];
                b[i]=RANSAC_B[i];
            }
            else if (RANSAC_A[i]<0 && RANSAC_B[i]<400){
                a[i]=RANSAC_A[i];
                b[i]=RANSAC_B[i];
            }
            
        }
        
        wall.clear();
		wall = outliers;
		outliers.clear();
	}
    
    double x,y;
    for(int i=0;i<LINE_NUM;i++)
    {
        for(int j=i+1;j<LINE_NUM;j++)
        {
            x=(b[j]-b[i])/(a[i]-a[j]);
            y=a[i]*(b[j]-b[i])/(a[i]-a[j])+b[i];
            line(x, y);
        }
    }
    //p1から順番にp配列にpush_backする
    p.push_back(p1);
    p.push_back(p2);
    p.push_back(p3);
    p.push_back(p4);
    
}
bool parseManifest(const URL& manifestURL, const char* data, int length, Manifest& manifest)
{
    ASSERT(manifest.explicitURLs.isEmpty());
    ASSERT(manifest.onlineWhitelistedURLs.isEmpty());
    ASSERT(manifest.fallbackURLs.isEmpty());
    manifest.allowAllNetworkRequests = false;

    Mode mode = Explicit;

    String s = TextResourceDecoder::create("text/cache-manifest", "UTF-8")->decodeAndFlush(data, length);
    
    // Look for the magic signature: "^\xFEFF?CACHE MANIFEST[ \t]?" (the BOM is removed by TextResourceDecoder).
    // Example: "CACHE MANIFEST #comment" is a valid signature.
    // Example: "CACHE MANIFEST;V2" is not.
    if (!s.startsWith("CACHE MANIFEST"))
        return false;
    
    StringView manifestAfterSignature = StringView(s).substring(14); // "CACHE MANIFEST" is 14 characters.
    auto upconvertedCharacters = manifestAfterSignature.upconvertedCharacters();
    const UChar* p = upconvertedCharacters;
    const UChar* end = p + manifestAfterSignature.length();

    if (p < end && *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r')
        return false;

    // Skip to the end of the line.
    while (p < end && *p != '\r' && *p != '\n')
        p++;

    while (1) {
        // Skip whitespace
        while (p < end && (*p == '\n' || *p == '\r' || *p == ' ' || *p == '\t'))
            p++;
        
        if (p == end)
            break;
        
        const UChar* lineStart = p;
        
        // Find the end of the line
        while (p < end && *p != '\r' && *p != '\n')
            p++;
        
        // Check if we have a comment
        if (*lineStart == '#')
            continue;
        
        // Get rid of trailing whitespace
        const UChar* tmp = p - 1;
        while (tmp > lineStart && (*tmp == ' ' || *tmp == '\t'))
            tmp--;
        
        String line(lineStart, tmp - lineStart + 1);

        if (line == "CACHE:") 
            mode = Explicit;
        else if (line == "FALLBACK:")
            mode = Fallback;
        else if (line == "NETWORK:")
            mode = OnlineWhitelist;
        else if (line.endsWith(':'))
            mode = Unknown;
        else if (mode == Unknown)
            continue;
        else if (mode == Explicit || mode == OnlineWhitelist) {
            auto upconvertedLineCharacters = StringView(line).upconvertedCharacters();
            const UChar* p = upconvertedLineCharacters;
            const UChar* lineEnd = p + line.length();
            
            // Look for whitespace separating the URL from subsequent ignored tokens.
            while (p < lineEnd && *p != '\t' && *p != ' ') 
                p++;

            if (mode == OnlineWhitelist && p - upconvertedLineCharacters == 1 && line[0] == '*') {
                // Wildcard was found.
                manifest.allowAllNetworkRequests = true;
                continue;
            }

            URL url(manifestURL, line.substring(0, p - upconvertedLineCharacters));
            
            if (!url.isValid())
                continue;

            if (url.hasFragmentIdentifier())
                url.removeFragmentIdentifier();
            
            if (!equalIgnoringASCIICase(url.protocol(), manifestURL.protocol()))
                continue;
            
            if (mode == Explicit && manifestURL.protocolIs("https") && !protocolHostAndPortAreEqual(manifestURL, url))
                continue;
            
            if (mode == Explicit)
                manifest.explicitURLs.add(url.string());
            else
                manifest.onlineWhitelistedURLs.append(url);
            
        } else if (mode == Fallback) {
            auto upconvertedLineCharacters = StringView(line).upconvertedCharacters();
            const UChar* p = upconvertedLineCharacters;
            const UChar* lineEnd = p + line.length();
            
            // Look for whitespace separating the two URLs
            while (p < lineEnd && *p != '\t' && *p != ' ') 
                p++;

            if (p == lineEnd) {
                // There was no whitespace separating the URLs.
                continue;
            }
            
            URL namespaceURL(manifestURL, line.substring(0, p - upconvertedLineCharacters));
            if (!namespaceURL.isValid())
                continue;
            if (namespaceURL.hasFragmentIdentifier())
                namespaceURL.removeFragmentIdentifier();

            if (!protocolHostAndPortAreEqual(manifestURL, namespaceURL))
                continue;
                                   
            // Skip whitespace separating fallback namespace from URL.
            while (p < lineEnd && (*p == '\t' || *p == ' '))
                p++;

            // Look for whitespace separating the URL from subsequent ignored tokens.
            const UChar* fallbackStart = p;
            while (p < lineEnd && *p != '\t' && *p != ' ') 
                p++;

            URL fallbackURL(manifestURL, String(fallbackStart, p - fallbackStart));
            if (!fallbackURL.isValid())
                continue;
            if (fallbackURL.hasFragmentIdentifier())
                fallbackURL.removeFragmentIdentifier();

            if (!protocolHostAndPortAreEqual(manifestURL, fallbackURL))
                continue;

            manifest.fallbackURLs.append(std::make_pair(namespaceURL, fallbackURL));            
        } else 
            ASSERT_NOT_REACHED();
    }

    return true;
}
Beispiel #26
0
bool CHttpServer::parse_request(String &method, String &uri, String &query, HeaderList &headers, String &body)
{
    method.clear();
    uri.clear();
    headers.clear();
    body.clear();

    size_t s = 0;
    ByteVector request;

    bool parsing_headers = true;
    size_t content_length = 0;

    for (;;) {
        if (!receive_request(request))
            return false;

        size_t lim = request.size();
        while (parsing_headers) {
            size_t e;
            for(e = s; e < lim && request[e] != '\r'; ++e);
            if (e >= lim - 1) {
                // Incomplete line, will read further
                break;
            }
            if (request[e + 1] != '\n') {
                RAWLOG_ERROR("Wrong request syntax, line should ends by '\\r\\n'");
                return false;
            }
            
            String line(&request[s], e - s);
            s = e + 2;
            
            if (line.empty()) {
                parsing_headers = false;
                break;
            }
            
            if (uri.empty()) {
                // Parse start line
                if (!parse_startline(line, method, uri, query) || uri.empty())
                    return false;
            }
            else {
                Header hdr;
                if (!parse_header(line, hdr) || hdr.name.empty())
                    return false;
                headers.push_back(hdr);
                
                String low;
                std::transform(hdr.name.begin(), hdr.name.end(), std::back_inserter(low), &::tolower);
                if (low == "content-length") {
                    content_length = ::atoi(hdr.value.c_str());
                }
            }
        }

        if (!parsing_headers) {
            if (content_length == 0)
                return true;

            if (lim - s < content_length)
                continue;

            body.assign(&request[s], &request[s] + content_length);
            return true;
        }
    }
}
Beispiel #27
0
void shakil::show()
{
 hidemouseptr();
 setcolor(123);

 for(i=0;i<n;i++)
 for(j=0;j<n;j++)
 {
   if(vm[i][j]==10)
   {setcolor(123);
   rectangle(xp1[i][j],yp1[i][j],xp2[i][j],yp2[i][j]);
   setfillstyle(SOLID_FILL,123);
   floodfill(xp1[i][j]+2,yp1[i][j]+2,123);
     }
    if(vm[i][j]==5)
    {setcolor(7);
     rectangle(xp1[i][j],yp1[i][j],xp2[i][j],yp2[i][j]);
      setfillstyle(SOLID_FILL,7);
     floodfill(xp1[i][j]+2,yp1[i][j]+2,7);

    }
   if(vm[i][j]==0)
   { setcolor(BLACK);
     rectangle(xp1[i][j],yp1[i][j],xp2[i][j]+(c12/2),yp2[i][j]+(c12/2));
     setfillstyle(SOLID_FILL,BLACK);
     floodfill(xp1[i][j]+2,yp1[i][j]+2,BLACK);
     line(xp1[i][j],yp2[i][j],xp1[i][j]+(c12/2),yp2[i][j]+(c12/2));
    line(xp2[i][j],yp1[i][j],xp2[i][j]+(c12/2),yp1[i][j]+(c12/2));
   }
   if(vm[i][j]==5||vm[i][j]==10)
   {
    setcolor(RED);
    p=res1[i][j]/100;
    if(p>0)
    {switch(p)
    {case 0:
	  outtextxy(xp1[i][j]+1,(yp1[i][j]+yp2[i][j])/2-10,"0");
	  break;
      case 1:
	  outtextxy(xp1[i][j]+1,(yp1[i][j]+yp2[i][j])/2-10,"1");
	  break;

    case 2:
	  outtextxy(xp1[i][j]+1,(yp1[i][j]+yp2[i][j])/2-10,"2");
	  break;
    case 3:
	  outtextxy(xp1[i][j]+1,(yp1[i][j]+yp2[i][j])/2-10,"3");
	  break;
   case 4:
	  outtextxy(xp1[i][j]+1,(yp1[i][j]+yp2[i][j])/2-10,"4");
	  break;
    case 5:
	  outtextxy(xp1[i][j]+1,(yp1[i][j]+yp2[i][j])/2-10,"5");
	  break;
    case 6:
	  outtextxy(xp1[i][j]+1,(yp1[i][j]+yp2[i][j])/2-10,"6");
	  break;
    case 7:
	  outtextxy(xp1[i][j]+1,(yp1[i][j]+yp2[i][j])/2-10,"7");
	  break;
    case 8:
	  outtextxy(xp1[i][j]+1,(yp1[i][j]+yp2[i][j])/2-10,"8");
	  break;
    case 9:
	  outtextxy(xp1[i][j]+1,(yp1[i][j]+yp2[i][j])/2-10,"9");
	  break;
    }

    }
    m=res1[i][j]/10;
    if(m>9)
    m=m-p*10;
    if(m>0||p>0)
    {switch(m)
    {case 0:
	  outtextxy(xp1[i][j]+10,(yp1[i][j]+yp2[i][j])/2-10,"0");
	  break;
    case 1:
	  outtextxy(xp1[i][j]+10,(yp1[i][j]+yp2[i][j])/2-10,"1");
	  break;

    case 2:
	  outtextxy(xp1[i][j]+10,(yp1[i][j]+yp2[i][j])/2-10,"2");
	  break;
    case 3:
	  outtextxy(xp1[i][j]+10,(yp1[i][j]+yp2[i][j])/2-10,"3");
	  break;
    case 4:
	  outtextxy(xp1[i][j]+10,(yp1[i][j]+yp2[i][j])/2-10,"4");
	  break;
    case 5:
	  outtextxy(xp1[i][j]+10,(yp1[i][j]+yp2[i][j])/2-10,"5");
	  break;
    case 6:
	  outtextxy(xp1[i][j]+10,(yp1[i][j]+yp2[i][j])/2-10,"6");
	  break;
    case 7:
	  outtextxy(xp1[i][j]+10,(yp1[i][j]+yp2[i][j])/2-10,"7");
	  break;
    case 8:
	  outtextxy(xp1[i][j]+10,(yp1[i][j]+yp2[i][j])/2-10,"8");
	  break;
    case 9:
	  outtextxy(xp1[i][j]+10,(yp1[i][j]+yp2[i][j])/2-10,"9");
	  break;



    }

    }
    m=res1[i][j]%10;
    switch(m)
    {case 0:
	  outtextxy(xp1[i][j]+20,(yp1[i][j]+yp2[i][j])/2-10,"0");
	  break;
      case 1:
	  outtextxy(xp1[i][j]+20,(yp1[i][j]+yp2[i][j])/2-10,"1");
	  break;

    case 2:
	  outtextxy(xp1[i][j]+20,(yp1[i][j]+yp2[i][j])/2-10,"2");
	  break;
    case 3:
	  outtextxy(xp1[i][j]+20,(yp1[i][j]+yp2[i][j])/2-10,"3");
	  break;
    case 4:
	  outtextxy(xp1[i][j]+20,(yp1[i][j]+yp2[i][j])/2-10,"4");
	  break;
    case 5:
	  outtextxy(xp1[i][j]+20,(yp1[i][j]+yp2[i][j])/2-10,"5");
	  break;
    case 6:
	  outtextxy(xp1[i][j]+20,(yp1[i][j]+yp2[i][j])/2-10,"6");
	  break;
    case 7:
	  outtextxy(xp1[i][j]+20,(yp1[i][j]+yp2[i][j])/2-10,"7");
	  break;
    case 8:
	  outtextxy(xp1[i][j]+20,(yp1[i][j]+yp2[i][j])/2-10,"8");
	  break;
    case 9:
	  outtextxy(xp1[i][j]+20,(yp1[i][j]+yp2[i][j])/2-10,"9");
	  break;



    }
    setcolor(8);
    line(xp1[i][j]+(c12/2),yp2[i][j]+(c12/2),xp2[i][j]+(c12/2),yp2[i][j]+(c12/2));
    line(xp2[i][j]+(c12/2),yp1[i][j]+(c12/2),xp2[i][j]+(c12/2),yp2[i][j]+(c12/2));
    line(xp1[i][j],yp2[i][j],xp1[i][j]+(c12/2),yp2[i][j]+(c12/2));
    line(xp2[i][j],yp1[i][j],xp2[i][j]+(c12/2),yp1[i][j]+(c12/2));
    // setfillstyle(SOLID_FILL,8);
   //  floodfill(xp2[i][j],yp2[i][j]+2,8);
    }
	}
    setcolor(123);
    rectangle(xp1[0][0]-c12,yp1[0][0]-c12,xp2[n-1][n-1]+c12,yp2[n-1][n-1]+c12);
    setcolor(2);
    rectangle(470,370,520,390);
    setfillstyle(SOLID_FILL,2);
    floodfill(477,376,2);
    setcolor(RED);
    outtextxy(476,369,"EXIT");
    setcolor(2);
    rectangle(470,270,520,290);
    setfillstyle(SOLID_FILL,2);
    floodfill(477,276,2);
    setcolor(RED);
    outtextxy(473,270,"SAVE");
    showmouseptr();

}
Beispiel #28
0
 ///Direct line through origin
 Line dualLine( VSR_PRECISION x, VSR_PRECISION y, VSR_PRECISION z ){
   return line(x,y,z).dual();
 }      
Beispiel #29
0
char obj_figura::edita()
{
  ctela.limpa_teclado();
  MouseFun mouse(getmaxx() / 2, getmaxy() / 2, 0);

  if (carquivo_somente_leitura)
    return FALSO;
  else
    if (!carquivo_definido)
      return FALSO;
    else
     {
       tipo_xy cx, cy;
       tipo_xy cxant, cyant;
       tipo_xy ccentrox, ccentroy;
       tipo_angulo cangulo = 0;
       tipo_raio craio = 1;
       char ccirculo = FALSO;
       char ccor = 15;
       char* cursor = (char*) malloc(sizeof(char) * 2);
       char caracter = NULL;
       char clicado = FALSO;
       char velocidade = 1;

       cx = (tipo_xy) (ctela.max_x + 1) / 2;
       cy = (tipo_xy) (ctela.max_y + 1) / 2;

       ccentrox = cx;
       ccentroy = cy;

       cor(8);
       line(cx, 0, cx, ctela.max_y);
       line(0, cy, ctela.max_x, cy);

       putpixel(0, 0, 15);
       getimage(0, 0, 0, 0, cursor);
       putpixel(0, 0, 0);

       do
       {
         cx = mouse.x();
         cy = mouse.y();

         if (keypressed)
         {
           ctela.le_teclado(&caracter);

           switch (caracter)
           {
             case CARACTER_NULO:
               ctela.le_teclado(&caracter);

               if (!ccirculo)
               {
                 switch (caracter)
                 {
                   case SETA_CIMA:
                     cy -= velocidade;
                   break;

                   case SETA_BAIXO:
                     cy += velocidade;
                   break;

                   case SETA_DIREITA:
                     cx += velocidade;
                   break;

                   case SETA_ESQUERDA:
                     cx -= velocidade;
                   break;
                 }
               }
               else
                 {
                   switch (caracter)
                   {
                     case SETA_CIMA:
                       craio += velocidade;
                     break;

                     case SETA_BAIXO:
                       craio -= velocidade;
                     break;

                     case SETA_DIREITA:
                       cangulo += velocidade;
                     break;

                     case SETA_ESQUERDA:
                       cangulo -= velocidade;
                     break;
                   }

                   converte(cangulo, craio, &cx, &cy, ccentrox, ccentroy);
                 }

             break;

             case BARRA_DE_ESPACO:
               if (!clicado)
               {
                 clicado = VERDADEIRO;
                 cxant = cx;
                 cyant = cy;
               }
               else
                 {
                   clicado = FALSO;
                   poe(cx, cy, cxant, cyant, ccor);
                 }
             break;

             case CTRL_A:
               poe(cx + 5, cy, cx + 20, cy + 13, ccor);
               poe(cx, cy, cx + 15, cy + 16, ccor);
               poe(cx - 2, cy + 5, cx + 13, cy + 19, ccor);
               poe(cx - 4, cy + 7, cx + 11, cy + 20, ccor);
               poe(cx - 5, cy + 14, cx + 12, cy, ccor);
               poe(cx - 1, cy + 16, cx + 15, cy + 2, ccor);
               poe(cx + 3, cy + 19, cx + 17, cy + 5, ccor);
               poe(cx + 6, cy + 20, cx + 20, cy + 8, ccor);
             break;

             case CTRL_B:
               ccor++;

               if (ccor > 15)
                 ccor = 0;
             break;

             case CTRL_D:
               if (!ccirculo)
               {
                 ccentrox = cx;
                 ccentroy = cy;
               }
               else
                 if (ccirculo)
                 {
                   cx = ccentrox;
                   cy = ccentroy;
                 }

               ccirculo = !ccirculo;
             break;

             case MAIS:
               velocidade++;
             break;

             case MENOS:
               velocidade--;
             break;

             case CTRL_Z:
               tira();
             break;
           }
         }

         putimage(cx, cy, cursor, XOR_PUT);
         delay(1);
         putimage(cx, cy, cursor, XOR_PUT);
       }
       while(caracter != ENTER);

       return VERDADEIRO;
     }
}
Beispiel #30
0
void dot::disp(dot r){
pixel(x,y,color);
line(x,y,r.x,r.y,color);
}