Esempio n. 1
0
osg::Node* createRoom(osg::Node* loadedModel)
{
    // default scale for this model.
    osg::BoundingSphere bs(osg::Vec3(0.0f,0.0f,0.0f),1.0f);

    osg::Group* root = new osg::Group;

    if (loadedModel)
    {
        const osg::BoundingSphere& loaded_bs = loadedModel->getBound();

        osg::PositionAttitudeTransform* pat = new osg::PositionAttitudeTransform();
        pat->setPivotPoint(loaded_bs.center());
        
        pat->setUpdateCallback(new ModelTransformCallback(loaded_bs));
        pat->addChild(loadedModel);
        
        bs = pat->getBound();
        
        root->addChild(pat);

    }

    bs.radius()*=1.5f;

    // create a bounding box, which we'll use to size the room.
    osg::BoundingBox bb;
    bb.expandBy(bs);


    // create statesets.
    osg::StateSet* rootStateSet = new osg::StateSet;
    root->setStateSet(rootStateSet);

    osg::StateSet* wall = new osg::StateSet;
    wall->setMode(GL_CULL_FACE,osg::StateAttribute::ON);
    
    osg::StateSet* floor = new osg::StateSet;
    floor->setMode(GL_CULL_FACE,osg::StateAttribute::ON);

    osg::StateSet* roof = new osg::StateSet;
    roof->setMode(GL_CULL_FACE,osg::StateAttribute::ON);

    osg::Geode* geode = new osg::Geode;
    
    // create front side.
    geode->addDrawable(createWall(bb.corner(0),
                                  bb.corner(4),
                                  bb.corner(1),
                                  wall));

    // right side
    geode->addDrawable(createWall(bb.corner(1),
                                  bb.corner(5),
                                  bb.corner(3),
                                  wall));

    // left side
    geode->addDrawable(createWall(bb.corner(2),
                                  bb.corner(6),
                                  bb.corner(0),
                                  wall));
    // back side
    geode->addDrawable(createWall(bb.corner(3),
                                  bb.corner(7),
                                  bb.corner(2),
                                  wall));

    // floor
    geode->addDrawable(createWall(bb.corner(0),
                                  bb.corner(1),
                                  bb.corner(2),
                                  floor));

    // roof
    geode->addDrawable(createWall(bb.corner(6),
                                  bb.corner(7),
                                  bb.corner(4),
                                  roof));

    root->addChild(geode);
    
    root->addChild(createLights(bb,rootStateSet));

    return root;
    
}    
void HuffmanStringProcessor::buildTables()
{
   TNLAssert(mTablesBuilt == false, "Cannot build tables twice!");
   mTablesBuilt = true;

   S32 i;

   // First, construct the array of wraps...
   //
   mHuffLeaves.setSize(256);
   mHuffNodes.reserve(256);
   mHuffNodes.setSize(mHuffNodes.size() + 1);
   for (i = 0; i < 256; i++) {
      HuffLeaf& rLeaf = mHuffLeaves[i];

      rLeaf.pop    = mCharFreqs[i] + 1;
      rLeaf.symbol = U8(i);

      memset(&rLeaf.code, 0, sizeof(rLeaf.code));
      rLeaf.numBits = 0;
   }

   S32 currWraps = 256;
   HuffWrap* pWrap = new HuffWrap[256];
   for (i = 0; i < 256; i++) {
      pWrap[i].set(&mHuffLeaves[i]);
   }

   while (currWraps != 1) {
      U32 min1 = 0xfffffffe, min2 = 0xffffffff;
      S32 index1 = -1, index2 = -1;

      for (i = 0; i < currWraps; i++) {
         if (pWrap[i].getPop() < min1) {
            min2   = min1;
            index2 = index1;

            min1   = pWrap[i].getPop();
            index1 = i;
         } else if (pWrap[i].getPop() < min2) {
            min2   = pWrap[i].getPop();
            index2 = i;
         }
      }
      TNLAssert(index1 != -1 && index2 != -1 && index1 != index2, "hrph");

      // Create a node for this...
      mHuffNodes.setSize(mHuffNodes.size() + 1);
      HuffNode& rNode = mHuffNodes.last();
      rNode.pop    = pWrap[index1].getPop() + pWrap[index2].getPop();
      rNode.index0 = determineIndex(pWrap[index1]);
      rNode.index1 = determineIndex(pWrap[index2]);

      S32 mergeIndex = index1 > index2 ? index2 : index1;
      S32 nukeIndex  = index1 > index2 ? index1 : index2;
      pWrap[mergeIndex].set(&rNode);

      if (index2 != (currWraps - 1)) {
         pWrap[nukeIndex] = pWrap[currWraps - 1];
      }
      currWraps--;
   }
   TNLAssert(currWraps == 1, "wrong wraps?");
   TNLAssert(pWrap[0].pNode != NULL && pWrap[0].pLeaf == NULL, "Wrong wrap type!");

   // Ok, now we have one wrap, which is a node.  we need to make sure that this
   //  is the first node in the node list.
   mHuffNodes[0] = *(pWrap[0].pNode);
   delete [] pWrap;

   U32 code = 0;
   BitStream bs((U8 *) &code, 4);

   generateCodes(bs, 0, 0);
}
Esempio n. 3
0
Dialog::Dialog() : QDialog(0, 0, TRUE)
{
    Q3VBoxLayout * vbox = new Q3VBoxLayout(this);
    Q3VGroupBox * gbox;
    Q3HButtonGroup * bg;
    Q3HBox * htab;

    vbox->setMargin(5);

    gbox = new Q3VGroupBox("Filters" , this);
    vbox->addWidget(gbox);

    htab = new Q3HBox(gbox);
    //htab->setMargin(5);

    new QLabel("filter 1 : ", htab);
    filter1_le = new LineEdit(htab);

    new QLabel("  ", htab);

    bg = new Q3HButtonGroup(htab);
    bg->setRadioButtonExclusive(TRUE);

    with1_rb = new QRadioButton("with", bg);
    new QRadioButton("without", bg);
    with1_rb->setChecked(TRUE);

    //

    htab = new Q3HBox(gbox);
    //htab->setMargin(5);

    new QLabel("", htab);
    bg = new Q3HButtonGroup(htab);
    bg->setRadioButtonExclusive(TRUE);

    and12_rb = new QRadioButton("and", bg);
    new QRadioButton("or", bg);
    and12_rb->setChecked(TRUE);

    new QLabel("", htab);

    //

    htab = new Q3HBox(gbox);
    //htab->setMargin(5);

    new QLabel("filter 2 : ", htab);
    filter2_le = new LineEdit(htab);

    new QLabel("  ", htab);

    bg = new Q3HButtonGroup(htab);
    bg->setRadioButtonExclusive(TRUE);

    with2_rb = new QRadioButton("with", bg);
    new QRadioButton("without", bg);
    with2_rb->setChecked(TRUE);

    //

    htab = new Q3HBox(gbox);
    //htab->setMargin(5);

    new QLabel("", htab);
    bg = new Q3HButtonGroup(htab);
    bg->setRadioButtonExclusive(TRUE);

    and23_rb = new QRadioButton("and", bg);
    new QRadioButton("or", bg);
    and23_rb->setChecked(TRUE);

    new QLabel("", htab);

    //

    htab = new Q3HBox(gbox);
    //htab->setMargin(5);

    new QLabel("filter 3 : ", htab);
    filter3_le = new LineEdit(htab);

    new QLabel("  ", htab);

    bg = new Q3HButtonGroup(htab);
    bg->setRadioButtonExclusive(TRUE);

    with3_rb = new QRadioButton("with", bg);
    new QRadioButton("without", bg);
    with3_rb->setChecked(TRUE);

    //
    //

    gbox = new Q3VGroupBox("Stereotype" , this);
    vbox->addWidget(gbox);

    htab = new Q3HBox(gbox);
    //htab->setMargin(5);

    bg = new Q3HButtonGroup(htab);
    bg->setRadioButtonExclusive(TRUE);

    any_rb = new QRadioButton("any", bg);
    is_rb = new QRadioButton("is", bg);
    isnot_rb = new QRadioButton("is not", bg);
    any_rb->setChecked(TRUE);
    stereotype_le = new QLineEdit(htab);

    //
    //

    gbox = new Q3VGroupBox("Targets" , this);
    vbox->addWidget(gbox);

    htab = new Q3HBox(gbox);
    //htab->setMargin(5);

    artifact_cb = new QCheckBox("artifact", htab);
    class_cb = new QCheckBox("class", htab);
    operation_cb = new QCheckBox("operation", htab);
    attribute_cb = new QCheckBox("attribute", htab);
    relation_cb = new QCheckBox("relation", htab);

    //
    //

    gbox = new Q3VGroupBox("Languages" , this);
    vbox->addWidget(gbox);

    htab = new Q3HBox(gbox);
    //htab->setMargin(5);

    cpp_cb = new QCheckBox("C++", htab);
    java_cb = new QCheckBox("Java", htab);
    php_cb = new QCheckBox("Php", htab);
    python_cb = new QCheckBox("Python", htab);
    idl_cb = new QCheckBox("Idl", htab);

    //
    //

    Q3Grid * grid = new Q3Grid(2, this);
    vbox->addWidget(grid);
    grid->setMargin(5);
    grid->setSpacing(5);

    new QLabel("current : ", grid);
    current_le  = new LineEdit(grid);

    new QLabel("new : ", grid);
    new_le  = new LineEdit(grid);

    //
    //

    htab = new Q3HBox(this);
    htab->setMargin(5);
    vbox->addWidget(htab);

    new QLabel(htab);
    QPushButton * replace = new QPushButton("Replace", htab);
    new QLabel(htab);
    QPushButton * quit = new QPushButton("Quit", htab);
    new QLabel(htab);

    QSize bs(replace->sizeHint());

    quit->setFixedSize(bs);

    connect(replace, SIGNAL(clicked()), this, SLOT(do_replace()));
    connect(quit, SIGNAL(clicked()), this, SLOT(reject()));

}
/*
Description: Tests what happens if two instances of RakNet connect to each other at the same time. This has caused handshaking problems in the past.

Success conditions:
Everything connects and sends normally.

Failure conditions:
Expected values from ping/pong do not occur within expected time.
*/
int CrossConnectionConvertTest::RunTest(DataStructures::List<RakString> params,bool isVerbose,bool noPauses)
{

	static const unsigned short SERVER_PORT=1234;
	//	char serverMode[32];
	char serverIP[64];

	strcpy(serverIP,"127.0.0.1");	

	char clientIP[64];
	RakPeerInterface *server,*client;
	unsigned short clientPort;
	bool gotNotification;
	server=RakPeerInterface::GetInstance();
	destroyList.Clear(false,_FILE_AND_LINE_);
	destroyList.Push(server,_FILE_AND_LINE_);
	client=RakPeerInterface::GetInstance();
	destroyList.Push(client,_FILE_AND_LINE_);

	

	server->Startup(1,&SocketDescriptor(SERVER_PORT,0), 1);
	server->SetMaximumIncomingConnections(1);

	client->Startup(1,&SocketDescriptor(0,0), 1);

	client->Ping(serverIP,SERVER_PORT,false);

	//	PacketLogger pl;
	//	pl.LogHeader();
	//	rakPeer->AttachPlugin(&pl);

	TimeMS connectionAttemptTime=0,connectionResultDeterminationTime=0,nextTestStartTime=0;

	TimeMS entryTime=GetTimeMS();//Loop entry time

	bool printedYet=false;
	while(GetTimeMS()-entryTime<10000)//Run for 10 Secoonds
	{

		Packet *p;

		printedYet=false;

		for (p=server->Receive(); p; server->DeallocatePacket(p), p=server->Receive())
		{

			if (isVerbose&&!printedYet)
			{
				printf("Server:\n");
				printedYet=true;
			}
			if (p->data[0]==ID_NEW_INCOMING_CONNECTION)
			{

				if (isVerbose)
					printf("ID_NEW_INCOMING_CONNECTION\n");
				gotNotification=true;
			}
			else if (p->data[0]==ID_CONNECTION_REQUEST_ACCEPTED)
			{

				if (isVerbose)
					printf("ID_CONNECTION_REQUEST_ACCEPTED\n");
				gotNotification=true;
			}
			else if (p->data[0]==ID_UNCONNECTED_PING)
			{

				if (isVerbose)
					printf("ID_PING\n");
				connectionAttemptTime=GetTimeMS()+1000;
				p->systemAddress.ToString(false,clientIP);
				clientPort=p->systemAddress.port;
				gotNotification=false;
			}
			else if (p->data[0]==ID_UNCONNECTED_PONG)
			{

				if (isVerbose)
					printf("ID_UNCONNECTED_PONG\n");
				TimeMS sendPingTime;
				BitStream bs(p->data,p->length,false);
				bs.IgnoreBytes(1);
				bs.Read(sendPingTime);
				TimeMS rtt = GetTimeMS() - sendPingTime;
				if (rtt/2<=500)
					connectionAttemptTime=GetTimeMS()+1000-rtt/2;
				else
					connectionAttemptTime=GetTimeMS();
				gotNotification=false;
			}
		}

		printedYet=false;
		for (p=client->Receive(); p; client->DeallocatePacket(p), p=client->Receive())
		{

			if (isVerbose&&!printedYet)
			{
				printf("Client:\n");
				printedYet=true;
			}
			if (p->data[0]==ID_NEW_INCOMING_CONNECTION)
			{

				if (isVerbose)
					printf("ID_NEW_INCOMING_CONNECTION\n");
				gotNotification=true;
			}
			else if (p->data[0]==ID_CONNECTION_REQUEST_ACCEPTED)
			{

				if (isVerbose)
					printf("ID_CONNECTION_REQUEST_ACCEPTED\n");
				gotNotification=true;
			}
			else if (p->data[0]==ID_UNCONNECTED_PING)
			{

				if (isVerbose)
					printf("ID_PING\n");
				connectionAttemptTime=GetTimeMS()+1000;
				p->systemAddress.ToString(false,clientIP);
				clientPort=p->systemAddress.port;
				gotNotification=false;
			}
			else if (p->data[0]==ID_UNCONNECTED_PONG)
			{

				if (isVerbose)
					printf("ID_UNCONNECTED_PONG\n");
				TimeMS sendPingTime;
				BitStream bs(p->data,p->length,false);
				bs.IgnoreBytes(1);
				bs.Read(sendPingTime);
				TimeMS rtt = GetTimeMS() - sendPingTime;
				if (rtt/2<=500)
					connectionAttemptTime=GetTimeMS()+1000-rtt/2;
				else
					connectionAttemptTime=GetTimeMS();
				gotNotification=false;
			}
		}

		if (connectionAttemptTime!=0 && GetTimeMS()>=connectionAttemptTime)
		{

			if (isVerbose)
				printf("Attemping connection\n");
			connectionAttemptTime=0;

			server->Connect(clientIP,clientPort,0,0);
			client->Connect(serverIP,SERVER_PORT,0,0);

			connectionResultDeterminationTime=GetTimeMS()+2000;
		}
		if (connectionResultDeterminationTime!=0 && GetTimeMS()>=connectionResultDeterminationTime)
		{
			connectionResultDeterminationTime=0;
			if (gotNotification==false)
			{
				DebugTools::ShowError("Did not recieve expected response. \n",!noPauses && isVerbose,__LINE__,__FILE__);
				return 1;
			}

			SystemAddress sa;
			sa.SetBinaryAddress(serverIP);
			sa.port=SERVER_PORT;
			client->CancelConnectionAttempt(sa);

			sa.SetBinaryAddress(clientIP);
			sa.port=clientPort;
			server->CancelConnectionAttempt(sa);

			server->CloseConnection(server->GetSystemAddressFromIndex(0),true,0);
			client->CloseConnection(client->GetSystemAddressFromIndex(0),true,0);

			//if (isServer==false)
			nextTestStartTime=GetTimeMS()+1000;

		}
		if (nextTestStartTime!=0 && GetTimeMS()>=nextTestStartTime)
		{
			client->Ping(serverIP,SERVER_PORT,false);
			nextTestStartTime=0;
		}
		RakSleep(0);

	}
	if (isVerbose)
		printf("Test succeeded.\n");

	return 0;

}
Esempio n. 5
0
int cDvbSubtitleConverter::ExtractSegment(const uchar *Data, int Length, int64_t Pts)
{
  cBitStream bs(Data, Length * 8);
  if (Length > 5 && bs.GetBits(8) == 0x0F) { // sync byte
     int segmentType = bs.GetBits(8);
     if (segmentType == STUFFING_SEGMENT)
        return -1;
     int pageId = bs.GetBits(16);
     int segmentLength = bs.GetBits(16);
     if (!bs.SetLength(bs.Index() + segmentLength * 8))
        return -1;
     cDvbSubtitlePage *page = NULL;
     LOCK_THREAD;
     for (cDvbSubtitlePage *sp = pages->First(); sp; sp = pages->Next(sp)) {
         if (sp->PageId() == pageId) {
            page = sp;
            break;
            }
         }
     if (!page) {
        page = new cDvbSubtitlePage(pageId);
        pages->Add(page);
        dbgpages("Create SubtitlePage %d (total pages = %d)\n", pageId, pages->Count());
        }
     if (Pts)
        page->SetPts(Pts);
     switch (segmentType) {
       case PAGE_COMPOSITION_SEGMENT: {
            dbgsegments("PAGE_COMPOSITION_SEGMENT\n");
            int pageTimeout = bs.GetBits(8);
            int pageVersion = bs.GetBits(4);
            if (pageVersion == page->Version())
               break; // no update
            page->SetVersion(pageVersion);
            page->SetTimeout(pageTimeout);
            page->SetState(bs.GetBits(2));
            bs.SkipBits(2); // reserved
            dbgpages("Update page id %d version %d pts %"PRId64" timeout %d state %d\n", pageId, page->Version(), page->Pts(), page->Timeout(), page->State());
            while (!bs.IsEOF()) {
                  cSubtitleRegion *region = page->GetRegionById(bs.GetBits(8), true);
                  bs.SkipBits(8); // reserved
                  region->SetHorizontalAddress(bs.GetBits(16));
                  region->SetVerticalAddress(bs.GetBits(16));
                  }
            break;
            }
       case REGION_COMPOSITION_SEGMENT: {
            dbgsegments("REGION_COMPOSITION_SEGMENT\n");
            cSubtitleRegion *region = page->GetRegionById(bs.GetBits(8));
            if (!region)
               break;
            int regionVersion = bs.GetBits(4);
            if (regionVersion == region->Version())
               break; // no update
            region->SetVersion(regionVersion);
            bool regionFillFlag = bs.GetBit();
            bs.SkipBits(3); // reserved
            int regionWidth = bs.GetBits(16);
            if (regionWidth < 1)
               regionWidth = 1;
            int regionHeight = bs.GetBits(16);
            if (regionHeight < 1)
               regionHeight = 1;
            region->SetSize(regionWidth, regionHeight);
            region->SetLevel(bs.GetBits(3));
            region->SetDepth(bs.GetBits(3));
            bs.SkipBits(2); // reserved
            region->SetClutId(bs.GetBits(8));
            dbgregions("Region pageId %d id %d version %d fill %d width %d height %d level %d depth %d clutId %d\n", pageId, region->RegionId(), region->Version(), regionFillFlag, regionWidth, regionHeight, region->Level(), region->Depth(), region->ClutId());
            int region8bitPixelCode = bs.GetBits(8);
            int region4bitPixelCode = bs.GetBits(4);
            int region2bitPixelCode = bs.GetBits(2);
            bs.SkipBits(2); // reserved
            if (regionFillFlag) {
               switch (region->Bpp()) {
                 case 2: region->FillRegion(region8bitPixelCode); break;
                 case 4: region->FillRegion(region4bitPixelCode); break;
                 case 8: region->FillRegion(region2bitPixelCode); break;
                 default: dbgregions("unknown bpp %d (%s %d)\n", region->Bpp(), __FUNCTION__, __LINE__);
                 }
               }
            while (!bs.IsEOF()) {
                  cSubtitleObject *object = region->GetObjectById(bs.GetBits(16), true);
                  int objectType = bs.GetBits(2);
                  object->SetCodingMethod(objectType);
                  object->SetProviderFlag(bs.GetBits(2));
                  int objectHorizontalPosition = bs.GetBits(12);
                  bs.SkipBits(4); // reserved
                  int objectVerticalPosition = bs.GetBits(12);
                  object->SetPosition(objectHorizontalPosition, objectVerticalPosition);
                  if (objectType == 0x01 || objectType == 0x02) {
                     object->SetForegroundPixelCode(bs.GetBits(8));
                     object->SetBackgroundPixelCode(bs.GetBits(8));
                     }
                  }
            break;
            }
       case CLUT_DEFINITION_SEGMENT: {
            dbgsegments("CLUT_DEFINITION_SEGMENT\n");
            cSubtitleClut *clut = page->GetClutById(bs.GetBits(8), true);
            int clutVersion = bs.GetBits(4);
            if (clutVersion == clut->Version())
               break; // no update
            clut->SetVersion(clutVersion);
            bs.SkipBits(4); // reserved
            dbgcluts("Clut pageId %d id %d version %d\n", pageId, clut->ClutId(), clut->Version());
            while (!bs.IsEOF()) {
                  uchar clutEntryId = bs.GetBits(8);
                  bool entryClut2Flag = bs.GetBit();
                  bool entryClut4Flag = bs.GetBit();
                  bool entryClut8Flag = bs.GetBit();
                  bs.SkipBits(4); // reserved
                  uchar yval;
                  uchar crval;
                  uchar cbval;
                  uchar tval;
                  if (bs.GetBit()) { // full_range_flag
                     yval  = bs.GetBits(8);
                     crval = bs.GetBits(8);
                     cbval = bs.GetBits(8);
                     tval  = bs.GetBits(8);
                     }
                  else {
                     yval  = bs.GetBits(6) << 2;
                     crval = bs.GetBits(4) << 4;
                     cbval = bs.GetBits(4) << 4;
                     tval  = bs.GetBits(2) << 6;
                     }
                  tColor value = 0;
                  if (yval) {
                     value = yuv2rgb(yval, cbval, crval);
                     value |= ((10 - (clutEntryId ? Setup.SubtitleFgTransparency : Setup.SubtitleBgTransparency)) * (255 - tval) / 10) << 24;
                     }
                  dbgcluts("%2d %d %d %d %08X\n", clutEntryId, entryClut2Flag ? 2 : 0, entryClut4Flag ? 4 : 0, entryClut8Flag ? 8 : 0, value);
                  if (entryClut2Flag)
                     clut->SetColor(2, clutEntryId, value);
                  if (entryClut4Flag)
                     clut->SetColor(4, clutEntryId, value);
                  if (entryClut8Flag)
                     clut->SetColor(8, clutEntryId, value);
                  }
            dbgcluts("\n");
            break;
            }
       case OBJECT_DATA_SEGMENT: {
            dbgsegments("OBJECT_DATA_SEGMENT\n");
            cSubtitleObject *object = page->GetObjectById(bs.GetBits(16));
            if (!object)
               break;
            int objectVersion = bs.GetBits(4);
            if (objectVersion == object->Version())
               break; // no update
            object->SetVersion(objectVersion);
            int codingMethod = bs.GetBits(2);
            object->SetNonModifyingColorFlag(bs.GetBit());
            bs.SkipBit(); // reserved
            dbgobjects("Object pageId %d id %d version %d method %d modify %d\n", pageId, object->ObjectId(), object->Version(), object->CodingMethod(), object->NonModifyingColorFlag());
            if (codingMethod == 0) { // coding of pixels
               int topFieldLength = bs.GetBits(16);
               int bottomFieldLength = bs.GetBits(16);
               object->DecodeSubBlock(bs.GetData(), topFieldLength, true);
               if (bottomFieldLength)
                  object->DecodeSubBlock(bs.GetData() + topFieldLength, bottomFieldLength, false);
               else
                  object->DecodeSubBlock(bs.GetData(), topFieldLength, false);
               bs.WordAlign();
               }
            else if (codingMethod == 1) { // coded as a string of characters
               int numberOfCodes = bs.GetBits(8);
               object->DecodeCharacterString(bs.GetData(), numberOfCodes);
               }
#ifdef FINISHPAGE_HACK
            FinishPage(page); // flush to OSD right away
#endif
            break;
            }
       case DISPLAY_DEFINITION_SEGMENT: {
            dbgsegments("DISPLAY_DEFINITION_SEGMENT\n");
            int version = bs.GetBits(4);
            if (version != ddsVersionNumber) {
               bool displayWindowFlag = bs.GetBit();
               windowHorizontalOffset = 0;
               windowVerticalOffset   = 0;
               bs.SkipBits(3); // reserved
               displayWidth  = windowWidth  = bs.GetBits(16) + 1;
               displayHeight = windowHeight = bs.GetBits(16) + 1;
               if (displayWindowFlag) {
                  windowHorizontalOffset = bs.GetBits(16);                              // displayWindowHorizontalPositionMinimum
                  windowWidth            = bs.GetBits(16) - windowHorizontalOffset + 1; // displayWindowHorizontalPositionMaximum
                  windowVerticalOffset   = bs.GetBits(16);                              // displayWindowVerticalPositionMinimum
                  windowHeight           = bs.GetBits(16) - windowVerticalOffset + 1;   // displayWindowVerticalPositionMaximum
                  }
               SetOsdData();
               SetupChanged();
               ddsVersionNumber = version;
               }
            break;
            }
       case DISPARITY_SIGNALING_SEGMENT: {
            dbgsegments("DISPARITY_SIGNALING_SEGMENT\n");
            bs.SkipBits(4); // dss_version_number
            bool disparity_shift_update_sequence_page_flag = bs.GetBit();
            bs.SkipBits(3); // reserved
            bs.SkipBits(8); // page_default_disparity_shift
            if (disparity_shift_update_sequence_page_flag) {
               bs.SkipBits(8); // disparity_shift_update_sequence_length
               bs.SkipBits(24); // interval_duration[23..0]
               int division_period_count = bs.GetBits(8);
               for (int i = 0; i < division_period_count; ++i) {
                   bs.SkipBits(8); // interval_count
                   bs.SkipBits(8); // disparity_shift_update_integer_part
                   }
               }
            while (!bs.IsEOF()) {
                  bs.SkipBits(8); // region_id
                  bool disparity_shift_update_sequence_region_flag = bs.GetBit();
                  bs.SkipBits(5); // reserved
                  int number_of_subregions_minus_1 = bs.GetBits(2);
                  for (int i = 0; i <= number_of_subregions_minus_1; ++i) {
                      if (number_of_subregions_minus_1 > 0) {
                         bs.SkipBits(16); // subregion_horizontal_position
                         bs.SkipBits(16); // subregion_width
                         }
                      bs.SkipBits(8); // subregion_disparity_shift_integer_part
                      bs.SkipBits(4); // subregion_disparity_shift_fractional_part
                      bs.SkipBits(4); // reserved
                      if (disparity_shift_update_sequence_region_flag) {
                         bs.SkipBits(8); // disparity_shift_update_sequence_length
                         bs.SkipBits(24); // interval_duration[23..0]
                         int division_period_count = bs.GetBits(8);
                         for (int i = 0; i < division_period_count; ++i) {
                             bs.SkipBits(8); // interval_count
                             bs.SkipBits(8); // disparity_shift_update_integer_part
                             }
                         }
                      }
                  }
            break;
            }
       case END_OF_DISPLAY_SET_SEGMENT: {
            dbgsegments("END_OF_DISPLAY_SET_SEGMENT\n");
            FinishPage(page);
            break;
            }
       default:
            dbgsegments("*** unknown segment type: %02X\n", segmentType);
       }
     return bs.Length() / 8;
     }
  return -1;
}
Esempio n. 6
0
bool SmackerDecoder::loadStream(Common::SeekableReadStream *stream) {
	close();

	_fileStream = stream;

	// Read in the Smacker header
	_header.signature = _fileStream->readUint32BE();

	if (_header.signature != MKTAG('S', 'M', 'K', '2') && _header.signature != MKTAG('S', 'M', 'K', '4'))
		return false;

	uint32 width = _fileStream->readUint32LE();
	uint32 height = _fileStream->readUint32LE();
	uint32 frameCount = _fileStream->readUint32LE();
	int32 frameDelay = _fileStream->readSint32LE();

	// frame rate contains 2 digits after the comma, so 1497 is actually 14.97 fps
	Common::Rational frameRate;
	if (frameDelay > 0)
		frameRate = Common::Rational(1000, frameDelay);
	else if (frameDelay < 0)
		frameRate = Common::Rational(100000, -frameDelay);
	else
		frameRate = 1000;

	// Flags are determined by which bit is set, which can be one of the following:
	// 0 - set to 1 if file contains a ring frame.
	// 1 - set to 1 if file is Y-interlaced
	// 2 - set to 1 if file is Y-doubled
	// If bits 1 or 2 are set, the frame should be scaled to twice its height
	// before it is displayed.
	_header.flags = _fileStream->readUint32LE();

	SmackerVideoTrack *videoTrack = createVideoTrack(width, height, frameCount, frameRate, _header.flags, _header.signature);
	addTrack(videoTrack);

	// TODO: should we do any extra processing for Smacker files with ring frames?

	// TODO: should we do any extra processing for Y-doubled videos? Are they the
	// same as Y-interlaced videos?

	uint32 i;
	for (i = 0; i < 7; ++i)
		_header.audioSize[i] = _fileStream->readUint32LE();

	_header.treesSize = _fileStream->readUint32LE();
	_header.mMapSize = _fileStream->readUint32LE();
	_header.mClrSize = _fileStream->readUint32LE();
	_header.fullSize = _fileStream->readUint32LE();
	_header.typeSize = _fileStream->readUint32LE();

	for (i = 0; i < 7; ++i) {
		// AudioRate - Frequency and format information for each sound track, up to 7 audio tracks.
		// The 32 constituent bits have the following meaning:
		// * bit 31 - indicates Huffman + DPCM compression
		// * bit 30 - indicates that audio data is present for this track
		// * bit 29 - 1 = 16-bit audio; 0 = 8-bit audio
		// * bit 28 - 1 = stereo audio; 0 = mono audio
		// * bit 27 - indicates Bink RDFT compression
		// * bit 26 - indicates Bink DCT compression
		// * bits 25-24 - unused
		// * bits 23-0 - audio sample rate
		uint32 audioInfo = _fileStream->readUint32LE();
		_header.audioInfo[i].hasAudio = audioInfo & 0x40000000;
		_header.audioInfo[i].is16Bits = audioInfo & 0x20000000;
		_header.audioInfo[i].isStereo = audioInfo & 0x10000000;
		_header.audioInfo[i].sampleRate = audioInfo & 0xFFFFFF;

		if (audioInfo & 0x8000000)
			_header.audioInfo[i].compression = kCompressionRDFT;
		else if (audioInfo & 0x4000000)
			_header.audioInfo[i].compression = kCompressionDCT;
		else if (audioInfo & 0x80000000)
			_header.audioInfo[i].compression = kCompressionDPCM;
		else
			_header.audioInfo[i].compression = kCompressionNone;

		if (_header.audioInfo[i].hasAudio) {
			if (_header.audioInfo[i].compression == kCompressionRDFT || _header.audioInfo[i].compression == kCompressionDCT)
				warning("Unhandled Smacker v2 audio compression");

			if (i == 0)
				addTrack(new SmackerAudioTrack(_header.audioInfo[i], _soundType));
		}
	}

	_header.dummy = _fileStream->readUint32LE();

	_frameSizes = new uint32[frameCount];
	for (i = 0; i < frameCount; ++i)
		_frameSizes[i] = _fileStream->readUint32LE();

	_frameTypes = new byte[frameCount];
	for (i = 0; i < frameCount; ++i)
		_frameTypes[i] = _fileStream->readByte();

	byte *huffmanTrees = (byte *) malloc(_header.treesSize);
	_fileStream->read(huffmanTrees, _header.treesSize);

	Common::BitStream8LSB bs(new Common::MemoryReadStream(huffmanTrees, _header.treesSize, DisposeAfterUse::YES), true);
	videoTrack->readTrees(bs, _header.mMapSize, _header.mClrSize, _header.fullSize, _header.typeSize);

	_firstFrameStart = _fileStream->pos();

	return true;
}
static status_t parseAudioSpecificConfig(ABitReader *bits, sp<ABuffer> *asc) {
    const uint8_t *dataStart = bits->data();
    size_t totalNumBits = bits->numBitsLeft();

    unsigned audioObjectType;
    CHECK_EQ(parseAudioObjectType(bits, &audioObjectType), (status_t)OK);

    unsigned samplingFreqIndex = bits->getBits(4);
    if (samplingFreqIndex == 0x0f) {
        /* unsigned samplingFrequency = */bits->getBits(24);
    }

    unsigned channelConfiguration = bits->getBits(4);

    unsigned extensionAudioObjectType = 0;
    unsigned sbrPresent = 0;

    if (audioObjectType == 5) {
        extensionAudioObjectType = audioObjectType;
        sbrPresent = 1;
        unsigned extensionSamplingFreqIndex = bits->getBits(4);
        if (extensionSamplingFreqIndex == 0x0f) {
            /* unsigned extensionSamplingFrequency = */bits->getBits(24);
        }
        CHECK_EQ(parseAudioObjectType(bits, &audioObjectType), (status_t)OK);
    }

    CHECK((audioObjectType >= 1 && audioObjectType <= 4)
        || (audioObjectType >= 6 && audioObjectType <= 7)
        || audioObjectType == 17
        || (audioObjectType >= 19 && audioObjectType <= 23));

    CHECK_EQ(parseGASpecificConfig(
                bits, audioObjectType, channelConfiguration), (status_t)OK);

    if (audioObjectType == 17
            || (audioObjectType >= 19 && audioObjectType <= 27)) {
        unsigned epConfig = bits->getBits(2);
        if (epConfig == 2 || epConfig == 3) {
            // ErrorProtectionSpecificConfig
            return ERROR_UNSUPPORTED;  // XXX to be implemented

            if (epConfig == 3) {
                unsigned directMapping = bits->getBits(1);
                CHECK_EQ(directMapping, 1u);
            }
        }
    }

    if (extensionAudioObjectType != 5 && bits->numBitsLeft() >= 16) {
        size_t numBitsLeftAtStart = bits->numBitsLeft();

        unsigned syncExtensionType = bits->getBits(11);
        if (syncExtensionType == 0x2b7) {
            ALOGI("found syncExtension");

            CHECK_EQ(parseAudioObjectType(bits, &extensionAudioObjectType),
                     (status_t)OK);

            sbrPresent = bits->getBits(1);

            if (sbrPresent == 1) {
                unsigned extensionSamplingFreqIndex = bits->getBits(4);
                if (extensionSamplingFreqIndex == 0x0f) {
                    /* unsigned extensionSamplingFrequency = */bits->getBits(24);
                }
            }

            size_t numBitsInExtension =
                numBitsLeftAtStart - bits->numBitsLeft();

            if (numBitsInExtension & 7) {
                // Apparently an extension is always considered an even
                // multiple of 8 bits long.

                ALOGI("Skipping %d bits after sync extension",
                     8 - (numBitsInExtension & 7));

                bits->skipBits(8 - (numBitsInExtension & 7));
            }
        } else {
            bits->putBits(syncExtensionType, 11);
        }
    }

    if (asc != NULL) {
        size_t bitpos = totalNumBits & 7;

        ABitReader bs(dataStart, (totalNumBits + 7) / 8);

        totalNumBits -= bits->numBitsLeft();

        size_t numBytes = (totalNumBits + 7) / 8;

        *asc = new ABuffer(numBytes);

        if (bitpos & 7) {
            bs.skipBits(8 - (bitpos & 7));
        }

        uint8_t *dstPtr = (*asc)->data();
        while (numBytes > 0) {
            *dstPtr++ = bs.getBits(8);
            --numBytes;
        }
    }

    return OK;
}
Esempio n. 8
0
void mexFunction(
   int nlhs, mxArray *plhs[],
   int nrhs, const mxArray *prhs[])
{
  mwSize n, nn, i; /*nn is mxGetNumberOfElements, n and i derive from nn.*/
  double *V, *Vend, *temp; /*mxGetPr, V, mxGetPr*/
  double *sigma, *S, *k, *r, *d, *T; /*mxGetPr,...,mxGetPr*/
  int nsigma, nS,nk,nr,nd,nT,nput, nv, nd1; /*1 or 0*/
  bool *putflag; /*true*/

  /* Error checking on inputs */  
  if (nrhs<6) mexErrMsgTxt("Not enough input arguments.");
  if (nrhs>7) mexErrMsgTxt("Too many input arguments.");
  if (nlhs>2) mexErrMsgTxt("Too many output arguments.");
  for (i=0; i<nrhs; i++)
  {
    if (!mxIsDouble(prhs[i]) && !mxIsSparse(prhs[i]))
      mexErrMsgTxt("Function not defined for variables of input class");
    if (mxIsComplex(prhs[i]))
      mexErrMsgTxt("X must be real.");
  }

  sigma=mxGetPr(prhs[0]);
  S=mxGetPr(prhs[1]);
  k=mxGetPr(prhs[2]);
  r=mxGetPr(prhs[3]);
  d=mxGetPr(prhs[4]);
  T=mxGetPr(prhs[5]);

  n=1;
  nn=mxGetNumberOfElements(prhs[0]);

  if (n!=nn)
    if (n==1) {n=nn; plhs[0]=mxDuplicateArray(prhs[0]);}  
    else if (nn>1) mexErrMsgTxt("Inputs are not size compatible");
  if (nn>1) nsigma=1; else nsigma=0;

  nn=mxGetNumberOfElements(prhs[1]);
  if (n!=nn)
    if (n==1) {n=nn; plhs[0]=mxDuplicateArray(prhs[1]);}  
    else if (nn>1) mexErrMsgTxt("Inputs are not size compatible");
  if (nn>1) nS=1; else nS=0;
 
  nn=mxGetNumberOfElements(prhs[2]);
  if (n!=nn)
    if (n==1) {n=nn; plhs[0]=mxDuplicateArray(prhs[2]);}  
    else if (nn>1) mexErrMsgTxt("Inputs are not size compatible");
  if (nn>1) nk=1; else nk=0;

  nn=mxGetNumberOfElements(prhs[3]);
  if (n!=nn)
    if (n==1) {n=nn; plhs[0]=mxDuplicateArray(prhs[3]);}  
    else if (nn>1) mexErrMsgTxt("Inputs are not size compatible");
  if (nn>1) nr=1; else nr=0;

  nn=mxGetNumberOfElements(prhs[4]);
  if (n!=nn)
    if (n==1)  {n=nn; plhs[0]=mxDuplicateArray(prhs[4]);} 
    else if (nn>1) mexErrMsgTxt("Inputs are not size compatible");
  if (nn>1) nd=1; else nd=0;

  nn=mxGetNumberOfElements(prhs[5]);
  if (n!=nn)
    if (n==1)  {n=nn; plhs[0]=mxDuplicateArray(prhs[5]);} 
    else if (nn>1) mexErrMsgTxt("Inputs are not size compatible");
  if (nn>1) nT=1; else nT=0;
    
  if (nrhs<7) {putflag=mxCalloc(1,sizeof(bool)); *putflag=false; nput=0;}
  else
  {
    nn=mxGetNumberOfElements(prhs[6]);
    if (n!=nn)
      if (n==1) {n=nn; plhs[0]=mxDuplicateArray(prhs[6]);}
      else if (nn>1) mexErrMsgTxt("Inputs are not size compatible");
    if (nn>1) nput=1; else nput=0;
    putflag=mxCalloc(nn,sizeof(bool));   
    temp=mxGetPr(prhs[6]);
    for (i=0;i<nn;i++)
      if (temp[i]==1) putflag[i]=true; else putflag[i]=false;
  }

  if (n==1) plhs[0]=mxCreateDoubleMatrix(1,1,mxREAL);

  V=mxGetPr(plhs[0]);
  Vend=V+n;
  for (;V<Vend;V++)
  {
    *V=bs(*sigma,*S,*k,*r,*d,*T,*putflag);
    sigma+=nsigma;
    S+=nS;
    k+=nk;
    r+=nr;
    d+=nd;
    T+=nT;
    putflag+=nput;
  }
}
Esempio n. 9
0
int main(int argc, char* argv[])
{
  BoxLib::Initialize(argc,argv);

  BL_PROFILE_VAR("main()", pmain);

  std::cout << std::setprecision(15);

  solver_type = BoxLib_C;
  bc_type = Periodic;

  Real     a = 0.0;
  Real     b = 1.0;

  // ---- First use the number of processors to decide how many grids you have.
  // ---- We arbitrarily decide to have one grid per MPI process in a uniform
  // ---- cubic domain, so we require that the number of processors be N^3.
  // ---- This requirement is somewhat arbitrary, but convenient for now.

  int nprocs = ParallelDescriptor::NProcs();

  // N is the cube root of the number of processors
  int N(0);
  for(int i(1); i*i*i <= nprocs; ++i) {
    if(i*i*i == nprocs) {
      N = i;
    }
  }

  if(N == 0) {  // not a cube
    if(ParallelDescriptor::IOProcessor()) {
      std::cerr << "**** Error:  nprocs = " << nprocs << " is not currently supported." << std::endl;
    }
    BoxLib::Error("We require that the number of processors be a perfect cube");
  }
  if(ParallelDescriptor::IOProcessor()) {
    std::cout << "N = " << N << std::endl;
  }


  // ---- make a box, then a boxarray with maxSize
  int domain_hi = (N*maxGrid) - 1;
  Box domain(IntVect(0,0,0), IntVect(domain_hi,domain_hi,domain_hi));
  BoxArray bs(domain);
  bs.maxSize(maxGrid);

  // This defines the physical size of the box.  Right now the box is [0,1] in each direction.
  RealBox real_box;
  for (int n = 0; n < BL_SPACEDIM; n++) {
    real_box.setLo(n, 0.0);
    real_box.setHi(n, 1.0);
  }
 
  // This says we are using Cartesian coordinates
  int coord = 0;
  
  // This sets the boundary conditions to be periodic or not
  int is_per[BL_SPACEDIM];
  
  if (bc_type == Dirichlet || bc_type == Neumann) {
    for (int n = 0; n < BL_SPACEDIM; n++) is_per[n] = 0;
  } 
  else {
    for (int n = 0; n < BL_SPACEDIM; n++) is_per[n] = 1;
  }
 
  // This defines a Geometry object which is useful for writing the plotfiles
  Geometry geom(domain,&real_box,coord,is_per);

  for ( int n=0; n<BL_SPACEDIM; n++ ) {
    dx[n] = ( geom.ProbHi(n) - geom.ProbLo(n) )/domain.length(n);
  }

  if (ParallelDescriptor::IOProcessor()) {
     std::cout << "Domain size     : " << N << std::endl;
     std::cout << "Max_grid_size   : " << maxGrid << std::endl;
     std::cout << "Number of grids : " << bs.size() << std::endl;
  }

  // Allocate and define the right hand side.
  MultiFab rhs(bs, Ncomp, 0, Fab_allocate); 
  setup_rhs(rhs, geom, a, b);

  MultiFab alpha(bs, Ncomp, 0, Fab_allocate);
  MultiFab beta[BL_SPACEDIM];
  for ( int n=0; n<BL_SPACEDIM; ++n ) {
    BoxArray bx(bs);
    beta[n].define(bx.surroundingNodes(n), Ncomp, 1, Fab_allocate);
  }

  setup_coeffs(bs, alpha, beta, geom);

  MultiFab anaSoln;
  if (comp_norm) {
    anaSoln.define(bs, Ncomp, 0, Fab_allocate);
    compute_analyticSolution(anaSoln);
  }

  // Allocate the solution array 
  // Set the number of ghost cells in the solution array.
  MultiFab soln(bs, Ncomp, 1, Fab_allocate);

  solve(soln, anaSoln, a, b, alpha, beta, rhs, bs, geom, BoxLib_C);

  BL_PROFILE_VAR_STOP(pmain);

  BoxLib::Finalize();
}
Esempio n. 10
0
int arithmetic_decoding(const char* encoded_file, const char* decoded_file)
{
    FILE* fout;
    uint8_t byte;
    int i;
    int i_ss;
    int i_d;
    int n;
    int bitc = 0;
    uint64_t tmp, mask, stream_slice;
    int bits_to_read;
    struct CST* cumulative_sums_tree_pointer;

    struct BitBuffer* bbp = bit_open(encoded_file, BIT_BUFFER_READ);
    if (bbp == NULL)
    {
	printf("%s: No such file\n", encoded_file);
	return -1;
    }

    cumulative_sums_tree_pointer = CST_create(NUM_CODEPOINTS);
    if (cumulative_sums_tree_pointer == NULL)
    {
	printf("Error: CST creation failed\n");
	bit_close(bbp);
	return -1;
    }

    fout = fopen(decoded_file, "wb");
    if (fout == NULL)
    {
	printf("Error: cannot create output file %s\n", decoded_file);
	return -1;
    }

    // we deal with the zero-frequency problem initializing all counters to 1 and consequently NUM_CODEPOINTS to total_count
    total_count = NUM_CODEPOINTS;
    for (i=1; i<NUM_CODEPOINTS; i++)
	counter_increment(cumulative_sums_tree_pointer, i);

    LOW = 0;
    HIGH = 0xFFFFFFFFFFFFFFFF;
    bits_to_read = sizeof(uint64_t) * 8;
    stream_slice = 0x0000000000000000;
    for (;;)
    {
	n = bit_read(bbp, &tmp, bits_to_read);
	if (n == -1)
	{
	    printf("Error occurred!!\n");
	    return -1;
	}
	// here n could be zero, but this is not a concern
	bitc+=n;

	if (bits_to_read == sizeof(uint64_t) * 8)
	    mask = 0xFFFFFFFFFFFFFFFF;
	else
	    mask = ((uint64_t)1 << bits_to_read) - 1;
	stream_slice = ((stream_slice << bits_to_read) | (tmp & mask));
	/*
	   i = 0;
	   mask = 0x0000000000000001;
	   while (i < bits_to_read)
	   {
	   stream_slice <<= 1;
	   if (tmp & mask)
	   stream_slice |= 0x0000000000000001;
	   mask <<= 1;
	   i++;
	   } */

	n = bs(cumulative_sums_tree_pointer, stream_slice);
	if (n == -1)
	    return -1;
	if (n == NUM_CODEPOINTS - 1)  // EOF symbol received
	    break;
	byte = (uint8_t)n;
	fwrite(&byte, 1, 1, fout);

	tmp = ((HIGH - LOW) / total_count);
	HIGH = LOW + tmp * (cumulative_sums_lookup(cumulative_sums_tree_pointer, byte + 1));
	LOW = LOW + tmp * cumulative_sums_lookup(cumulative_sums_tree_pointer, byte);

	// deadlock resolution
	if ((HIGH & 0xC000000000000000) == 0x8000000000000000 && (LOW & 0xC000000000000000) == 0x4000000000000000)
	{
	    i_d = 2;
	    mask = 0x2000000000000000;
	    while (mask && (LOW & mask) && (HIGH & mask) == 0)
	    {
		i_d++;
		mask >>= 1;
	    }
	    LOW &= ~mask;
	    HIGH |= mask;
	    HIGH <<= i_d;
	    LOW <<= i_d;
	}
	else
Esempio n. 11
0
ezQtShortcutEditorDlg::ezQtShortcutEditorDlg(QWidget* parent)
    : QDialog(parent)
{
  setupUi(this);

  EZ_VERIFY(connect(Shortcuts, SIGNAL(itemSelectionChanged()), this, SLOT(SlotSelectionChanged())) != nullptr,
            "signal/slot connection failed");

  m_iSelectedAction = -1;
  KeyEditor->setEnabled(false);

  ezMap<ezString, ezMap<ezString, ezInt32>> SortedItems;

  {
    auto itActions = ezActionManager::GetActionIterator();

    while (itActions.IsValid())
    {
      if (itActions.Value()->m_Type == ezActionType::Action)
      {
        SortedItems[itActions.Value()->m_sCategoryPath][itActions.Value()->m_sActionName] = m_ActionDescs.GetCount();
        m_ActionDescs.PushBack(itActions.Value());
      }

      itActions.Next();
    }
  }

  {
    ezQtScopedBlockSignals bs(Shortcuts);
    ezQtScopedUpdatesDisabled ud(Shortcuts);

    Shortcuts->setAlternatingRowColors(true);
    Shortcuts->setEditTriggers(QAbstractItemView::EditTrigger::NoEditTriggers);
    Shortcuts->setExpandsOnDoubleClick(true);

    ezStringBuilder sTemp;

    for (auto it = SortedItems.GetIterator(); it.IsValid(); ++it)
    {
      auto pParent = new QTreeWidgetItem();
      pParent->setData(0, Qt::DisplayRole, it.Key().GetData());
      Shortcuts->addTopLevelItem(pParent);

      pParent->setExpanded(true);
      pParent->setFirstColumnSpanned(true);
      pParent->setFlags(Qt::ItemFlag::ItemIsEnabled);

      QFont font = pParent->font(0);
      font.setBold(true);

      pParent->setFont(0, font);

      for (auto it2 : it.Value())
      {
        const auto& item = m_ActionDescs[it2.Value()];
        auto pItem = new QTreeWidgetItem(pParent);

        /// \todo Instead of removing &, replace it by underlined text (requires formatted text output)
        sTemp = ezTranslate(item->m_sActionName);
        sTemp.ReplaceAll("&", "");

        pItem->setData(0, Qt::UserRole, it2.Value());
        pItem->setData(0, Qt::DisplayRole, item->m_sActionName.GetData());
        pItem->setData(1, Qt::DisplayRole, sTemp.GetData());
        pItem->setData(2, Qt::DisplayRole, item->m_sShortcut.GetData());
        pItem->setData(3, Qt::DisplayRole, ezTranslateTooltip(item->m_sActionName));

        if (item->m_sShortcut == item->m_sDefaultShortcut)
          pItem->setBackground(2, QBrush());
        else
          pItem->setBackgroundColor(2, Qt::darkYellow);

        sTemp.Set("Default: ", item->m_sDefaultShortcut.IsEmpty() ? "<none>" : item->m_sDefaultShortcut);

        pItem->setToolTip(2, QString::fromUtf8(sTemp.GetData()));
      }
    }

    Shortcuts->resizeColumnToContents(0);
    Shortcuts->resizeColumnToContents(2);
  }

  ButtonAssign->setEnabled(false);
  ButtonRemove->setEnabled(false);
  ButtonReset->setEnabled(false);
}
    int search(int A[], int n, int target) {

        return bs(A,0,n-1,target);
    }
Esempio n. 13
0
void Office::draw()
{
    float x,y;
    x=posx;
    y=posy;
    float size = 0.39f;
    glm::vec3 a(x+size,y+size,0);
    glm::vec3 b(x-size,y+size,0);
    glm::vec3 c(x-size,y-size,0);
    glm::vec3 d(x+size,y-size,0);
    float height = 1.9f;
    glm::vec3 as(x+size,y+size,height);
    glm::vec3 bs(x-size,y+size,height);
    glm::vec3 cs(x-size,y-size,height);
    glm::vec3 ds(x+size,y-size,height);

glBindTexture(GL_TEXTURE_2D,tex->getTexture("roof"));
    glBegin(GL_QUADS);



    glTexCoord2f(0,1);
    glVertex3f(as.x,as.y,as.z);
    glTexCoord2f(0,0);
    glVertex3f(bs.x,bs.y,bs.z);
    glTexCoord2f(1,0);
    glVertex3f(cs.x,cs.y,cs.z);
    glTexCoord2f(1,1);
    glVertex3f(ds.x,ds.y,ds.z);
    glEnd();

glBindTexture(GL_TEXTURE_2D,tex->getTexture("wall"));

glBegin(GL_QUADS);

    glTexCoord2f(0,1);
    glVertex3f(as.x,as.y,as.z);
    glTexCoord2f(1,1);
    glVertex3f(bs.x,bs.y,bs.z);
    glTexCoord2f(1,0);
    glVertex3f(b.x,b.y,b.z);
    glTexCoord2f(0,0);
    glVertex3f(a.x,a.y,a.z);


    glTexCoord2f(0,1);
    glVertex3f(bs.x,bs.y,bs.z);
    glTexCoord2f(1,1);
    glVertex3f(cs.x,cs.y,cs.z);
    glTexCoord2f(1,0);
    glVertex3f(c.x,c.y,c.z);
    glTexCoord2f(0,0);
    glVertex3f(b.x,b.y,b.z);

    glTexCoord2f(0,1);
    glVertex3f(cs.x,cs.y,cs.z);
    glTexCoord2f(1,1);
    glVertex3f(ds.x,ds.y,ds.z);
    glTexCoord2f(1,0);
    glVertex3f(d.x,d.y,d.z);
    glTexCoord2f(0,0);
    glVertex3f(c.x,c.y,c.z);


    glTexCoord2f(0,1);
    glVertex3f(ds.x,ds.y,ds.z);
    glTexCoord2f(1,1);
    glVertex3f(as.x,as.y,as.z);
    glTexCoord2f(1,0);
    glVertex3f(a.x,a.y,a.z);
    glTexCoord2f(0,0);
    glVertex3f(d.x,d.y,d.z);



    glEnd();
}
Esempio n. 14
0
chat()
{
int c,kh,ch,x,y;

c=0;
ch=0;
kh=0;
put_char(12);
print("-*[ Force Ten Chat ]*-  %s Chatting with %s #%d",config.sysop,user.name,user.number);
nl();
nl();
nl();
if(!useron)
	{
	nl();
	pl(">>> No user on-line");
	nl();
	}
comm_flush();
while(1)
	{
	if(kbhit())
		{
		kh=1;
		c=getch();
		if(c==0)
			{
			c=getch();
			if(c==68)
				return;
			}
/*		if(c==F1)
			{
			curr_cursor(&x,&y);
			c=kh=0;
			pullmenu();
			cursor(x,y);
			}*/
		if(c==13)
			{
			nl();
			kh=c=0;
			}
		if(c==8)
			{
			bs();
			kh=c=0;
			}
		}
	if(comm_avail())
		{
		ch=1;
		c=comm_getc(1);
		if(c==13)
			{
			nl();
			ch=c=0;
			}
		if(c==8)
			{
			bs();
			ch=c=0;
			}
		}
	if(ch || kh)
		{
		if(kh)
			ansic(1);
		else
			ansic(2);
		ch=kh=0;
		put_char(c);
		}
	}
}
Esempio n. 15
0
double BFGS (
	     Vector & x,         // i: Startwert
	     // o: Loesung, falls IFAIL = 0
	     const MinFunction & fun,
	     const OptiParameters & par,
	     double eps
	     )


{
  int i, j, n = x.Size();
  long it;
  char a1crit, a3acrit;


  Vector d(n), g(n), p(n), temp(n), bs(n), xneu(n), y(n), s(n), x0(n);
  DenseMatrix l(n);
  DenseMatrix hesse(n);

  double /* normg, */ alphahat, hd, fold;
  double a1, a2;
  const double mu1 = 0.1, sigma = 0.1, xi1 = 1, xi2 = 10;
  const double tau = 0.1, tau1 = 0.1, tau2 = 0.6;

  Vector typx(x.Size());      // i: typische Groessenordnung der Komponenten
  double f, f0;
  double typf;               // i: typische Groessenordnung der Loesung
  double fmin = -1e5;           // i: untere Schranke fuer Funktionswert
  //  double eps = 1e-8;            // i: Abbruchschranke fuer relativen Gradienten
  double tauf = 0.1;            // i: Abbruchschranke fuer die relative Aenderung der
                                //    Funktionswerte
  int ifail;                    // o:  0 .. Erfolg
                                //    -1 .. Unterschreitung von fmin
                                //     1 .. kein Erfolg bei Liniensuche
                                //     2 .. Überschreitung von itmax

  typx = par.typx;
  typf = par.typf;


  l = 0;
  for (i = 1; i <= n; i++)
    l.Elem(i, i) = 1;

  f = fun.FuncGrad (x, g);
  f0 = f;
  x0 = x;

  it = 0;
  do
    {
      // Restart

      if (it % (5 * n) == 0)
	{

	  for (i = 1; i <= n; i++)
	    d.Elem(i) = typf/ sqr (typx.Get(i));   // 1;
	  for (i = 2; i <= n; i++)
	    for (j = 1; j < i; j++)
	      l.Elem(i, j) = 0;

	  /*
	  hesse = 0;
	  for (i = 1; i <= n; i++)
	    hesse.Elem(i, i) = typf / sqr (typx.Get(i));  

	  fun.ApproximateHesse (x, hesse);

	  Cholesky (hesse, l, d);
	  */
	}

      it++;
      if (it > par.maxit_bfgs)
	{
	  ifail = 2;
	  break;
	}


      // Solve with factorized B

      SolveLDLt (l, d, g, p);

 //      (*testout) << "l " << l << endl
// 		 << "d " << d << endl
// 		 << "g " << g << endl
// 		 << "p " << p << endl;


      p *= -1;
      y = g;

      fold = f;

      // line search


      alphahat = 1;
      lines (x, xneu, p, f, g, fun, par, alphahat, fmin,
	     mu1, sigma, xi1, xi2, tau, tau1, tau2, ifail);

      if(ifail == 1)
	(*testout) << "no success with linesearch" << endl;

       /*
      // if (it > par.maxit_bfgs/2)
	{
	  (*testout) << "x = " << x << endl;
	  (*testout) << "xneu = " << xneu << endl;
	  (*testout) << "f = " << f << endl;
	  (*testout) << "g = " << g << endl;
	}
      */

      //      (*testout) << "it = " << it << " f = " << f << endl;
      //      if (ifail != 0) break;

      s.Set2 (1, xneu, -1, x);
      y *= -1;
      y.Add (1,g); // y += g;

      x = xneu;

      // BFGS Update

      MultLDLt (l, d, s, bs);

      a1 = y * s;
      a2 = s * bs;

      if (a1 > 0 && a2 > 0)
	{
	  if (LDLtUpdate (l, d, 1 / a1, y) != 0)
	    {
	      // [JW] according to [JS] we can safely ignore this error
	      //cerr << "BFGS update error1" << endl;
	      //(*testout) << "BFGS update error1" << endl;
	      //(*testout) << "l " << endl << l << endl
			 //<< "d " << d << endl;
	      ifail = 1;
	      break;
	    }

	  if (LDLtUpdate (l, d, -1 / a2, bs) != 0)
	    {
	      // [JW] according to [JS] we can safely ignore this error	    
	      //cerr << "BFGS update error2" << endl;
	      //(*testout) << "BFGS update error2" << endl;
	      //(*testout) << "l " << endl << l << endl
			// << "d " << d << endl;
	      ifail = 1;
	      break;
	    }
	}

      // Calculate stop conditions

      hd = eps * max2 (typf, fabs (f));
      a1crit = 1;
      for (i = 1; i <= n; i++)
	if ( fabs (g.Elem(i)) * max2 (typx.Elem(i), fabs (x.Elem(i))) > hd)
	  a1crit = 0;


      a3acrit = (fold - f <= tauf * max2 (typf, fabs (f)));

      //    testout << "g = " << g << endl;
      //    testout << "a1crit, a3crit = " << int(a1crit) << ", " << int(a3acrit) << endl;

      /*
	// Output for tests

	normg = sqrt (g * g);

	testout << "it =" << setw (5) << it
	<< " f =" << setw (12) << setprecision (5) << f
	<< " |g| =" << setw (12) << setprecision (5) << normg;

	testout << " x = (" << setw (12) << setprecision (5) << x.Elem(1);
	for (i = 2; i <= n; i++)
	testout << "," << setw (12) << setprecision (5) << x.Elem(i);
	testout << ")" << endl;
	*/

      //(*testout) << "it = " << it << " f = " << f << " x = " << x << endl
      //	 << " g = " << g << " p = " << p << endl << endl;

      //      (*testout) << "|g| = " << g.L2Norm() << endl;

      if (g.L2Norm() < fun.GradStopping (x)) break;

    }
  while (!a1crit || !a3acrit);

  /*
  (*testout) << "it = " << it << " g = " << g << " f = " << f 
	     << " fail = " << ifail << endl;
  */
  if (f0 < f || (ifail == 1))
    {
      (*testout) << "fail, f = " << f << " f0 = " << f0 << endl;
      f = f0;
      x = x0;
    }

  //  (*testout) << "x = " << x << ", x0 = " << x0 << endl;
  return f;
}
Esempio n. 16
0
void HifiClientProcessList::clientCatchup(GameConnection * connection)
{
#ifdef TORQUE_DEBUG_NET_MOVES
   Con::printf("client catching up... (%i)%s", mCatchup, mForceHifiReset ? " reset" : "");
#endif

   if (connection->getControlObject() && connection->getControlObject()->isGhostUpdated())
      // if control object is reset, make sure moves are reset too
      connection->mMoveList->resetCatchup();

   const F32 maxVel = mSqrt(gMaxHiFiVelSq) * 1.25f;
   F32 dt = F32(mCatchup+1) * TickSec;
   Point3F bigDelta(maxVel*dt,maxVel*dt,maxVel*dt);

   // walk through all process objects looking for ones which were updated
   // -- during first pass merely collect neighbors which need to be reset and updated in unison
   ProcessObject * pobj;
   if (mCatchup && !mForceHifiReset)
   {
      for (pobj = mHead.mProcessLink.next; pobj != &mHead; pobj = pobj->mProcessLink.next)
      {
         GameBase *obj = getGameBase( pobj );
         static SimpleQueryList nearby;
         nearby.mList.clear();
         // check for nearby objects which need to be reset and then caught up
         // note the funky loop logic -- first time through obj is us, then
         // we start iterating through nearby list (to look for objects nearby
         // the nearby objects), which is why index starts at -1
         // [objects nearby the nearby objects also get added to the nearby list]
         for (S32 i=-1; obj; obj = ++i<nearby.mList.size() ? (GameBase*)nearby.mList[i] : NULL)
         {
            if (obj->isGhostUpdated() && (obj->getTypeMask() & GameBaseHiFiObjectType) && !obj->isNetNearbyAdded())
            {
               Point3F start = obj->getWorldSphere().center;
               Point3F end = start + 1.1f * dt * obj->getVelocity();
               F32 rad = 1.5f * obj->getWorldSphere().radius;

               // find nearby items not updated but are hi fi, mark them as updated (and restore old loc)
               // check to see if added items have neighbors that need updating
               Box3F box;
               Point3F rads(rad,rad,rad);
               box.minExtents = box.maxExtents = start;
               box.minExtents -= bigDelta + rads;
               box.maxExtents += bigDelta + rads;

               // CodeReview - this is left in for MBU, but also so we can deal with the issue later.
               // add marble blast hack so hifi networking can see hidden objects
               // (since hidden is under control of hifi networking)
               //  gForceNotHidden = true;

               S32 j = nearby.mList.size();
               gClientContainer.findObjects(box, GameBaseHiFiObjectType, SimpleQueryList::insertionCallback, &nearby);

               // CodeReview - this is left in for MBU, but also so we can deal with the issue later.
               // disable above hack
               //  gForceNotHidden = false;

               // drop anyone not heading toward us or already checked
               for (; j<nearby.mList.size(); j++)
               {
                  GameBase * obj2 = (GameBase*)nearby.mList[j];
                  // if both passive, these guys don't interact with each other
                  bool passive = obj->isHifiPassive() && obj2->isHifiPassive();
                  if (!obj2->isGhostUpdated() && !passive)
                  {
                     // compare swept spheres of obj and obj2
                     // if collide, reset obj2, setGhostUpdated(true), and continue
                     Point3F end2 = obj2->getWorldSphere().center;
                     Point3F start2 = end2 - 1.1f * dt * obj2->getVelocity();
                     F32 rad2 = 1.5f * obj->getWorldSphere().radius;
                     if (MathUtils::capsuleCapsuleOverlap(start,end,rad,start2,end2,rad2))
                     {
                        // better add obj2
                        obj2->getTickCache().beginCacheList();
                        TickCacheEntry * tce = obj2->getTickCache().incCacheList();
                        BitStream bs(tce->packetData,TickCacheEntry::MaxPacketSize);
                        obj2->readPacketData(connection,&bs);
                        obj2->setGhostUpdated(true);

                        // continue so we later add the neighbors too
                        continue;
                     }

                  }

                  // didn't pass above test...so don't add it or nearby objects
                  nearby.mList[j] = nearby.mList.last();
                  nearby.mList.decrement();
                  j--;
               }
               obj->setNetNearbyAdded(true);
            }
         }
      }
   }

   // save water mark -- for game base list
   FrameAllocatorMarker mark;

   // build ordered list of client objects which need to be caught up
   GameBaseListNode list;
   for (pobj = mHead.mProcessLink.next; pobj != &mHead; pobj = pobj->mProcessLink.next)
   {
      GameBase *obj = getGameBase( pobj );
      //GameBase *obj = dynamic_cast<GameBase*>( pobj );
      //GameBase *obj = (GameBase*)pobj;

      // Not a GameBase object so nothing to do.
      if ( !obj )
         continue;

      if (obj->isGhostUpdated() && (obj->getTypeMask() & GameBaseHiFiObjectType))
      {
         // construct process object and add it to the list
         // hold pointer to our object in mAfterObject
         GameBaseListNode * po = (GameBaseListNode*)FrameAllocator::alloc(sizeof(GameBaseListNode));
         po->mObject = obj;
         po->linkBefore(&list);

         // begin iterating through tick list (skip first tick since that is the state we've been reset to)
         obj->getTickCache().beginCacheList();
         obj->getTickCache().incCacheList();
      }
      else if (mForceHifiReset && (obj->getTypeMask() & GameBaseHiFiObjectType))
      {
         // add all hifi objects
         obj->getTickCache().beginCacheList();
         TickCacheEntry * tce = obj->getTickCache().incCacheList();
         BitStream bs(tce->packetData,TickCacheEntry::MaxPacketSize);
         obj->readPacketData(connection,&bs);
         obj->setGhostUpdated(true);

         // construct process object and add it to the list
         // hold pointer to our object in mAfterObject
         GameBaseListNode * po = (GameBaseListNode*)FrameAllocator::alloc(sizeof(GameBaseListNode));
         po->mObject = obj;
         po->linkBefore(&list);
      }
      else if (obj == connection->getControlObject() && obj->isGhostUpdated())
      {
         // construct process object and add it to the list
         // hold pointer to our object in mAfterObject
         // .. but this is not a hi fi object, so don't mess with tick cache
         GameBaseListNode * po = (GameBaseListNode*)FrameAllocator::alloc(sizeof(GameBaseListNode));
         po->mObject = obj;
         po->linkBefore(&list);
      }
      else if (obj->isGhostUpdated())
      {
         // not hifi but we were updated, so perform net smooth now
         obj->computeNetSmooth(mLastDelta);
      }

      // clear out work flags
      obj->setNetNearbyAdded(false);
      obj->setGhostUpdated(false);
   }

   // run through all the moves in the move list so we can play them with our control object
   Move* movePtr;
   U32 numMoves;
   connection->mMoveList->resetClientMoves();
   connection->mMoveList->getMoves(&movePtr, &numMoves);
   AssertFatal(mCatchup<=numMoves,"doh");

   // tick catchup time
   for (U32 m=0; m<mCatchup; m++)
   {
      for (GameBaseListNode * walk = list.mNext; walk != &list; walk = walk->mNext)
      {
         // note that we get object from after object not getGameBase function
         // this is because we are an on the fly linked list which uses mAfterObject
         // rather than the linked list embedded in GameBase (clean this up?)
         GameBase * obj = walk->mObject;

         // it's possible for a non-hifi object to get in here, but
         // only if it is a control object...make sure we don't do any
         // of the tick cache stuff if we are not hifi.
         bool hifi = obj->getTypeMask() & GameBaseHiFiObjectType;
         TickCacheEntry * tce = hifi ? obj->getTickCache().incCacheList() : NULL;

         // tick object
         if (obj==connection->getControlObject())
         {
            obj->processTick(movePtr);
            movePtr->checksum = obj->getPacketDataChecksum(connection);
            movePtr++;
         }
         else
         {
            AssertFatal(tce && hifi,"Should not get in here unless a hi fi object!!!");
            obj->processTick(tce->move);
         }

         if (hifi)
         {
            BitStream bs(tce->packetData,TickCacheEntry::MaxPacketSize);
            obj->writePacketData(connection,&bs);
         }
      }
      if (connection->getControlObject() == NULL)
         movePtr++;
   }
   connection->mMoveList->clearMoves(mCatchup);

   // Handle network error smoothing here...but only for control object
   GameBase * control = connection->getControlObject();
   if (control && !control->isNewGhost())
   {
      control->computeNetSmooth(mLastDelta);
      control->setNewGhost(false);
   }

   if (moveSync.doAction() && moveSync.moveDiff>0)
   {
      S32 moveDiff = moveSync.moveDiff;
#ifdef TORQUE_DEBUG_NET_MOVES
      Con::printf("client timewarping to catchup %i moves",moveDiff);
#endif
      while (moveDiff--)
         advanceObjects();
      moveSync.reset();
   }

#ifdef TORQUE_DEBUG_NET_MOVES
   Con::printf("---------");
#endif

   // all caught up
   mCatchup = 0;
}
Esempio n. 17
0
int main(int argc, char *argv[])
{
	int opt = 0;
	dtn::data::EID _destination;
	std::string _source = "stream";
	int _priority = 1;
	unsigned int _lifetime = 30;
	unsigned int _receive_timeout = 0;

	size_t _min_chunk_size = 4096;
	size_t _max_chunk_size = 512000;

	dtn::data::EID _group;
	bool _bundle_encryption = false;
	bool _bundle_signed = false;
	bool _bundle_group = false;
	bool _wait_seq_zero = false;
	bool _flow_control = false;
	ibrcommon::File _unixdomain;

	while((opt = getopt(argc, argv, "hg:Gd:t:s:c:C:p:l:ESU:wf")) != -1)
	{
		switch (opt)
		{
		case 'h':
			print_help();
			return 0;

		case 'd':
			_destination = std::string(optarg);
			break;

		case 'g':
			_group = std::string(optarg);
			break;

		case 'G':
			_bundle_group = true;
			break;

		case 's':
			_source = optarg;
			break;

		case 'c':
			_min_chunk_size = atoi(optarg);
			break;

		case 'C':
			_max_chunk_size = atoi(optarg);
			break;

		case 't':
			_receive_timeout = atoi(optarg);
			break;

		case 'p':
			_priority = atoi(optarg);
			break;

		case 'l':
			_lifetime = atoi(optarg);
			break;

		case 'E':
			_bundle_encryption = true;
			break;

		case 'S':
			_bundle_signed = true;
			break;

		case 'U':
			_unixdomain = ibrcommon::File(optarg);
			break;

		case 'w':
			_wait_seq_zero = true;
			break;

		case 'f':
			_flow_control = true;
			break;

		default:
			std::cout << "unknown command" << std::endl;
			return -1;
		}
	}

	try {
		// Create a stream to the server using TCP.
		ibrcommon::clientsocket *sock = NULL;

		// check if the unixdomain socket exists
		if (_unixdomain.exists())
		{
			// connect to the unix domain socket
			sock = new ibrcommon::filesocket(_unixdomain);
		}
		else
		{
			// connect to the standard local api port
			ibrcommon::vaddress addr("localhost", 4550);
			sock = new ibrcommon::tcpsocket(addr);
		}

		ibrcommon::socketstream conn(sock);

		// Initiate a derivated client
		BundleStream bs(conn, _min_chunk_size, _max_chunk_size, _source, _group, _wait_seq_zero);

		// set flow-control as requested
		bs.setAutoFlush(_flow_control);

		// set the receive timeout
		bs.setReceiveTimeout(_receive_timeout);

		// Connect to the server. Actually, this function initiate the
		// stream protocol by starting the thread and sending the contact header.
		bs.connect();

		// transmitter mode
		if (_destination != dtn::data::EID())
		{
			bs.base().destination = _destination;
			bs.base().setPriority(dtn::data::PrimaryBlock::PRIORITY(_priority));
			bs.base().lifetime = _lifetime;
			if (_bundle_encryption) bs.base().set(dtn::data::PrimaryBlock::DTNSEC_REQUEST_ENCRYPT, true);
			if (_bundle_signed) bs.base().set(dtn::data::PrimaryBlock::DTNSEC_REQUEST_SIGN, true);
			if (_bundle_group) bs.base().set(dtn::data::PrimaryBlock::DESTINATION_IS_SINGLETON, false);
			std::ostream stream(&bs.rdbuf());
			stream << std::cin.rdbuf() << std::flush;
		}
		// receiver mode
		else
		{
			std::istream stream(&bs.rdbuf());
			std::cout << stream.rdbuf() << std::flush;
		}

		// Shutdown the client connection.
		bs.close();
		conn.close();
	} catch (const ibrcommon::socket_exception&) {
		std::cerr << "Can not connect to the daemon. Does it run?" << std::endl;
		return -1;
	} catch (const std::exception&) {

	}
}
Esempio n. 18
0
Dialog::Dialog(UmlArtifact * art, const Q3CString & path_exe, Q3CString & pro, Q3CString & target, Q3CString & tmplt, Q3CString & config, Q3CString & defines, Q3CString & includepath, Q3CString & dependpath, Q3CString & objectsdir, Q3CString & footer)
    : QDialog(0, 0, TRUE), _art(art), _pro(pro), _target(target), _tmplt(tmplt),
      _config(config), _defines(defines), _includepath(includepath), _dependpath(dependpath),
      _objectsdir(objectsdir), _footer(footer)
{
    QDir d(path_exe);
    Q3VBoxLayout * vbox = new Q3VBoxLayout(this);
    Q3Grid * grid = new Q3Grid(2, this);
    Q3HBox * htab;
    int index;

    vbox->addWidget(grid);
    vbox->setMargin(5);

    new QLabel(".pro file : ", grid);
    htab = new Q3HBox(grid);
    edpro = new QLineEdit(htab);
    edpro->setText(d.absFilePath(pro));

    new QLabel(" ", htab);
    browsepro = new SmallPushButton("browse", htab);
    connect(browsepro, SIGNAL(clicked()), this, SLOT(browse_pro()));

    new QLabel("target : ", grid);
    htab = new Q3HBox(grid);
    edtarget = new QLineEdit(htab);
    edtarget->setText(d.absFilePath(target));
    new QLabel(" ", htab);
    browsetarget = new SmallPushButton("browse", htab);
    connect(browsetarget, SIGNAL(clicked()), this, SLOT(browse_target()));

    new QLabel("template : ", grid);
    cbtemplate = new Q3ComboBox(TRUE, grid);

    static const char * templates[] = { "app", "lib", "subdirs" };
    bool find = FALSE;

    for (index = 0; index != sizeof(templates) / sizeof(*templates); index += 1) {
        cbtemplate->insertItem(templates[index]);

        if (tmplt == templates[index]) {
            cbtemplate->setCurrentItem(index);
            find = TRUE;
        }
    }

    if (! find) {
        cbtemplate->insertItem((QString) tmplt);
        cbtemplate->setCurrentItem(index);
    }

    new QLabel("config : ", grid);
    htab = new Q3HBox(grid);
    cbconf[0] = new Q3ComboBox(FALSE, htab);
    cbconf[0]->insertItem("debug");
    cbconf[0]->insertItem("release");

    QStringList lcnf =
        QStringList::split(" ", (const char *) config);
    QStringList::Iterator it = lcnf.begin();

    cbconf[0]->setCurrentItem((*it++ == "debug") ? 0 : 1);

    cbconf[1] = new Q3ComboBox(FALSE, htab);
    cbconf[1]->insertItem("warn_on");
    cbconf[1]->insertItem("warn_off");
    cbconf[1]->setCurrentItem((*it++ == "warn_on") ? 0 : 1);

    QSizePolicy sp = cbconf[0]->sizePolicy();

    sp.setHorData(QSizePolicy::Fixed);
    cbconf[0]->setSizePolicy(sp);
    cbconf[1]->setSizePolicy(sp);

    new QLabel(" qt ", htab);
    it++;	// qt

    const char * configs[] = {
        "", "opengl", "thread", "x11", "windows",
        "console", "dll", "staticlib", 0
    };

    for (index = 2;
         index != sizeof(cbconf) / sizeof(*cbconf) - 1;
         index += 1) {
        cbconf[index] = new Q3ComboBox(TRUE, htab);

        if (it != lcnf.end())
            cbconf[index]->insertItem(*it++);

        cbconf[index]->insertStrList(configs);
        cbconf[index]->setCurrentItem(0);
    }

    cbconf[index] = new Q3ComboBox(TRUE, htab);

    if (it != lcnf.end()) {
        QString s = *it++;

        while (it != lcnf.end())
            s += " " + *it++;

        cbconf[index]->insertItem(s);
    }

    cbconf[index]->insertStrList(configs);
    cbconf[index]->setCurrentItem(0);


    new QLabel("defines : ", grid);
    eddefines = new QLineEdit(grid);
    eddefines->setText(defines);

    ///may be computed
    new QLabel("include paths : ", grid);
    htab = new Q3HBox(grid);
    edincludepath = new QLineEdit(htab);
    edincludepath->setText(includepath);
    new QLabel(" ", htab);
    computeincludepath = new SmallPushButton("compute", htab);
    connect(computeincludepath, SIGNAL(clicked()), this, SLOT(compute_includepath()));

    new QLabel("depend paths : ", grid);
    eddependpath = new QLineEdit(grid);
    eddependpath->setText(dependpath);

    new QLabel("objects dir : ", grid);
    htab = new Q3HBox(grid);
    edobjectsdir = new QLineEdit(htab);
    edobjectsdir->setText(objectsdir);
    new QLabel(" ", htab);
    browseobjectsdir = new SmallPushButton("browse", htab);
    connect(browseobjectsdir, SIGNAL(clicked()), this, SLOT(browse_objectsdir()));

    new QLabel("footer : ", grid);
    edfooter = new Q3TextEdit(grid);
    edfooter->setText(footer);

    new QLabel(grid);
    new QLabel(grid);

    new QLabel(grid);
    htab = new Q3HBox(grid);
    new QLabel(htab);
    QPushButton * ok = new QPushButton("&OK", htab);
    new QLabel(htab);
    QPushButton * cancel = new QPushButton("&Cancel", htab);
    new QLabel(htab);
    QSize bs(cancel->sizeHint());

    ok->setDefault(TRUE);

    if (ok->sizeHint().width() > bs.width())
        bs.setWidth(ok->sizeHint().width());

    ok->setFixedSize(bs);
    cancel->setFixedSize(bs);

    connect(ok, SIGNAL(clicked()), this, SLOT(accept()));
    connect(cancel, SIGNAL(clicked()), this, SLOT(reject()));
}
Esempio n. 19
0
Dialog::Dialog(WrapperStr & path, WrapperStr & encoding, WrapperStr & nomodel, WrapperStr & genview, WrapperStr & uml20, WrapperStr & pk, WrapperStr & vis, WrapperStr & primitivetype, WrapperStr & genextension, WrapperStr & geneclipse, WrapperStr & commentexporter, WrapperStr & linefeed, Language & lang)
    : QDialog(0, 0, TRUE), _path(path), _encoding(encoding), _nomodel(nomodel), _genview(genview), _uml20(uml20), _pk(pk), _vis(vis), _primitivetype(primitivetype), _genextension(genextension), _geneclipse(geneclipse), _commentexporter(commentexporter), _linefeed(linefeed), _lang(lang)
{
    Q3VBoxLayout * vbox = new Q3VBoxLayout(this);
    Q3HBox * htab;

    vbox->setMargin(5);

    // get xmi pathname

    htab = new Q3HBox(this);
    htab->setMargin(5);
    vbox->addWidget(htab);

    new QLabel("generated \nXMI file : ", htab);

    ed = new QLineEdit(htab);
    ed->setText(_path);

    new QLabel(" ", htab);

    SmallPushButton * br = new SmallPushButton("browse", htab);

    connect(br, SIGNAL(clicked()), this, SLOT(browse()));

    // to choose encoding

    htab = new Q3HBox(this);
    htab->setMargin(5);
    vbox->addWidget(htab);

    new QLabel("Encoding : ", htab);

    QString charset = getenv("BOUML_CHARSET");
    int index = 0;

    while ((index = charset.find('_')) != -1) {
        charset[index] = '-';
        index += 1;
    }

    encoding_cb = new QComboBox(TRUE, htab);
    htab->setStretchFactor(encoding_cb, 1000);

    if (_encoding.isEmpty())
        _encoding = "UTF-8";

    encoding_cb->insertItem(QString(_encoding));

    if (!charset.isEmpty() && (_encoding != (const char *) charset))
        encoding_cb->insertItem(charset);

    if (_encoding != "UTF-8")
        encoding_cb->insertItem("UTF-8");

#ifdef WIN32

    if ((_encoding != "windows-1252") && (charset != "windows-1252"))
        encoding_cb->insertItem("windows-1252");

    if ((_encoding != "ISO-8859-1") && (charset != "ISO-8859-1"))
        encoding_cb->insertItem("ISO-8859-1");

#else

    if ((_encoding != "ISO-8859-1") && (charset != "ISO-8859-1"))
        encoding_cb->insertItem("ISO-8859-1");

    if ((_encoding != "windows-1252") && (charset != "windows-1252"))
        encoding_cb->insertItem("windows-1252");

#endif

    // uml 2.0 or uml2.1

    htab = new Q3HBox(this);
    htab->setMargin(5);
    vbox->addWidget(htab);

    Q3ButtonGroup * bg = new Q3ButtonGroup(2, Qt::Horizontal, "Uml", htab);

    uml20_rb = new QRadioButton("uml 2.0", bg);
    uml21_rb = new QRadioButton("uml 2.1", bg);

    if (uml20 == "yes")
        uml20_rb->setChecked(TRUE);
    else
        uml21_rb->setChecked(TRUE);

    // generate model

    htab = new Q3HBox(this);
    htab->setMargin(5);
    vbox->addWidget(htab);

    nomodel_cb = new QCheckBox("Don't generate model level", htab);

    if (_nomodel == "yes")
        nomodel_cb->setChecked(TRUE);

    // generate view checkbox

    htab = new Q3HBox(this);
    htab->setMargin(5);
    vbox->addWidget(htab);

    genview_cb = new QCheckBox("Generate views as package (not compatible with profile generation)", htab);

    if (_genview == "yes")
        genview_cb->setChecked(TRUE);

    // generate pk_ prefix

    htab = new Q3HBox(this);
    htab->setMargin(5);
    vbox->addWidget(htab);

    pk_cb = new QCheckBox("Generate 'pk_' prefix for parameter direction", htab);

    if (_pk == "yes")
        pk_cb->setChecked(TRUE);

    // generate vis_ prefix

    htab = new Q3HBox(this);
    htab->setMargin(5);
    vbox->addWidget(htab);

    vis_cb = new QCheckBox("Generate 'vis_' prefix for visibility", htab);

    if (_vis == "yes")
        vis_cb->setChecked(TRUE);

    // use PrimitiveType rather than DataType

    htab = new Q3HBox(this);
    htab->setMargin(5);
    vbox->addWidget(htab);

    primitivetype_cb = new QCheckBox("Use PrimitiveType rather than DataType", htab);

    if (_primitivetype == "yes")
        primitivetype_cb->setChecked(TRUE);

    // generate extension

    htab = new Q3HBox(this);
    htab->setMargin(5);
    vbox->addWidget(htab);

    genextension_cb = new QCheckBox("Generate extensions", htab);

    if (_genextension == "yes")
        genextension_cb->setChecked(TRUE);

    // generate for Eclipse

    htab = new Q3HBox(this);
    htab->setMargin(5);
    vbox->addWidget(htab);

    geneclipse_cb = new QCheckBox("Generate for Eclipse (aggregation set on other relation side)", htab);

    if (_geneclipse == "yes")
        geneclipse_cb->setChecked(TRUE);

    // comment exporter

    htab = new Q3HBox(this);
    htab->setMargin(5);
    vbox->addWidget(htab);

    commentexporter_cb = new QCheckBox("Comment exporter indication (needed to import in some tools like Rsa)", htab);

    if (_commentexporter == "yes")
        commentexporter_cb->setChecked(TRUE);

    // generate &#10; rather than linefeed

    htab = new Q3HBox(this);
    htab->setMargin(5);
    vbox->addWidget(htab);

    linefeed_cb = new QCheckBox("Generate lf and cr characters in string rather than '&&#10;' and '&&#13;'", htab);

    if (_linefeed == "yes")
        linefeed_cb->setChecked(TRUE);

    // uml , c++, java, cancel buttons

    htab = new Q3HBox(this);
    htab->setMargin(5);
    vbox->addWidget(htab);

    new QLabel(htab);
    QPushButton * uml = new QPushButton("&Uml", htab);
    new QLabel(htab);
    QPushButton * cpp = new QPushButton("&C++", htab);
    new QLabel(htab);
    QPushButton * java = new QPushButton("&Java", htab);
    new QLabel(htab);
    QPushButton * cancel = new QPushButton("&Cancel", htab);
    new QLabel(htab);
    QSize bs(cancel->sizeHint());

    uml->setFixedSize(bs);
    cpp->setFixedSize(bs);
    java->setFixedSize(bs);

    connect(uml, SIGNAL(clicked()), this, SLOT(accept_uml()));
    connect(cpp, SIGNAL(clicked()), this, SLOT(accept_cpp()));
    connect(java, SIGNAL(clicked()), this, SLOT(accept_java()));
    connect(cancel, SIGNAL(clicked()), this, SLOT(reject()));

    // help

    htab = new Q3HBox(this);
    htab->setMargin(5);
    vbox->addWidget(htab);

    new QLabel(htab);
    new QLabel("Remark : to help Eclipse to import the generated file,\n"
               "choose Uml 2.1 and name the file with the extension '.xmi'", htab);
    new QLabel(htab);
}
Esempio n. 20
0
		void Server::Update()
		{
			// Store all incoming packets in a temporary list (to defer parsing of packets that arrive during parsing)
			std::vector<RakNet::Packet*> packets;
			for (RakNet::Packet* packet = m_peer->Receive(); packet; packet = m_peer->Receive())
			{
				packets.push_back(packet);
			}

			// Parse all incoming packets
			for (size_t i = 0; i < packets.size(); ++i)
			{
				RakNet::Packet* packet = packets[i];
				RakNet::BitStream bs(packet->data, packet->length, false);
				RakNet::MessageID id = 0;
				RakNet::Time time = 0;
				
				bs.Read(id);
				if (id == ID_TIMESTAMP)
				{
					bs.Read(time);
					bs.Read(id);
				}

				if (m_messageHandler != nullptr)
				{
					if (!m_messageHandler->ParsePacket(id, &bs, packet, time))
					{
						m_logger->LogText(LogTag::SERVER, LogLevel::WARNING, "Message handler neglected to parse message with ID: %u", id);
					}
				}
				else
				{
					m_logger->LogText(LogTag::SERVER, LogLevel::WARNING, "No message handler to parse message with ID: %u", id);
				}

			}

			// Deallocate the temporary list
			for (size_t i = 0; i < packets.size(); ++i)
			{
				m_peer->DeallocatePacket(packets[i]);
			}

			// Reduce time from delta timer and if 
			m_worldDeltaTimer += m_world->GetDelta();
			//m_logger->LogText(LogTag::SERVER, LogLevel::DEBUG_PRINT, "worldDeltaTimer = %f", m_worldDeltaTimer);
			if(m_worldDeltaTimer > WORLD_DELTA_UPDATE_INTERVAL)
			{
				m_worldDeltaTimer = 0;

				RakNet::BitStream bs;
				bs.Write((RakNet::MessageID) ID_TIMESTAMP);
				bs.Write(RakNet::GetTime());
				bs.Write((RakNet::MessageID) NetworkMessage::MessageType::GameStateDelta);
				NetworkMessage::SerializeWorld(&bs, m_world, g_networkEntityMap);

				m_peer->Send(&bs, HIGH_PRIORITY, UNRELIABLE_SEQUENCED, 0, RakNet::UNASSIGNED_RAKNET_GUID, true);
				//m_logger->LogText(LogTag::SERVER, LogLevel::DEBUG_PRINT, "Sending DeltaWorld snapshot: %d bytes", bs.GetNumberOfBytesUsed());
			}
		}
Esempio n. 21
0
/*
encode using lempel ziv algorithm.
*/
int COMP_INFO::encode_lz(
				    const UBMP8* in_table,
		            UBMP8* out_table,
					const UBMP32 size
				 ) {

	register int i;
	const UBMP8* in = in_table;
	const UBMP8* ine = in_table + size;
	const UBMP8* swindow = in_table;
	UBMP8* out = out_table;
	PAIR pair;
	PAIR pair1;
	BITSET bs(in,out);
	LINK::clear();

	while(in < ine) {
	    pair = find_match(in,ine);

		if(pair.len) {
			//lazy match
			i = 0;
			do {
				if(pair.len >= MAX_MATCH_LENGTH)
					break;

				pair1 = find_match(in + 1,ine);

				if(pair1.len > pair.len) {
					pair = pair1;

					//write literal byte
					bs.writeliteral(*in);

					LINK::list[*in].add(in);
					in++;

					bs.writebits();
				} else {
					break;
				}
				i++;
			} while(in < ine && i < pair.len);

            //write pair bytes
			bs.writepair(pair);

			for(i = 0;i < pair.len;i++) {
				LINK::list[*in].add(in);
				in++;
			}
		} else {
			//write literal byte
			bs.writeliteral(*in);

			LINK::list[*in].add(in);
			in++;
		}
		bs.writebits();
	}
	bs.flushbits();

	return int(out - out_table);
}
Esempio n. 22
0
void ttyout(unsigned char c)
{
    switch(mode)
    {
    /* Print mode */
    case 5:
        if(c==6) break;
        pp(c);
        return;

    /* No prefix characters */
    case 0:
        switch(c)
        {
        case 6:
            mode=5;
            return;         /* Pass-thru printing */
        case 7:
            bell();
            break;
        case 8:
            dowrap=0;
            bs();
            break;
        case 9:
            tab();
            break;
        case 10:
        case 11:
        case 12:
            dowrap=0;
            if(mnl) cr();
            lf();
            break;
        case 13:
            dowrap=0;
            cr();
            break;
        case 27:
            mode=1;
            return;
        case 0x84:
            dowrap=0;
            lf();
            break;
        case 0x85:
            dowrap=0;
            cr();
            lf();
            break;
        case 0x88:
            settab();
            break;
        case 0x8d:
            dowrap=0;
            ups();
            break;
        case 0x9b:
            begin();
            mode=2;
            return;
        default:
            if(minsert) insc(c);
            else type(c);
        }
        break;

    /* ESC has been received */
    case 1:
        switch(c)
        {
        case 27:
            return;
        case '[':
            begin();
            mode=2;
            return;
        case 'D':
            dowrap=0;
            lf();
            break;
        case 'E':
            dowrap=0;
            cr();
            lf();
            break;
        case 'H':
            settab();
            break;
        case 'M':
            dowrap=0;
            ups();
            break;
        case '#':
            mode=3;
            return;
        }
        break;

    /* ESC [ or 0x9B has been received */
    case 2:
        /* Enter numbers */
        switch(c)
        {
        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
            parry[nptr]=parry[nptr]*10+c-'0';
            return;
        case ';':
            if(MAXPARMS== ++nptr) break;
            else return;
        case 27:
            mode=1;
            return;
        case '[':
            begin();
            return;
        case 'c':
            ttyinit();
            break;
        case 'p':
            dowrap=0;
            break;  /* Reset what? */
        case 'r':
            dowrap=0;
            setregn();
            break;
        case 'm':
            setattrib();
            break;
        case 'J':
            clrs();
            break;
        case 'K':
            clrl();
            break;
        case 'X':
            clrc();
            break;
        case 'H':
            dowrap=0;
            pos();
            break;
        case 'C':
            dowrap=0;
            right();
            break;
        case 'D':
            dowrap=0;
            left();
            break;
        case 'A':
            dowrap=0;
            up();
            break;
        case 'B':
            dowrap=0;
            down();
            break;
        case 'g':
            clrt();
            break;
        case 'M':
            dell();
            break;
        case 'L':
            insl();
            break;
        case 'P':
            delc();
            break;
        case '@':
            inss();
            break;
        case 'h':
            hmode();
            break;
        case 'l':
            lmode();
            break;
        case '!':
        case '?':
            return;
        }
        break;

    /* ESC # has been received */
    case 3:
        switch(c)
        {
        case 27:
            mode=1;
            return;
        case '[':
            begin();
            mode=2;
            return;
        }
        break;
    }
    mode=0;
}
Esempio n. 23
0
box
pager_rep::pages_format (pagelet pg) {
  // cout << "Formatting pagelet " << (N(pages)+1)
  //      << " stretch " << pg->stretch
  //      << " height " << stretch_space (pg->ht, pg->stretch) << LF << INDENT;
  if (N (pg->ins) == 0) {
    if (N(pages) == 0) return dummy_box (decorate_middle (ip));
    return dummy_box (decorate_middle (pages [N(pages)-1] -> find_rip ()));
  }
  else if (N (pg->ins) == 1) {
    insertion ins= pg->ins[0];
    // cout << ins << " stretch " << ins->stretch
    //      << " height " << stretch_space (ins->ht, ins->stretch) << LF;
    //      << UNINDENT << "Formatted pagelet " << (N(pages)+1) << LF << LF;
    return pages_format (ins);
  }
  else {
    int i, n= N(pg->ins);
    array<box> bs (n);
    array<SI>  bx (n);
    array<SI>  by (n);
    SI y= 0, fnote_y= MAX_SI;
    for (i=0; i<n; i++) {
      insertion ins= pg->ins[i];
      // cout << ins << " at " << y << " stretch " << ins->stretch
      //      << " height " << stretch_space (ins->ht, ins->stretch) << LF;
      bs[i]= pages_format (ins);
      bx[i]= 0;
      by[i]= y;
      y -= bs[i]->h();
      if (i < n-1) {
	insertion next= pg->ins[i+1];
	if (ins->type != next->type) {
	  if (is_tuple (next->type, "footnote")) {
	    // cout << "sep " << stretch_space (fnote_sep, ins->stretch) << LF;
	    y -= stretch_space (fnote_sep, ins->stretch);
	    fnote_y= y;
	  }
	  else if (is_tuple (ins->type, "float")) {
	    if (!is_tuple (next->type, "float")) {
	      // cout << "sep " << stretch_space(float_sep, ins->stretch) << LF;
	      y -= stretch_space (float_sep, ins->stretch);
	    }
	  }
	  else if (is_tuple (ins->type, "multi-column") ||
		   is_tuple (next->type, "multi-column")) {
	    page_item item= access (l, path_dec (ins->end));
	    // cout << "sep " << stretch_space (item->spc, ins->stretch) << LF;
	    y -= stretch_space (item->spc, ins->stretch);
	  }
	}
	if (is_tuple (ins->type, "footnote"))
	  if (is_tuple (next->type, "footnote")) {
	    page_item item= access (l, path_dec (ins->end));
	    SI sep= stretch_space (item->spc + fn_sep, ins->stretch);
	    // cout << "sep " << sep << LF;
	    y -= sep;
	  }
	if (is_tuple (next->type, "float")) {
	  // cout << "sep " << stretch_space (float_sep, ins->stretch) << LF;
	  y -= stretch_space (float_sep, ins->stretch);
	}
      }
    }
    if (fnote_y != MAX_SI) {
      pencil pen= env->pen->set_width (env->fn->wline);
      bs << line_box (decorate(), 0, 0, fnote_bl, 0, pen);
      bx << 0;
      by << (fnote_y + env->fn->sep);
    }
    // cout << UNINDENT << "Formatted pagelet " << (N(pages)+1) << LF << LF;
    return scatter_box (ip, bs, bx, by);
  }
}
Esempio n. 24
0
TEST(ByteStream, size) {
	narf::ByteStream bs(7);
	ASSERT_EQ(7, bs.size());
}
Esempio n. 25
0
void cSubtitleObject::DecodeSubBlock(const uchar *Data, int Length, bool Even)
{
  int x = 0;
  int y = Even ? 0 : 1;
  uint8_t map2to4[ 4] = { 0x00, 0x07, 0x08, 0x0F };
  uint8_t map2to8[ 4] = { 0x00, 0x77, 0x88, 0xFF };
  uint8_t map4to8[16] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
  const uint8_t *mapTable = NULL;
  cBitStream bs(Data, Length * 8);
  while (!bs.IsEOF()) {
        switch (bs.GetBits(8)) {
          case 0x10:
               dbgobjects("2-bit / pixel code string\n");
               switch (bitmap->Bpp()) {
                 case 8:  mapTable = map2to8; break;
                 case 4:  mapTable = map2to4; break;
                 default: mapTable = NULL;    break;
                 }
               while (Decode2BppCodeString(&bs, x, y, mapTable) && !bs.IsEOF())
                     ;
               bs.ByteAlign();
               break;
          case 0x11:
               dbgobjects("4-bit / pixel code string\n");
               switch (bitmap->Bpp()) {
                 case 8:  mapTable = map4to8; break;
                 default: mapTable = NULL;    break;
                 }
               while (Decode4BppCodeString(&bs, x, y, mapTable) && !bs.IsEOF())
                     ;
               bs.ByteAlign();
               break;
          case 0x12:
               dbgobjects("8-bit / pixel code string\n");
               while (Decode8BppCodeString(&bs, x, y) && !bs.IsEOF())
                     ;
               break;
          case 0x20:
               dbgobjects("sub block 2 to 4 map\n");
               map2to4[0] = bs.GetBits(4);
               map2to4[1] = bs.GetBits(4);
               map2to4[2] = bs.GetBits(4);
               map2to4[3] = bs.GetBits(4);
               break;
          case 0x21:
               dbgobjects("sub block 2 to 8 map\n");
               for (int i = 0; i < 4; ++i)
                   map2to8[i] = bs.GetBits(8);
               break;
          case 0x22:
               dbgobjects("sub block 4 to 8 map\n");
               for (int i = 0; i < 16; ++i)
                   map4to8[i] = bs.GetBits(8);
               break;
          case 0xF0:
               dbgobjects("end of object line\n");
               x = 0;
               y += 2;
               break;
          default: dbgobjects("unknown sub block %s %d\n", __FUNCTION__, __LINE__);
          }
        }
}
Esempio n. 26
0
TEST(ByteStream, ctorData) {
	const char* data = "abc";
	narf::ByteStream bs(data, 3);
	bs.skip(1);
	ASSERT_EQ('b', bs.readU8());
}
void JvmtiClassFileReconstituter::copy_bytecodes(methodHandle mh,
                                                 unsigned char* bytecodes) {
  // use a BytecodeStream to iterate over the bytecodes. JVM/fast bytecodes
  // and the breakpoint bytecode are converted to their original bytecodes.

  BytecodeStream bs(mh);

  unsigned char* p = bytecodes;
  Bytecodes::Code code;
  bool is_rewritten = mh->method_holder()->is_rewritten();

  while ((code = bs.next()) >= 0) {
    assert(Bytecodes::is_java_code(code), "sanity check");
    assert(code != Bytecodes::_breakpoint, "sanity check");

    // length of bytecode (mnemonic + operands)
    address bcp = bs.bcp();
    int     len = bs.instruction_size();
    assert(len > 0, "length must be > 0");

    // copy the bytecodes
    *p = (unsigned char) (bs.is_wide()? Bytecodes::_wide : code);
    if (len > 1) {
      memcpy(p+1, bcp+1, len-1);
    }

    // During linking the get/put and invoke instructions are rewritten
    // with an index into the constant pool cache. The original constant
    // pool index must be returned to caller.  Rewrite the index.
    if (is_rewritten && len > 1) {
      bool is_wide = false;
      switch (code) {
      case Bytecodes::_getstatic       :  // fall through
      case Bytecodes::_putstatic       :  // fall through
      case Bytecodes::_getfield        :  // fall through
      case Bytecodes::_putfield        :  // fall through
      case Bytecodes::_invokevirtual   :  // fall through
      case Bytecodes::_invokespecial   :  // fall through
      case Bytecodes::_invokestatic    :  // fall through
      case Bytecodes::_invokedynamic   :  // fall through
      case Bytecodes::_invokeinterface : {
        assert(len == 3 ||
               (code == Bytecodes::_invokeinterface && len == 5) ||
               (code == Bytecodes::_invokedynamic   && len == 5),
               "sanity check");

        int cpci = Bytes::get_native_u2(bcp+1);
        bool is_invokedynamic = (EnableInvokeDynamic && code == Bytecodes::_invokedynamic);
        ConstantPoolCacheEntry* entry;
        if (is_invokedynamic) {
          cpci = Bytes::get_native_u4(bcp+1);
          entry = mh->constants()->invokedynamic_cp_cache_entry_at(cpci);
        } else {
        // cache cannot be pre-fetched since some classes won't have it yet
          entry = mh->constants()->cache()->entry_at(cpci);
        }
        int i = entry->constant_pool_index();
        assert(i < mh->constants()->length(), "sanity check");
        Bytes::put_Java_u2((address)(p+1), (u2)i);     // java byte ordering
        if (is_invokedynamic)  *(p+3) = *(p+4) = 0;
        break;
      }
      case Bytecodes::_ldc_w:
        is_wide = true; // fall through
      case Bytecodes::_ldc: {
        if (bs.raw_code() == Bytecodes::_fast_aldc || bs.raw_code() == Bytecodes::_fast_aldc_w) {
          int cpci = is_wide ? Bytes::get_native_u2(bcp+1) : (u1)(*(bcp+1));
          int i = mh->constants()->object_to_cp_index(cpci);
          assert(i < mh->constants()->length(), "sanity check");
          if (is_wide) {
            Bytes::put_Java_u2((address)(p+1), (u2)i);     // java byte ordering
          } else {
            *(p+1) = (u1)i;
          }
        }
        break;
        }
      }
    }

    p += len;
  }
}
Esempio n. 28
0
TEST(ByteStream, ctorString) {
	std::string data = "abc";
	narf::ByteStream bs(data);
	bs.skip(1);
	ASSERT_EQ('b', bs.readU8());
}
Esempio n. 29
0
template <class FT> int Pruner<FT>::nelder_mead_step(/*io*/ vec &b)
{
  int dn = b.size();
  int l  = dn + 1;
  evec tmp_constructor(dn);
  vector<evec> bs(l);  // The simplexe (d+1) vector of dim d
  FT *fs = new FT[l];  // Values of f at the simplex vertices

  for (int i = 0; i < l; ++i)  // Intialize the simplex
  {
    bs[i] = b;  // Start from b
    if (i < dn)
    {
      bs[i][i] += (bs[i][i] < .5) ? ND_INIT_WIDTH : -ND_INIT_WIDTH;
    }
    enforce(bs[i]);
    fs[i] = target_function(bs[i]);  // initialize the value
  }

  FT init_cf = fs[l - 1];

  vec bo(dn);  // centeroid
  FT fo;       // value at the centroid

  FT fs_maxi_last = fs[0];  // value of the last centroid

  if (verbosity)
  {
    cerr << "  Starting nelder_mead cf = " << init_cf << " proba = " << measure_metric(b) << endl;
  }
  unsigned int counter = 0;
  int mini = 0, maxi = 0, maxi2 = 0;
  while (1)  // Main loop
  {
    mini = maxi = maxi2 = 0;
    for (int i = 0; i < dn; ++i)
      bo[i] = bs[0][i];
    ////////////////
    // step 1. and 2. : Order and centroid
    ////////////////
    for (int i = 1; i < l; ++i)  // determine min and max, and centroid
    {
      mini = (fs[i] < fs[mini]) ? i : mini;
      maxi = (fs[i] > fs[mini]) ? i : maxi;
      for (int j = 0; j < dn; ++j)
      {
        bo[j] += bs[i][j];
      }
    }
    FT tmp;
    tmp = l;
    for (int i = 0; i < dn; ++i)
      bo[i] /= tmp;  // Centroid calculated

    fs_maxi_last = (!counter) ? fs[maxi] : fs_maxi_last;

    // determine min and max, and centroid
    maxi2 += (!maxi);
    for (int i = 1; i < l; ++i)
    {
      maxi2 = ((fs[i] > fs[maxi2]) && (i != maxi)) ? i : maxi2;
    }

    if (enforce(bo))  // Maybe want to skip this test, that may be kinda costly.
    {
      throw std::runtime_error("Concavity says that should not happen.");
    }

    if (verbosity)  // Not sure such verbosity is now of any use
    {
      cerr << "  melder_mead step " << counter << "cf = " << fs[mini]
           << " proba = " << measure_metric(bs[mini]) << " cost = " << single_enum_cost(bs[mini])
           << endl;
      for (int i = 0; i < dn; ++i)
      {
        cerr << ceil(bs[mini][i].get_d() * 1000) << " ";
      }
      cerr << endl;
    }

    ////////////////
    // Stopping condition (Not documented on wikipedia, improvising)
    // I'm not satistifed by it anymore. Exploration needed.
    ////////////////

    counter++;
    if (!(counter % l))  // Every l steps, we check progress and stop if none is done
    {
      if (fs[maxi] > fs_maxi_last * min_cf_decrease)
      {
        break;
      }
      fs_maxi_last = fs[maxi];
    }

    for (int i = 0; i < l; ++i)  // determine second best
    {
      if ((fs[i] > fs[maxi2]) && (i != maxi))
        maxi2 = i;
    }

    if (verbosity)
    {
      cerr << mini << " " << maxi2 << " " << maxi << endl;
      cerr << fs[mini] << " < " << fs[maxi2] << " < " << fs[maxi] << " | " << endl;
    }

    ////////////////
    // step 3. Reflection
    ////////////////

    vec br(dn);  // reflected point
    FT fr;       // Value at the reflexion point
    for (int i = 0; i < dn; ++i)
      br[i] = bo[i] + ND_ALPHA * (bo[i] - bs[maxi][i]);
    enforce(br);
    fr = target_function(br);
    if (verbosity)
    {
      cerr << "fr " << fr << endl;
    }

    if ((fs[mini] <= fr) && (fr < fs[maxi2]))
    {
      bs[maxi] = br;
      fs[maxi] = fr;
      if (verbosity)
      {
        cerr << "    Reflection " << endl;
      }
      continue;  // Go to step 1.
    }

    ////////////////
    // step 4. Expansion
    ////////////////

    if (fr < fs[mini])
    {
      vec be(dn);
      FT fe;
      for (int i = 0; i < dn; ++i)
        be[i] = bo[i] + ND_GAMMA * (br[i] - bo[i]);
      enforce(be);
      fe = target_function(be);
      if (verbosity)
      {
        cerr << "fe " << fe << endl;
      }
      if (fe < fr)
      {
        bs[maxi] = be;
        fs[maxi] = fe;
        if (verbosity)
        {
          cerr << "    Expansion A " << endl;
        }
        continue;  // Go to step 1.
      }
      else
      {
        bs[maxi] = br;
        fs[maxi] = fr;
        if (verbosity)
        {
          cerr << "    Expansion B " << endl;
        }
        continue;  // Go to step 1.
      }
    }

    ////////////////
    // step 5. Contraction
    ////////////////

    if (!(fr >= fs[maxi2]))  // Here, it is certain that fr >= fs[maxi2]
    {
      throw std::runtime_error("Something certain is false in Nelder-Mead.");
    }

    vec bc(dn);
    FT fc;
    for (int i = 0; i < dn; ++i)
      bc[i] = bo[i] + ND_RHO * (bs[maxi][i] - bo[i]);
    enforce(bc);
    fc = target_function(bc);
    if (verbosity)
    {
      cerr << "fc " << fc << endl;
    }
    if (fc < fs[maxi])
    {
      bs[maxi] = bc;
      fs[maxi] = fc;
      if (verbosity)
      {
        cerr << "    Contraction " << endl;
      }
      continue;  // Go to step 1.
    }

    ////////////////
    // step 6. Shrink
    ////////////////
    if (verbosity)
    {
      cerr << "    Shrink " << endl;
    }
    for (int j = 0; j < l; ++j)
    {
      for (int i = 0; i < dn; ++i)
      {
        bs[j][i] = bs[mini][i] + ND_SIGMA * (bs[j][i] - bs[mini][i]);
      }
      enforce(bs[j]);
      fs[j] = target_function(bs[j]);  // initialize the value
    }
  }

  b            = bs[mini];
  int improved = (init_cf * min_cf_decrease) > fs[mini];

  if (verbosity)
  {
    cerr << "Done nelder_mead, after " << counter << " steps" << endl;
    cerr << "Final cf = " << fs[mini] << " proba = " << measure_metric(b) << endl;
    if (improved)
    {
      cerr << "Progress has been made: init cf = " << init_cf << endl;
    }
    cerr << endl;
  }

  return improved;  // Has MN made any progress
}
Esempio n. 30
0
bool RS_Math::linearSolver(const QVector<QVector<double> >& mt, QVector<double>& sn){
    //verify the matrix size
    int mSize(mt.size()); //rows
    int aSize(mSize+1); //columns of augmented matrix
    for(int i=0;i<mSize;i++) {
        if(mt[i].size() != aSize ) return false;
    }
    sn.resize(mSize);//to hold the solution
#ifdef	HAS_BOOST
    boost::numeric::ublas::matrix<double> bm (mSize, mSize);
    boost::numeric::ublas::vector<double> bs(mSize);

    for(int i=0;i<mSize;i++) {
        for(int j=0;j<mSize;j++) {
            bm(i,j)=mt[i][j];
        }
        bs(i)=mt[i][mSize];
    }
    //solve the linear equation set by LU decomposition in boost ublas

    if ( boost::numeric::ublas::lu_factorize<boost::numeric::ublas::matrix<double> >(bm) ) {
        RS_DEBUG->print(RS_Debug::D_WARNING, "Those 4 points do not define an ellipse");
        return false;
    }

    boost::numeric::ublas:: triangular_matrix<double, boost::numeric::ublas::unit_lower>
            lm = boost::numeric::ublas::triangular_adaptor< boost::numeric::ublas::matrix<double>,  boost::numeric::ublas::unit_lower>(bm);
    boost::numeric::ublas:: triangular_matrix<double,  boost::numeric::ublas::upper>
            um =  boost::numeric::ublas::triangular_adaptor< boost::numeric::ublas::matrix<double>,  boost::numeric::ublas::upper>(bm);
    ;
    boost::numeric::ublas::inplace_solve(lm,bs, boost::numeric::ublas::lower_tag());
    boost::numeric::ublas::inplace_solve(um,bs, boost::numeric::ublas::upper_tag());
    for(int i=0;i<mSize;i++){
        sn[i]=bs(i);
    }
    //    std::cout<<"dn="<<dn<<std::endl;
    //    data.center.set(-0.5*dn(1)/dn(0),-0.5*dn(3)/dn(2)); // center
    //    double d(1.+0.25*(dn(1)*dn(1)/dn(0)+dn(3)*dn(3)/dn(2)));
    //    if(fabs(dn(0))<RS_TOLERANCE*RS_TOLERANCE
    //            ||fabs(dn(2))<RS_TOLERANCE*RS_TOLERANCE
    //            ||d/dn(0)<RS_TOLERANCE*RS_TOLERANCE
    //            ||d/dn(2)<RS_TOLERANCE*RS_TOLERANCE
    //            ) {
    //        //ellipse not defined
    //        return false;
    //    }
    //    d=sqrt(d/dn(0));
    //    data.majorP.set(d,0.);
    //    data.ratio=sqrt(dn(0)/dn(2));
#else
    // solve the linear equation by Gauss-Jordan elimination
    QVector<QVector<double> > mt0(mt); //copy the matrix;
    for(int i=0;i<mSize;i++){
        int imax(i);
        double cmax(fabs(mt0[i][i]));
        for(int j=i+1;j<mSize;j++) {
            if(fabs(mt0[j][i]) > cmax ) {
                imax=j;
                cmax=fabs(mt0[j][i]);
            }
        }
        if(cmax<RS_TOLERANCE*RS_TOLERANCE) return false; //singular matrix
        if(imax != i) {//move the line with largest absolute value at column i to row i, to avoid division by zero
            std::swap(mt0[i],mt0[imax]);
            //            for(int j=i;j<=mSize;j++) {
            //                std::swap(m[i][j],m[imax][j]);
            //            }
        }
        //        for(int k=i+1;k<5;k++) { //normalize the i-th row
        for(int k=mSize;k>=i;k--) { //normalize the i-th row
            mt0[i][k] /= mt0[i][i];
        }
        for(int j=0;j<mSize;j++) {//Gauss-Jordan
            if(j != i ) {
                //                for(int k=i+1;k<5;k++) {
                for(int k=mSize;k>=i;k--) {
                    mt0[j][k] -= mt0[i][k]*mt0[j][i];
                }
            }
        }
        //output gauss-jordan results for debugging
        //        std::cout<<"========"<<i<<"==========\n";
        //        for(int j=0;j<mSize;j++) {//Gauss-Jordan
        //            for(int k=0;k<=mSize;k++) {
        //                std::cout<<m[j][k]<<'\t';
        //            }
        //            std::cout<<std::endl;
        //        }
    }
    for(int i=0;i<mSize;i++) {
        sn[i]=mt0[i][mSize];
    }
#endif

    return true;
}