dsp* FaustgenFactory::createDSPAux(FaustAudioPluginInstance* instance)
{
  dsp* dsp = nullptr;
  std::string error;
  String logStr;

  // Factory already allocated
  if (fDSPfactory)
  {
    dsp = fDSPfactory->createDSPInstance();
    logStr << "Factory already allocated, " <<  dsp->getNumInputs() << " input(s), " << dsp->getNumOutputs() << " output(s)";
    goto end;
  }
  
  // Tries to create from bitcode
  if (fBitCode.length() > 0)
  {
    fDSPfactory = createFactoryFromBitcode();
    if (fDSPfactory)
    {
      dsp = fDSPfactory->createDSPInstance();
      logStr << "Compilation from bitcode succeeded, " <<  dsp->getNumInputs() << " input(s), " << dsp->getNumOutputs() << " output(s)";
      goto end;
    }
  }
  
  // Otherwise tries to create from source code
  if (fSourceCode.length() > 0)
  {
    fDSPfactory = createFactoryFromSourceCode(instance);
    if (fDSPfactory)
    {
      dsp = fDSPfactory->createDSPInstance();
      logStr << "Compilation from source code succeeded, " <<  dsp->getNumInputs() << " input(s), " << dsp->getNumOutputs() << " output(s)";
      goto end;
    }
  }
  
  // Otherwise creates default DSP keeping the same input/output number
  fDSPfactory = createDSPFactoryFromString("default", DEFAULT_CODE, 0, 0, getTarget(), error, LLVM_OPTIMIZATION);

  jassert(fDSPfactory);

  if (fDSPfactory)
  {
    dsp = fDSPfactory->createDSPInstance();
    logStr << "Allocation of default DSP succeeded, " << dsp->getNumInputs() << " input(s), " << dsp->getNumOutputs() << " output(s)";
  }

end:
  LOG(logStr);
  jassert(dsp);

  // Prepare JSON
  JSONUI builder(dsp->getNumInputs(), dsp->getNumOutputs());
  dsp->metadata(&builder);
  dsp->buildUserInterface(&builder);
  fJSON = String(builder.JSON());
  
  //LOG(fJSON);
  return dsp;
}
TEST_F(FontBuilderInitTest, NotDirty)
{
    FontBuilder builder(document());
    ASSERT_FALSE(builder.fontDirty());
}
Example #3
0
QgsGraph* RgShortestPathWidget::getPath( QgsPoint& p1, QgsPoint& p2 )
{
  if ( mFrontPointLineEdit->text().isNull() || mBackPointLineEdit->text().isNull() )
  {
    QMessageBox::critical( this, tr( "Point not selected" ), tr( "First, select start and stop points." ) );
    return NULL;
  }

  QgsGraphBuilder builder(
    mPlugin->iface()->mapCanvas()->mapSettings().destinationCrs(),
    mPlugin->iface()->mapCanvas()->mapSettings().hasCrsTransformEnabled(),
    mPlugin->topologyToleranceFactor() );
  {
    const QgsGraphDirector *director = mPlugin->director();
    if ( director == NULL )
    {
      QMessageBox::critical( this, tr( "Plugin isn't configured" ), tr( "Plugin isn't configured!" ) );
      return NULL;
    }
    connect( director, SIGNAL( buildProgress( int, int ) ), mPlugin->iface()->mainWindow(), SLOT( showProgress( int, int ) ) );
    connect( director, SIGNAL( buildMessage( QString ) ), mPlugin->iface()->mainWindow(), SLOT( showStatusMessage( QString ) ) );

    QVector< QgsPoint > points;
    QVector< QgsPoint > tiedPoint;

    points.push_back( mFrontPoint );
    points.push_back( mBackPoint );
    director->makeGraph( &builder, points, tiedPoint );

    p1 = tiedPoint[ 0 ];
    p2 = tiedPoint[ 1 ];
    // not need
    delete director;
  }

  if ( p1 == QgsPoint( 0.0, 0.0 ) )
  {
    QMessageBox::critical( this, tr( "Tie point failed" ), tr( "Start point doesn't tie to the road!" ) );
    return NULL;
  }
  if ( p2 == QgsPoint( 0.0, 0.0 ) )
  {
    QMessageBox::critical( this, tr( "Tie point failed" ), tr( "Stop point doesn't tie to the road!" ) );
    return NULL;
  }

  QgsGraph *graph = builder.graph();

  int startVertexIdx = graph->findVertex( p1 );
  if ( startVertexIdx < 0 )
  {
    mPlugin->iface()->messageBar()->pushMessage(
      tr( "Cannot calculate path" ),
      tr( "Could not find start vertex. Please check your input data." ),
      QgsMessageBar::WARNING,
      mPlugin->iface()->messageTimeout()
    );

    delete graph;
    return NULL;
  }

  int criterionNum = 0;
  if ( mCriterionName->currentIndex() > 0 )
    criterionNum = 1;

  if ( graph->vertexCount() == 0 )
  {
    mPlugin->iface()->messageBar()->pushMessage(
      tr( "Cannot calculate path" ),
      tr( "The created graph is empty. Please check your input data." ),
      QgsMessageBar::WARNING,
      mPlugin->iface()->messageTimeout()
    );

    delete graph;
    return NULL;
  }


  QgsGraph* shortestpathTree = QgsGraphAnalyzer::shortestTree( graph, startVertexIdx, criterionNum );
  delete graph;

  if ( shortestpathTree->findVertex( p2 ) == -1 )
  {
    delete shortestpathTree;
    QMessageBox::critical( this, tr( "Path not found" ), tr( "Path not found" ) );
    return NULL;
  }
  return shortestpathTree;
}
// internal
int asCScriptFunction::ParseListPattern(asSListPatternNode *&target, const char *decl, asCScriptNode *listNodes)
{
	asSListPatternNode *node = target;

	listNodes = listNodes->firstChild;
	while( listNodes )
	{
		if( listNodes->nodeType == snIdentifier )
		{
			asCString token(&decl[listNodes->tokenPos], listNodes->tokenLength);
			if( token == "repeat" )
			{
				node->next = asNEW(asSListPatternNode)(asLPT_REPEAT);
				node = node->next;
			}
			else if( token == "repeat_same" )
			{
				// TODO: list: Should make sure this is a sub-list
				node->next = asNEW(asSListPatternNode)(asLPT_REPEAT_SAME);
				node = node->next;
			}
			else
			{
				// Shouldn't happen as the parser already reported the error
				asASSERT(false);
			}
		}
		else if( listNodes->nodeType == snDataType )
		{
			asCDataType dt;
			asCBuilder builder(engine, 0);
			asCScriptCode code;
			code.SetCode("", decl, 0, false);
			dt = builder.CreateDataTypeFromNode(listNodes, &code, engine->defaultNamespace, false, returnType.GetObjectType());

			node->next = asNEW(asSListPatternDataTypeNode)(dt);
			node = node->next;
		}
		else if( listNodes->nodeType == snListPattern )
		{
			node->next = asNEW(asSListPatternNode)(asLPT_START);
			node = node->next;

			// Recursively parse the child
			int r = ParseListPattern(node, decl, listNodes);
			if( r < 0 )
				return r;

			node->next = asNEW(asSListPatternNode)(asLPT_END);
			node = node->next;
		}
		else
		{
			// Unexpected token in the list, the parser shouldn't have allowed
			asASSERT( false );
			return -1;
		}

		listNodes = listNodes->next;
	}

	target = node;
	return 0;
}
void dgPolygonSoupDatabaseBuilder::OptimizeByGroupID()
{
  dgTree<int, int> attribFilter(m_allocator);
  dgPolygonSoupDatabaseBuilder builder(m_allocator);
  dgPolygonSoupDatabaseBuilder builderAux(m_allocator);
  dgPolygonSoupDatabaseBuilder builderLeftOver(m_allocator);

  builder.Begin();
  dgInt32 polygonIndex = 0;
  for (dgInt32 i = 0; i < m_faceCount; i++)
  {
    dgInt32 attribute = m_vertexIndex[polygonIndex];
    if (!attribFilter.Find(attribute))
    {
      attribFilter.Insert(attribute, attribute);
      builder.OptimizeByGroupID(*this, i, polygonIndex, builderLeftOver);
      for (dgInt32 j = 0; builderLeftOver.m_faceCount && (j < 64); j++)
      {
        builderAux.m_faceVertexCount[builderLeftOver.m_faceCount] = 0;
        builderAux.m_vertexIndex[builderLeftOver.m_indexCount] = 0;
        builderAux.m_vertexPoints[builderLeftOver.m_vertexCount].m_x =
            dgFloat32(0.0f);

        memcpy(&builderAux.m_faceVertexCount[0],
            &builderLeftOver.m_faceVertexCount[0],
            sizeof(dgInt32) * builderLeftOver.m_faceCount);
        memcpy(&builderAux.m_vertexIndex[0], &builderLeftOver.m_vertexIndex[0],
            sizeof(dgInt32) * builderLeftOver.m_indexCount);
        memcpy(&builderAux.m_vertexPoints[0],
            &builderLeftOver.m_vertexPoints[0],
            sizeof(dgBigVector) * builderLeftOver.m_vertexCount);

        builderAux.m_faceCount = builderLeftOver.m_faceCount;
        builderAux.m_indexCount = builderLeftOver.m_indexCount;
        builderAux.m_vertexCount = builderLeftOver.m_vertexCount;

        dgInt32 prevFaceCount = builderLeftOver.m_faceCount;
        builderLeftOver.m_faceCount = 0;
        builderLeftOver.m_indexCount = 0;
        builderLeftOver.m_vertexCount = 0;

        builder.OptimizeByGroupID(builderAux, 0, 0, builderLeftOver);
        if (prevFaceCount == builderLeftOver.m_faceCount)
        {
          break;
        }
      }
      _ASSERTE(builderLeftOver.m_faceCount == 0);
    }
    polygonIndex += m_faceVertexCount[i];
  }
//	builder.End();
  builder.Optimize(false);

  m_faceVertexCount[builder.m_faceCount] = 0;
  m_vertexIndex[builder.m_indexCount] = 0;
  m_vertexPoints[builder.m_vertexCount].m_x = dgFloat32(0.0f);

  memcpy(&m_faceVertexCount[0], &builder.m_faceVertexCount[0],
      sizeof(dgInt32) * builder.m_faceCount);
  memcpy(&m_vertexIndex[0], &builder.m_vertexIndex[0],
      sizeof(dgInt32) * builder.m_indexCount);
  memcpy(&m_vertexPoints[0], &builder.m_vertexPoints[0],
      sizeof(dgBigVector) * builder.m_vertexCount);

  m_faceCount = builder.m_faceCount;
  m_indexCount = builder.m_indexCount;
  m_vertexCount = builder.m_vertexCount;
  m_normalCount = builder.m_normalCount;
}
GrStencilAndCoverTextContext::TextRun::TextRun(const SkPaint& fontAndStroke)
    : fStroke(fontAndStroke),
      fFont(fontAndStroke),
      fTotalGlyphCount(0),
      fFallbackGlyphCount(0),
      fDetachedGlyphCache(nullptr),
      fLastDrawnGlyphsID(SK_InvalidUniqueID) {
    SkASSERT(!fStroke.isHairlineStyle()); // Hairlines are not supported.

    // Setting to "fill" ensures that no strokes get baked into font outlines. (We use the GPU path
    // rendering API for stroking).
    fFont.setStyle(SkPaint::kFill_Style);

    if (fFont.isFakeBoldText() && SkStrokeRec::kStroke_Style != fStroke.getStyle()) {
        // Instead of letting fake bold get baked into the glyph outlines, do it with GPU stroke.
        SkScalar fakeBoldScale = SkScalarInterpFunc(fFont.getTextSize(),
                                                    kStdFakeBoldInterpKeys,
                                                    kStdFakeBoldInterpValues,
                                                    kStdFakeBoldInterpLength);
        SkScalar extra = SkScalarMul(fFont.getTextSize(), fakeBoldScale);
        fStroke.setStrokeStyle(fStroke.needToApply() ? fStroke.getWidth() + extra : extra,
                               true /*strokeAndFill*/);

        fFont.setFakeBoldText(false);
    }

    if (!fFont.getPathEffect() && !fStroke.isDashed()) {
        // We can draw the glyphs from canonically sized paths.
        fTextRatio = fFont.getTextSize() / SkPaint::kCanonicalTextSizeForPaths;
        fTextInverseRatio = SkPaint::kCanonicalTextSizeForPaths / fFont.getTextSize();

        // Compensate for the glyphs being scaled by fTextRatio.
        if (!fStroke.isFillStyle()) {
            fStroke.setStrokeStyle(fStroke.getWidth() / fTextRatio,
                                   SkStrokeRec::kStrokeAndFill_Style == fStroke.getStyle());
        }

        fFont.setLinearText(true);
        fFont.setLCDRenderText(false);
        fFont.setAutohinted(false);
        fFont.setHinting(SkPaint::kNo_Hinting);
        fFont.setSubpixelText(true);
        fFont.setTextSize(SkIntToScalar(SkPaint::kCanonicalTextSizeForPaths));

        fUsingRawGlyphPaths = SK_Scalar1 == fFont.getTextScaleX() &&
                              0 == fFont.getTextSkewX() &&
                              !fFont.isFakeBoldText() &&
                              !fFont.isVerticalText();
    } else {
        fTextRatio = fTextInverseRatio = 1.0f;
        fUsingRawGlyphPaths = false;
    }

    // Generate the key that will be used to cache the GPU glyph path objects.
    if (fUsingRawGlyphPaths && fStroke.isFillStyle()) {
        static const GrUniqueKey::Domain kRawFillPathGlyphDomain = GrUniqueKey::GenerateDomain();

        const SkTypeface* typeface = fFont.getTypeface();
        GrUniqueKey::Builder builder(&fGlyphPathsKey, kRawFillPathGlyphDomain, 1);
        reinterpret_cast<uint32_t&>(builder[0]) = typeface ? typeface->uniqueID() : 0;
    } else {
        static const GrUniqueKey::Domain kPathGlyphDomain = GrUniqueKey::GenerateDomain();

        int strokeDataCount = fStroke.computeUniqueKeyFragmentData32Cnt();
        if (fUsingRawGlyphPaths) {
            const SkTypeface* typeface = fFont.getTypeface();
            GrUniqueKey::Builder builder(&fGlyphPathsKey, kPathGlyphDomain, 2 + strokeDataCount);
            reinterpret_cast<uint32_t&>(builder[0]) = typeface ? typeface->uniqueID() : 0;
            reinterpret_cast<uint32_t&>(builder[1]) = strokeDataCount;
            fStroke.asUniqueKeyFragment(&builder[2]);
        } else {
            SkGlyphCache* glyphCache = this->getGlyphCache();
            const SkTypeface* typeface = glyphCache->getScalerContext()->getTypeface();
            const SkDescriptor* desc = &glyphCache->getDescriptor();
            int descDataCount = (desc->getLength() + 3) / 4;
            GrUniqueKey::Builder builder(&fGlyphPathsKey, kPathGlyphDomain,
                                         2 + strokeDataCount + descDataCount);
            reinterpret_cast<uint32_t&>(builder[0]) = typeface ? typeface->uniqueID() : 0;
            reinterpret_cast<uint32_t&>(builder[1]) = strokeDataCount | (descDataCount << 16);
            fStroke.asUniqueKeyFragment(&builder[2]);
            memcpy(&builder[2 + strokeDataCount], desc, desc->getLength());
        }
    }
}
Example #7
0
bool
GlueMapWindow::ShowMapItems(const GeoPoint &location,
                            bool show_empty_message) const
{
  /* not using MapWindowBlackboard here because this method is called
     by the main thread */
  const ComputerSettings &computer_settings =
    CommonInterface::GetComputerSettings();
  const MapSettings &settings = CommonInterface::GetMapSettings();
  const MoreData &basic = CommonInterface::Basic();
  const DerivedInfo &calculated = CommonInterface::Calculated();

  auto range = visible_projection.DistancePixelsToMeters(Layout::GetHitRadius());

  MapItemList list;
  MapItemListBuilder builder(list, location, range);

  if (settings.item_list.add_location)
      builder.AddLocation(basic, terrain);

  if (settings.item_list.add_arrival_altitude && route_planner)
    builder.AddArrivalAltitudes(*route_planner, terrain,
                                computer_settings.task.safety_height_arrival);

  if (basic.location_available)
    builder.AddSelfIfNear(basic.location, basic.attitude.heading);

  if (task)
    builder.AddTaskOZs(*task);

  const Airspaces *airspace_database = airspace_renderer.GetAirspaces();
  if (airspace_database)
    builder.AddVisibleAirspace(*airspace_database,
                               airspace_renderer.GetWarningManager(),
                               computer_settings.airspace,
                               settings.airspace, basic,
                               calculated);

  if (visible_projection.GetMapScale() <= 4000)
    builder.AddThermals(calculated.thermal_locator, basic, calculated);

  if (waypoints)
    builder.AddWaypoints(*waypoints);

#ifdef HAVE_NOAA
  if (noaa_store)
    builder.AddWeatherStations(*noaa_store);
#endif

  builder.AddTraffic(basic.flarm.traffic);

#ifdef HAVE_SKYLINES_TRACKING_HANDLER
  builder.AddSkyLinesTraffic();
#endif

  // Sort the list of map items
  list.Sort();

  // Show the list dialog
  if (list.empty()) {
    if (show_empty_message)
      ShowMessageBox(_("There is nothing interesting near this location."),
                  _("Map elements at this location"), MB_OK | MB_ICONINFORMATION);

    return false;
  }

  ShowMapItemListDialog(list,
                        UIGlobals::GetDialogLook(), look, traffic_look,
                        final_glide_bar_renderer.GetLook(), settings,
                        glide_computer != nullptr
                        ? &glide_computer->GetAirspaceWarnings() : nullptr);
  return true;
}
Example #8
0
void Channel::KickOrBan(Player const* player, std::string const& badname, bool ban)
{
    ObjectGuid const& good = player->GetGUID();

    if (!IsOn(good))
    {
        NotMemberAppend appender;
        ChannelNameBuilder<NotMemberAppend> builder(this, appender);
        SendToOne(builder, good);
        return;
    }

    PlayerInfo& info = _playersStore.at(good);
    if (!info.IsModerator() && !player->GetSession()->HasPermission(rbac::RBAC_PERM_CHANGE_CHANNEL_NOT_MODERATOR))
    {
        NotModeratorAppend appender;
        ChannelNameBuilder<NotModeratorAppend> builder(this, appender);
        SendToOne(builder, good);
        return;
    }

    Player* bad = ObjectAccessor::FindConnectedPlayerByName(badname);
    ObjectGuid const& victim = bad ? bad->GetGUID() : ObjectGuid::Empty;
    if (!victim || !IsOn(victim))
    {
        PlayerNotFoundAppend appender(badname);
        ChannelNameBuilder<PlayerNotFoundAppend> builder(this, appender);
        SendToOne(builder, good);
        return;
    }

    bool changeowner = _ownerGuid == victim;

    if (!player->GetSession()->HasPermission(rbac::RBAC_PERM_CHANGE_CHANNEL_NOT_MODERATOR) && changeowner && good != _ownerGuid)
    {
        NotOwnerAppend appender;
        ChannelNameBuilder<NotOwnerAppend> builder(this, appender);
        SendToOne(builder, good);
        return;
    }

    if (ban && !IsBanned(victim))
    {
        _bannedStore.insert(victim);
        UpdateChannelInDB();

        if (!player->GetSession()->HasPermission(rbac::RBAC_PERM_SILENTLY_JOIN_CHANNEL))
        {
            PlayerBannedAppend appender(good, victim);
            ChannelNameBuilder<PlayerBannedAppend> builder(this, appender);
            SendToAll(builder);
        }
    }
    else if (!player->GetSession()->HasPermission(rbac::RBAC_PERM_SILENTLY_JOIN_CHANNEL))
    {
        PlayerKickedAppend appender(good, victim);
        ChannelNameBuilder<PlayerKickedAppend> builder(this, appender);
        SendToAll(builder);
    }

    _playersStore.erase(victim);
    bad->LeftChannel(this);

    if (changeowner && _ownershipEnabled && !_playersStore.empty())
    {
        info.SetModerator(true);
        SetOwner(good);
    }
}
Example #9
0
		void EMailImapService::generateBundle(vmime::ref<vmime::net::message> &msg)
		{

			// Create new Bundle
			dtn::data::Bundle newBundle;

			// Clear all blocks
			newBundle.clear();

			// Get header of mail
			vmime::ref<const vmime::header> header = msg->getHeader();
			std::string mailID = " (ID: " + msg->getUniqueId() + ")";

			// Check EMailCL version
			try {
				int version = toInt(header->findField("Bundle-EMailCL-Version")->getValue()->generate());
				if(version != 1)
					throw IMAPException("Wrong EMailCL version found in mail" + mailID);
			}catch(vmime::exceptions::no_such_field&) {
				throw IMAPException("Field \"Bundle-EMailCL-Version\" not found in mail" + mailID);
			}catch(InvalidConversion&) {
				throw IMAPException("Field \"Bundle-EMailCL-Version\" wrong formatted in mail" + mailID);
			}

			try {
				newBundle.procflags = toInt(header->findField("Bundle-Flags")->getValue()->generate());
				newBundle.destination = header->findField("Bundle-Destination")->getValue()->generate();
				newBundle.source = dtn::data::EID(header->findField("Bundle-Source")->getValue()->generate());
				newBundle.reportto = header->findField("Bundle-Report-To")->getValue()->generate();
				newBundle.custodian = header->findField("Bundle-Custodian")->getValue()->generate();
				newBundle.timestamp = toInt(header->findField("Bundle-Creation-Time")->getValue()->generate());
				newBundle.sequencenumber = toInt(header->findField("Bundle-Sequence-Number")->getValue()->generate());
				newBundle.lifetime = toInt(header->findField("Bundle-Lifetime")->getValue()->generate());
			}catch(vmime::exceptions::no_such_field&) {
				throw IMAPException("Missing bundle headers in mail" + mailID);
			}catch(InvalidConversion&) {
				throw IMAPException("Wrong formatted bundle headers in mail" + mailID);
			}

			// If bundle is a fragment both fields need to be set
			try {
				newBundle.fragmentoffset = toInt(header->findField("Bundle-Fragment-Offset")->getValue()->generate());
				newBundle.appdatalength = toInt(header->findField("Bundle-Total-Application-Data-Unit-Length")->getValue()->generate());
			}catch(vmime::exceptions::no_such_field&) {
				newBundle.fragmentoffset = 0;
				newBundle.appdatalength = 0;
			}catch(InvalidConversion&) {
				throw IMAPException("Wrong formatted fragment offset in mail" + mailID);
			}

			//Check if bundle is already in the storage
			try {
				if(dtn::core::BundleCore::getInstance().getRouter().isKnown(newBundle))
					throw IMAPException("Bundle in mail" + mailID + " already processed");
			} catch (dtn::storage::NoBundleFoundException&) {
				// Go ahead
			}

			// Validate the primary block
			try {
				dtn::core::BundleCore::getInstance().validate((dtn::data::PrimaryBlock)newBundle);
			}catch(dtn::data::Validator::RejectedException&) {
				throw IMAPException("Bundle in mail" + mailID + " was rejected by validator");
			}

			// Get names of additional blocks
			std::vector<vmime::ref<vmime::headerField> > additionalBlocks =
					header.constCast<vmime::header>()->findAllFields("Bundle-Additional-Block");
			std::vector<std::string> additionalBlockNames;
			for(std::vector<vmime::ref<vmime::headerField> >::iterator it = additionalBlocks.begin();
					it != additionalBlocks.end(); ++it)
			{
				additionalBlockNames.push_back((*it)->getValue()->generate());
			}

			// Get all attachments
			std::vector<vmime::ref<const vmime::attachment> > attachments =
					vmime::attachmentHelper::findAttachmentsInMessage(msg->getParsedMessage());

			// Extract payload block info
			size_t payloadFlags;
			std::string payloadName;
			try {
				payloadFlags = toInt(header->findField("Bundle-Payload-Flags")->getValue()->generate());
				// Payload length will be calculated automatically
				//length = toInt(header->findField("Bundle-Payload-Block-Length")->getValue()->generate());
				payloadName = header->findField("Bundle-Payload-Data-Name")->getValue()->generate();
			}catch(vmime::exceptions::no_such_field&) {
				// No payload block there
			}catch(InvalidConversion&) {
				throw IMAPException("Wrong formatted payload flags in mail" + mailID);
			}

			// Create new bundle builder
			dtn::data::BundleBuilder builder(newBundle);

			// Download attachments
			for(std::vector<vmime::ref<const vmime::attachment> >::iterator it = attachments.begin(); it != attachments.end(); ++it)
			{
				if((*it)->getName().getBuffer() == payloadName && !payloadName.empty()) {
					dtn::data::PayloadBlock &pb = newBundle.push_back<dtn::data::PayloadBlock>();
					// Set data
					ibrcommon::BLOB::Reference ref = pb.getBLOB();
					ibrcommon::BLOB::iostream payloadData = ref.iostream();
					vmime::utility::outputStreamAdapter data((*payloadData));
					(*it)->getData()->extract(data);
					// Set flags
					setProcFlags(pb, payloadFlags);
					continue;
				}

				// If current attachment name is contained in additional attachment list
				if(std::find(additionalBlockNames.begin(), additionalBlockNames.end(), (*it)->getName().getBuffer()) != additionalBlockNames.end())
				{
					// Search for the block type
					block_t blockType;
					try {
						blockType = toInt((*it)->getHeader()->findField("Block-Type")->getValue()->generate());
					}catch(vmime::exceptions::no_such_field&) {
						throw IMAPException("Block type not found in attachment of mail" + mailID);
					}

					// Search for processing flags
					size_t flags;
					try {
						flags = toInt((*it)->getHeader()->findField("Block-Processing-Flags")->getValue()->generate());
					}catch(vmime::exceptions::no_such_field&) {
						throw IMAPException("Missing block processing flags in extension attachment of mail" + mailID);
					}catch(InvalidConversion&) {
						throw IMAPException("Wrong formatted processing flags in extension attachment of mail" + mailID);
					}

					// Create a block object
					dtn::data::Block &block = builder.insert(blockType, flags);

					// Add EIDs
					try {
						addEIDList(block, (*it));
					}catch(InvalidConversion&) {
						throw IMAPException("Wrong formatted EID list in extension attachment of mail" + mailID);
					}

					// Get payload of current block
					std::stringstream ss;
					vmime::utility::outputStreamAdapter data(ss);
					(*it)->getData()->extract(data);

					block.deserialize(ss, ss.str().length());
				}
			}

			// Validate whole bundle
			try {
				dtn::core::BundleCore::getInstance().validate(newBundle);
			}catch(dtn::data::Validator::RejectedException&) {
				throw IMAPException("Bundle in mail" + mailID + " was rejected by validator");
			}

			// create a filter context
			dtn::core::FilterContext context;
			context.setProtocol(dtn::core::Node::CONN_EMAIL);

			// push bundle through the filter routines
			context.setBundle(newBundle);
			BundleFilter::ACTION ret = dtn::core::BundleCore::getInstance().filter(dtn::core::BundleFilter::INPUT, context, newBundle);

			if (ret == BundleFilter::ACCEPT)
			{
				// Raise default bundle received event
				dtn::net::BundleReceivedEvent::raise(newBundle.source, newBundle, false);
			}
		}
Example #10
0
void Channel::JoinChannel(Player* player, std::string const& pass)
{
    ObjectGuid const& guid = player->GetGUID();
    if (IsOn(guid))
    {
        // Do not send error message for built-in channels
        if (!IsConstant())
        {
            PlayerAlreadyMemberAppend appender(guid);
            ChannelNameBuilder<PlayerAlreadyMemberAppend> builder(this, appender);
            SendToOne(builder, guid);
        }
        return;
    }

    if (IsBanned(guid))
    {
        BannedAppend appender;
        ChannelNameBuilder<BannedAppend> builder(this, appender);
        SendToOne(builder, guid);
        return;
    }

    if (!_channelPassword.empty() && pass != _channelPassword)
    {
        WrongPasswordAppend appender;
        ChannelNameBuilder<WrongPasswordAppend> builder(this, appender);
        SendToOne(builder, guid);
        return;
    }

    if (HasFlag(CHANNEL_FLAG_LFG) &&
        sWorld->getBoolConfig(CONFIG_RESTRICTED_LFG_CHANNEL) &&
        AccountMgr::IsPlayerAccount(player->GetSession()->GetSecurity()) && //FIXME: Move to RBAC
        player->GetGroup())
    {
        NotInLFGAppend appender;
        ChannelNameBuilder<NotInLFGAppend> builder(this, appender);
        SendToOne(builder, guid);
        return;
    }

    player->JoinedChannel(this);

    if (_announceEnabled && !player->GetSession()->HasPermission(rbac::RBAC_PERM_SILENTLY_JOIN_CHANNEL))
    {
        JoinedAppend appender(guid);
        ChannelNameBuilder<JoinedAppend> builder(this, appender);
        SendToAll(builder);
    }

    bool newChannel = _playersStore.empty();

    PlayerInfo& playerInfo = _playersStore[guid];
    playerInfo.SetInvisible(!player->isGMVisible());

    /*
    YouJoinedAppend appender;
    ChannelNameBuilder<YouJoinedAppend> builder(this, appender);
    SendToOne(builder, guid);
    */

    auto builder = [&](LocaleConstant /*locale*/)
    {
        WorldPackets::Channel::ChannelNotifyJoined* notify = new WorldPackets::Channel::ChannelNotifyJoined();
        //notify->ChannelWelcomeMsg = "";
        notify->ChatChannelID = _channelId;
        //notify->InstanceID = 0;
        notify->_ChannelFlags = _channelFlags;
        notify->_Channel = _channelName;
        return notify;
    };

    SendToOne(builder, guid);

    JoinNotify(player);

    // Custom channel handling
    if (!IsConstant())
    {
        // Update last_used timestamp in db
        if (!_playersStore.empty())
            UpdateChannelUseageInDB();

        // If the channel has no owner yet and ownership is allowed, set the new owner.
        // or if the owner was a GM with .gm visible off
        // don't do this if the new player is, too, an invis GM, unless the channel was empty
        if (_ownershipEnabled && (newChannel || !playerInfo.IsInvisible()) && (_ownerGuid.IsEmpty() || _isOwnerInvisible))
        {
            _isOwnerInvisible = playerInfo.IsInvisible();

            SetOwner(guid, !newChannel && !_isOwnerInvisible);
            playerInfo.SetModerator(true);
        }
    }
}
Example #11
0
void Channel::LeaveChannel(Player* player, bool send)
{
    ObjectGuid const& guid = player->GetGUID();
    if (!IsOn(guid))
    {
        if (send)
        {
            NotMemberAppend appender;
            ChannelNameBuilder<NotMemberAppend> builder(this, appender);
            SendToOne(builder, guid);
        }
        return;
    }

    player->LeftChannel(this);

    if (send)
    {
        /*
        YouLeftAppend appender;
        ChannelNameBuilder<YouLeftAppend> builder(this, appender);
        SendToOne(builder, guid);
        */

        auto builder = [&](LocaleConstant locale)
        {
            LocaleConstant localeIdx = sWorld->GetAvailableDbcLocale(locale);

            WorldPackets::Channel::ChannelNotifyLeft* notify = new WorldPackets::Channel::ChannelNotifyLeft();
            notify->Channel = GetName(localeIdx);
            notify->ChatChannelID = 0;
            //notify->Suspended = false;
            return notify;
        };

        SendToOne(builder, guid);
    }

    PlayerInfo& info = _playersStore.at(guid);
    bool changeowner = info.IsOwner();
    _playersStore.erase(guid);

    if (_announceEnabled && !player->GetSession()->HasPermission(rbac::RBAC_PERM_SILENTLY_JOIN_CHANNEL))
    {
        LeftAppend appender(guid);
        ChannelNameBuilder<LeftAppend> builder(this, appender);
        SendToAll(builder);
    }

    LeaveNotify(player);

    if (!IsConstant())
    {
        // Update last_used timestamp in db
        UpdateChannelUseageInDB();

        // If the channel owner left and there are still playersStore inside, pick a new owner
        // do not pick invisible gm owner unless there are only invisible gms in that channel (rare)
        if (changeowner && _ownershipEnabled && !_playersStore.empty())
        {
            PlayerContainer::iterator itr;
            for (itr = _playersStore.begin(); itr != _playersStore.end(); ++itr)
            {
                if (!itr->second.IsInvisible())
                    break;
            }

            if (itr == _playersStore.end())
                itr = _playersStore.begin();

            ObjectGuid const& newowner = itr->first;
            itr->second.SetModerator(true);

            SetOwner(newowner);

            // if the new owner is invisible gm, set flag to automatically choose a new owner
            if (itr->second.IsInvisible())
                _isOwnerInvisible = true;
        }
    }
}
Example #12
0
void Joiner::Worker::doRun() {
    LayerTagManager& tagManager = lattice_.getLayerTagManager();
    LayerTagMask leftMask = tagManager.getAlternativeMaskFromTagNames(
                                processor_.leftMaskSpecification_);
    LayerTagMask rightMask = tagManager.getAlternativeMaskFromTagNames(
                                 processor_.rightMaskSpecification_);

    lattice_.addTagMaskIndex_(leftMask);
    lattice_.addTagMaskIndex_(rightMask);

    LayerTagCollection providedTags = tagManager.createTagCollection(
                                          processor_.outTags_);

    LayerTagCollection providedTagsPlane = tagManager.onlyPlaneTags(providedTags);

    Lattice::EdgesSortedBySourceIterator leftIter(lattice_, leftMask);

    while (leftIter.hasNext()) {
        Lattice::EdgeDescriptor edge = leftIter.next();

        boost::optional<Lattice::EdgeDescriptor> parent = lattice_.getParent(edge);

        bool foundRightEdge = false;

        if (parent) {
            std::vector<Lattice::EdgeDescriptor> rightEdges =
                lattice_.getChildren(*parent, rightMask);

            BOOST_FOREACH(Lattice::EdgeDescriptor rightEdge, rightEdges) {
                foundRightEdge = true;

                std::string category =
                    lattice_.getAnnotationCategory(
                        processor_.takeLeftCategory_ ? edge : rightEdge);
                std::string text =
                    lattice_.getAnnotationText(
                        processor_.takeLeftText_ ? edge : rightEdge);

                AnnotationItem attrsSource
                    = lattice_.getEdgeAnnotationItem(
                          (processor_.handlingAttributes_ ==
                           TAKE_RIGHT_ATTRIBUTES)
                          ? rightEdge
                          : edge);

                AnnotationItem annotationItem(
                    attrsSource, category, StringFrag(text));

                if (processor_.handlingAttributes_ ==
                        MERGE_ATTRIBUTES) {
                    lattice_.getAnnotationItemManager().addValues(
                        annotationItem,
                        lattice_.getEdgeAnnotationItem(rightEdge));
                }

                Lattice::EdgeSequence::Builder builder(lattice_);

                builder.addEdge(edge);
                builder.addEdge(rightEdge);

                Lattice::VertexDescriptor fromVertex = lattice_.getEdgeSource(edge);
                Lattice::VertexDescriptor toVertex = lattice_.getEdgeTarget(edge);

                lattice_.addEdge(
                    fromVertex,
                    toVertex,
                    annotationItem,
                    providedTags,
                    builder.build());
            }
        }

        if (processor_.extendedOuterJoin_ || (!foundRightEdge && processor_.outerJoin_)) {

            LayerTagCollection edgePlane = tagManager.onlyPlaneTags(
                                               lattice_.getEdgeLayerTags(edge));

            // if this is the same plane, we have to avoid circular
            // references
            if (providedTagsPlane == edgePlane)
                lattice_.addPartitionToEdge(
                    edge,
                    providedTags);
            else {
                Lattice::EdgeSequence::Builder builder(lattice_);
                builder.addEdge(edge);

                Lattice::VertexDescriptor fromVertex = lattice_.getEdgeSource(edge);
                Lattice::VertexDescriptor toVertex = lattice_.getEdgeTarget(edge);

                lattice_.addEdge(
                    fromVertex,
                    toVertex,
                    lattice_.getEdgeAnnotationItem(edge),
                    providedTags,
                    builder.build());
            }
        }
    }
Example #13
0
bool FixWinding(SkPath* path) {
    SkPath::FillType fillType = path->getFillType();
    if (fillType == SkPath::kInverseEvenOdd_FillType) {
        fillType = SkPath::kInverseWinding_FillType;
    } else if (fillType == SkPath::kEvenOdd_FillType) {
        fillType = SkPath::kWinding_FillType;
    }
    SkPathPriv::FirstDirection dir;
    if (one_contour(*path) && SkPathPriv::CheapComputeFirstDirection(*path, &dir)) {
        if (dir != SkPathPriv::kCCW_FirstDirection) {
            SkPath temp;
            temp.reverseAddPath(*path);
            *path = temp;
        }
        path->setFillType(fillType);
        return true;
    }
    SkChunkAlloc allocator(4096);
    SkOpContourHead contourHead;
    SkOpGlobalState globalState(nullptr, &contourHead  SkDEBUGPARAMS(false)
            SkDEBUGPARAMS(nullptr));
    SkOpEdgeBuilder builder(*path, &contourHead, &allocator, &globalState);
    builder.finish(&allocator);
    if (!contourHead.next()) {
        return false;
    }
    contourHead.resetReverse();
    bool writePath = false;
    SkOpSpan* topSpan;
    globalState.setPhase(SkOpGlobalState::kFixWinding);
    while ((topSpan = FindSortableTop(&contourHead))) {
        SkOpSegment* topSegment = topSpan->segment();
        SkOpContour* topContour = topSegment->contour();
        SkASSERT(topContour->isCcw() >= 0);
#if DEBUG_WINDING
        SkDebugf("%s id=%d nested=%d ccw=%d\n",  __FUNCTION__,
                topSegment->debugID(), globalState.nested(), topContour->isCcw());
#endif
        if ((globalState.nested() & 1) != SkToBool(topContour->isCcw())) {
            topContour->setReverse();
            writePath = true;
        }
        topContour->markDone();
        globalState.clearNested();
    }
    if (!writePath) {
        path->setFillType(fillType);
        return true;
    }
    SkPath empty;
    SkPathWriter woundPath(empty);
    SkOpContour* test = &contourHead;
    do {
        if (test->reversed()) {
            test->toReversePath(&woundPath);
        } else {
            test->toPath(&woundPath);
        }
    } while ((test = test->next()));
    *path = *woundPath.nativePath();
    path->setFillType(fillType);
    return true;
}
Example #14
0
/*
    check start and end of each contour
    if not the same, record them
    match them up
    connect closest
    reassemble contour pieces into new path
*/
void Assemble(const SkPathWriter& path, SkPathWriter* simple) {
#if DEBUG_PATH_CONSTRUCTION
    SkDebugf("%s\n", __FUNCTION__);
#endif
    SkTArray<SkOpContour> contours;
    SkOpEdgeBuilder builder(path, contours);
    builder.finish();
    int count = contours.count();
    int outer;
    SkTArray<int, true> runs(count);  // indices of partial contours
    for (outer = 0; outer < count; ++outer) {
        const SkOpContour& eContour = contours[outer];
        const SkPoint& eStart = eContour.start();
        const SkPoint& eEnd = eContour.end();
#if DEBUG_ASSEMBLE
        SkDebugf("%s contour", __FUNCTION__);
        if (!approximatelyEqual(eStart, eEnd)) {
            SkDebugf("[%d]", runs.count());
        } else {
            SkDebugf("   ");
        }
        SkDebugf(" start=(%1.9g,%1.9g) end=(%1.9g,%1.9g)\n",
                 eStart.fX, eStart.fY, eEnd.fX, eEnd.fY);
#endif
        if (approximatelyEqual(eStart, eEnd)) {
            eContour.toPath(simple);
            continue;
        }
        runs.push_back(outer);
    }
    count = runs.count();
    if (count == 0) {
        return;
    }
    SkTArray<int, true> sLink, eLink;
    sLink.push_back_n(count);
    eLink.push_back_n(count);
    int rIndex, iIndex;
    for (rIndex = 0; rIndex < count; ++rIndex) {
        sLink[rIndex] = eLink[rIndex] = SK_MaxS32;
    }
    const int ends = count * 2;  // all starts and ends
    const int entries = (ends - 1) * count;  // folded triangle : n * (n - 1) / 2
    SkTArray<double, true> distances;
    distances.push_back_n(entries);
    for (rIndex = 0; rIndex < ends - 1; ++rIndex) {
        outer = runs[rIndex >> 1];
        const SkOpContour& oContour = contours[outer];
        const SkPoint& oPt = rIndex & 1 ? oContour.end() : oContour.start();
        const int row = rIndex < count - 1 ? rIndex * ends : (ends - rIndex - 2)
                        * ends - rIndex - 1;
        for (iIndex = rIndex + 1; iIndex < ends; ++iIndex) {
            int inner = runs[iIndex >> 1];
            const SkOpContour& iContour = contours[inner];
            const SkPoint& iPt = iIndex & 1 ? iContour.end() : iContour.start();
            double dx = iPt.fX - oPt.fX;
            double dy = iPt.fY - oPt.fY;
            double dist = dx * dx + dy * dy;
            distances[row + iIndex] = dist;  // oStart distance from iStart
        }
    }
    SkTArray<int, true> sortedDist;
    sortedDist.push_back_n(entries);
    for (rIndex = 0; rIndex < entries; ++rIndex) {
        sortedDist[rIndex] = rIndex;
    }
    SkTQSort<int>(sortedDist.begin(), sortedDist.end() - 1, DistanceLessThan(distances.begin()));
    int remaining = count;  // number of start/end pairs
    for (rIndex = 0; rIndex < entries; ++rIndex) {
        int pair = sortedDist[rIndex];
        int row = pair / ends;
        int col = pair - row * ends;
        int thingOne = row < col ? row : ends - row - 2;
        int ndxOne = thingOne >> 1;
        bool endOne = thingOne & 1;
        int* linkOne = endOne ? eLink.begin() : sLink.begin();
        if (linkOne[ndxOne] != SK_MaxS32) {
            continue;
        }
        int thingTwo = row < col ? col : ends - row + col - 1;
        int ndxTwo = thingTwo >> 1;
        bool endTwo = thingTwo & 1;
        int* linkTwo = endTwo ? eLink.begin() : sLink.begin();
        if (linkTwo[ndxTwo] != SK_MaxS32) {
            continue;
        }
        SkASSERT(&linkOne[ndxOne] != &linkTwo[ndxTwo]);
        bool flip = endOne == endTwo;
        linkOne[ndxOne] = flip ? ~ndxTwo : ndxTwo;
        linkTwo[ndxTwo] = flip ? ~ndxOne : ndxOne;
        if (!--remaining) {
            break;
        }
    }
    SkASSERT(!remaining);
#if DEBUG_ASSEMBLE
    for (rIndex = 0; rIndex < count; ++rIndex) {
        int s = sLink[rIndex];
        int e = eLink[rIndex];
        SkDebugf("%s %c%d <- s%d - e%d -> %c%d\n", __FUNCTION__, s < 0 ? 's' : 'e',
                 s < 0 ? ~s : s, rIndex, rIndex, e < 0 ? 'e' : 's', e < 0 ? ~e : e);
    }
#endif
    rIndex = 0;
    do {
        bool forward = true;
        bool first = true;
        int sIndex = sLink[rIndex];
        SkASSERT(sIndex != SK_MaxS32);
        sLink[rIndex] = SK_MaxS32;
        int eIndex;
        if (sIndex < 0) {
            eIndex = sLink[~sIndex];
            sLink[~sIndex] = SK_MaxS32;
        } else {
            eIndex = eLink[sIndex];
            eLink[sIndex] = SK_MaxS32;
        }
        SkASSERT(eIndex != SK_MaxS32);
#if DEBUG_ASSEMBLE
        SkDebugf("%s sIndex=%c%d eIndex=%c%d\n", __FUNCTION__, sIndex < 0 ? 's' : 'e',
                 sIndex < 0 ? ~sIndex : sIndex, eIndex < 0 ? 's' : 'e',
                 eIndex < 0 ? ~eIndex : eIndex);
#endif
        do {
            outer = runs[rIndex];
            const SkOpContour& contour = contours[outer];
            if (first) {
                first = false;
                const SkPoint* startPtr = &contour.start();
                simple->deferredMove(startPtr[0]);
            }
            if (forward) {
                contour.toPartialForward(simple);
            } else {
                contour.toPartialBackward(simple);
            }
#if DEBUG_ASSEMBLE
            SkDebugf("%s rIndex=%d eIndex=%s%d close=%d\n", __FUNCTION__, rIndex,
                     eIndex < 0 ? "~" : "", eIndex < 0 ? ~eIndex : eIndex,
                     sIndex == ((rIndex != eIndex) ^ forward ? eIndex : ~eIndex));
#endif
            if (sIndex == ((rIndex != eIndex) ^ forward ? eIndex : ~eIndex)) {
                simple->close();
                break;
            }
            if (forward) {
                eIndex = eLink[rIndex];
                SkASSERT(eIndex != SK_MaxS32);
                eLink[rIndex] = SK_MaxS32;
                if (eIndex >= 0) {
                    SkASSERT(sLink[eIndex] == rIndex);
                    sLink[eIndex] = SK_MaxS32;
                } else {
                    SkASSERT(eLink[~eIndex] == ~rIndex);
                    eLink[~eIndex] = SK_MaxS32;
                }
            } else {
                eIndex = sLink[rIndex];
                SkASSERT(eIndex != SK_MaxS32);
                sLink[rIndex] = SK_MaxS32;
                if (eIndex >= 0) {
                    SkASSERT(eLink[eIndex] == rIndex);
                    eLink[eIndex] = SK_MaxS32;
                } else {
                    SkASSERT(sLink[~eIndex] == ~rIndex);
                    sLink[~eIndex] = SK_MaxS32;
                }
            }
            rIndex = eIndex;
            if (rIndex < 0) {
                forward ^= 1;
                rIndex = ~rIndex;
            }
        } while (true);
        for (rIndex = 0; rIndex < count; ++rIndex) {
            if (sLink[rIndex] != SK_MaxS32) {
                break;
            }
        }
    } while (rIndex < count);
#if DEBUG_ASSEMBLE
    for (rIndex = 0; rIndex < count; ++rIndex) {
        SkASSERT(sLink[rIndex] == SK_MaxS32);
        SkASSERT(eLink[rIndex] == SK_MaxS32);
    }
#endif
}
Example #15
0
void DolphinAnalytics::MakePerGameBuilder()
{
  Common::AnalyticsReportBuilder builder(m_base_builder);

  // Gameid.
  builder.AddData("gameid", SConfig::GetInstance().GetGameID());

  // Unique id bound to the gameid.
  builder.AddData("id", MakeUniqueId(SConfig::GetInstance().GetGameID()));

  // Configuration.
  builder.AddData("cfg-dsp-hle", SConfig::GetInstance().bDSPHLE);
  builder.AddData("cfg-dsp-jit", SConfig::GetInstance().m_DSPEnableJIT);
  builder.AddData("cfg-dsp-thread", SConfig::GetInstance().bDSPThread);
  builder.AddData("cfg-cpu-thread", SConfig::GetInstance().bCPUThread);
  builder.AddData("cfg-fastmem", SConfig::GetInstance().bFastmem);
  builder.AddData("cfg-syncgpu", SConfig::GetInstance().bSyncGPU);
  builder.AddData("cfg-audio-backend", SConfig::GetInstance().sBackend);
  builder.AddData("cfg-oc-enable", SConfig::GetInstance().m_OCEnable);
  builder.AddData("cfg-oc-factor", SConfig::GetInstance().m_OCFactor);
  builder.AddData("cfg-render-to-main", SConfig::GetInstance().bRenderToMain);
  if (g_video_backend)
  {
    builder.AddData("cfg-video-backend", g_video_backend->GetName());
  }

  // Video configuration.
  builder.AddData("cfg-gfx-multisamples", g_Config.iMultisamples);
  builder.AddData("cfg-gfx-ssaa", g_Config.bSSAA);
  builder.AddData("cfg-gfx-anisotropy", g_Config.iMaxAnisotropy);
  builder.AddData("cfg-gfx-vsync", g_Config.bVSync);
  builder.AddData("cfg-gfx-aspect-ratio", static_cast<int>(g_Config.aspect_mode));
  builder.AddData("cfg-gfx-efb-access", g_Config.bEFBAccessEnable);
  builder.AddData("cfg-gfx-efb-copy-format-changes", g_Config.bEFBEmulateFormatChanges);
  builder.AddData("cfg-gfx-efb-copy-ram", !g_Config.bSkipEFBCopyToRam);
  builder.AddData("cfg-gfx-xfb-copy-ram", !g_Config.bSkipXFBCopyToRam);
  builder.AddData("cfg-gfx-immediate-xfb", !g_Config.bImmediateXFB);
  builder.AddData("cfg-gfx-efb-copy-scaled", g_Config.bCopyEFBScaled);
  builder.AddData("cfg-gfx-internal-resolution", g_Config.iEFBScale);
  builder.AddData("cfg-gfx-tc-samples", g_Config.iSafeTextureCache_ColorSamples);
  builder.AddData("cfg-gfx-stereo-mode", static_cast<int>(g_Config.stereo_mode));
  builder.AddData("cfg-gfx-per-pixel-lighting", g_Config.bEnablePixelLighting);
  builder.AddData("cfg-gfx-shader-compilation-mode", GetShaderCompilationMode(g_Config));
  builder.AddData("cfg-gfx-wait-for-shaders", g_Config.bWaitForShadersBeforeStarting);
  builder.AddData("cfg-gfx-fast-depth", g_Config.bFastDepthCalc);
  builder.AddData("cfg-gfx-vertex-rounding", g_Config.UseVertexRounding());

  // GPU features.
  if (g_Config.iAdapter < static_cast<int>(g_Config.backend_info.Adapters.size()))
  {
    builder.AddData("gpu-adapter", g_Config.backend_info.Adapters[g_Config.iAdapter]);
  }
  else if (!g_Config.backend_info.AdapterName.empty())
  {
    builder.AddData("gpu-adapter", g_Config.backend_info.AdapterName);
  }
  builder.AddData("gpu-has-exclusive-fullscreen",
                  g_Config.backend_info.bSupportsExclusiveFullscreen);
  builder.AddData("gpu-has-dual-source-blend", g_Config.backend_info.bSupportsDualSourceBlend);
  builder.AddData("gpu-has-primitive-restart", g_Config.backend_info.bSupportsPrimitiveRestart);
  builder.AddData("gpu-has-oversized-viewports", g_Config.backend_info.bSupportsOversizedViewports);
  builder.AddData("gpu-has-geometry-shaders", g_Config.backend_info.bSupportsGeometryShaders);
  builder.AddData("gpu-has-3d-vision", g_Config.backend_info.bSupports3DVision);
  builder.AddData("gpu-has-early-z", g_Config.backend_info.bSupportsEarlyZ);
  builder.AddData("gpu-has-binding-layout", g_Config.backend_info.bSupportsBindingLayout);
  builder.AddData("gpu-has-bbox", g_Config.backend_info.bSupportsBBox);
  builder.AddData("gpu-has-fragment-stores-and-atomics",
                  g_Config.backend_info.bSupportsFragmentStoresAndAtomics);
  builder.AddData("gpu-has-gs-instancing", g_Config.backend_info.bSupportsGSInstancing);
  builder.AddData("gpu-has-post-processing", g_Config.backend_info.bSupportsPostProcessing);
  builder.AddData("gpu-has-palette-conversion", g_Config.backend_info.bSupportsPaletteConversion);
  builder.AddData("gpu-has-clip-control", g_Config.backend_info.bSupportsClipControl);
  builder.AddData("gpu-has-ssaa", g_Config.backend_info.bSupportsSSAA);

  // NetPlay / recording.
  builder.AddData("netplay", NetPlay::IsNetPlayRunning());
  builder.AddData("movie", Movie::IsMovieActive());

  // Controller information
  // We grab enough to tell what percentage of our users are playing with keyboard/mouse, some kind
  // of gamepad
  // or the official gamecube adapter.
  builder.AddData("gcadapter-detected", GCAdapter::IsDetected());
  builder.AddData("has-controller", Pad::GetConfig()->IsControllerControlledByGamepadDevice(0) ||
                                        GCAdapter::IsDetected());

  m_per_game_builder = builder;
}
void MPIWorkerMaster::run()
{
	Profiler::getInstance().setEnabled(true);

	CriticalDegree degree;
	//FlightDataReader reader("c:\\basic1.txt");
	FlightDataReader reader("c:\\basic2.txt");
	//FlightDataReader reader("c:\\big1.txt");
	//FlightDataReader reader("c:\\big2.txt");

	echo(MakeString() << "Load data... (" << reader.getFileName() << ")");
	reader.open();
	reader.readHeader();

	Profiler::getInstance().start("1. Read flights data");
	// 1. Read flights data
	std::vector<Flight> flights = reader.readFlights();
	Profiler::getInstance().finish();

 	ProjectInfo projectInfo = reader.getProjectInfo();
	echo(MakeString() << "Project info: " << projectInfo.dump().str());

	//Init available slaves (if any) with project info (mSlaveQueue)
	initSlaves(projectInfo);

	// 2. Build flight paths
	// OpenMP splitted by number of flights ()
	buildFlightsPathsParallel(projectInfo, flights);

	// Calculate total number of project spaces to be processed
	int numOfTasks = calcNumberOfTasks(projectInfo);
	echo(MakeString() << "Max number of threads: " << omp_get_max_threads());		
	echo(MakeString() << "Total number of tasks: " << numOfTasks);
	echo("Processing...");

	int progress = 1;
	Profiler::getInstance().start("Process project spaces");
	ProjectSpaceBuilder builder(projectInfo, flights);
	// 3. Calculate Critical Degree
	while(builder.nextTime()) {
		ProjectSpace projectSpace = builder.build();

		// LB - Have free workers send more tasks
		if (mSlaveQueue.size() > 0) {
			sendTask(projectSpace);
		} else { 
			CriticalLevel level = executeTask(projectSpace);
			degree.addCriticalLevel(level);
		}

		collectSlaveResults(degree);

		if (progress % 10000 == 0) {
			echo (MakeString() << " Progress: " << progress);
		}
		progress++;
	}
	Profiler::getInstance().finish();

	echo("Collect results from still running slaves.");
	while(mSlaveRunningTasks > 0) {
		collectSlaveResults(degree);
	}
	sendSlavesFinishSignal();
	
	printResult(degree);
}
static sk_sp<GrTextureProxy> create_profile_texture(GrResourceProvider* resourceProvider,
                                                    const SkRect& circle,
                                                    float sigma,
                                                    float* solidRadius, float* textureRadius) {
    float circleR = circle.width() / 2.0f;
    // Profile textures are cached by the ratio of sigma to circle radius and by the size of the
    // profile texture (binned by powers of 2).
    SkScalar sigmaToCircleRRatio = sigma / circleR;
    // When sigma is really small this becomes a equivalent to convolving a Gaussian with a half-
    // plane. Similarly, in the extreme high ratio cases circle becomes a point WRT to the Guassian
    // and the profile texture is a just a Gaussian evaluation. However, we haven't yet implemented
    // this latter optimization.
    sigmaToCircleRRatio = SkTMin(sigmaToCircleRRatio, 8.f);
    SkFixed sigmaToCircleRRatioFixed;
    static const SkScalar kHalfPlaneThreshold = 0.1f;
    bool useHalfPlaneApprox = false;
    if (sigmaToCircleRRatio <= kHalfPlaneThreshold) {
        useHalfPlaneApprox = true;
        sigmaToCircleRRatioFixed = 0;
        *solidRadius = circleR - 3 * sigma;
        *textureRadius = 6 * sigma;
    } else {
        // Convert to fixed point for the key.
        sigmaToCircleRRatioFixed = SkScalarToFixed(sigmaToCircleRRatio);
        // We shave off some bits to reduce the number of unique entries. We could probably shave
        // off more than we do.
        sigmaToCircleRRatioFixed &= ~0xff;
        sigmaToCircleRRatio = SkFixedToScalar(sigmaToCircleRRatioFixed);
        sigma = circleR * sigmaToCircleRRatio;
        *solidRadius = 0;
        *textureRadius = circleR + 3 * sigma;
    }

    static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
    GrUniqueKey key;
    GrUniqueKey::Builder builder(&key, kDomain, 1);
    builder[0] = sigmaToCircleRRatioFixed;
    builder.finish();

    sk_sp<GrTextureProxy> blurProfile = resourceProvider->findProxyByUniqueKey(key);
    if (!blurProfile) {
        static constexpr int kProfileTextureWidth = 512;
        GrSurfaceDesc texDesc;
        texDesc.fWidth = kProfileTextureWidth;
        texDesc.fHeight = 1;
        texDesc.fConfig = kAlpha_8_GrPixelConfig;

        std::unique_ptr<uint8_t[]> profile(nullptr);
        if (useHalfPlaneApprox) {
            profile.reset(create_half_plane_profile(kProfileTextureWidth));
        } else {
            // Rescale params to the size of the texture we're creating.
            SkScalar scale = kProfileTextureWidth / *textureRadius;
            profile.reset(create_circle_profile(sigma * scale, circleR * scale,
                                                kProfileTextureWidth));
        }

        blurProfile = GrSurfaceProxy::MakeDeferred(resourceProvider,
                                                   texDesc, SkBudgeted::kYes, profile.get(), 0);
        if (!blurProfile) {
            return nullptr;
        }

        resourceProvider->assignUniqueKeyToProxy(key, blurProfile.get());
    }

    return blurProfile;
}
Example #18
0
// ---------------------------------------------------------------------------
//  analyze
// ---------------------------------------------------------------------------
//! Analyze a range of (mono) samples at the given sample rate      
//! (in Hz) and store the extracted Partials in the Analyzer's
//! PartialList (std::list of Partials). Use the specified envelope
//! as a frequency reference for Partial tracking.
//! 
//! \param bufBegin is a pointer to a buffer of floating point samples
//! \param bufEnd is (one-past) the end of a buffer of floating point 
//! samples
//! \param srate is the sample rate of the samples in the buffer
//! \param reference is an Envelope having the approximate
//! frequency contour expected of the resulting Partials.
//
void 
Analyzer::analyze( const double * bufBegin, const double * bufEnd, double srate,
                   const Envelope & reference )
{ 
    //  configure the reassigned spectral analyzer, 
    //  always use odd-length windows:

    //  Kaiser window
    double winshape = KaiserWindow::computeShape( sidelobeLevel() );
    long winlen = KaiserWindow::computeLength( windowWidth() / srate, winshape );    
    if (! (winlen % 2)) 
    {
        ++winlen;
    }
    debugger << "Using Kaiser window of length " << winlen << endl;
    
    std::vector< double > window( winlen );
    KaiserWindow::buildWindow( window, winshape );
    
    std::vector< double > windowDeriv( winlen );
    KaiserWindow::buildTimeDerivativeWindow( windowDeriv, winshape );
       
    ReassignedSpectrum spectrum( window, windowDeriv );   
    
    //  configure the peak selection and partial formation policies:
    SpectralPeakSelector selector( srate, m_cropTime );
    PartialBuilder builder( m_freqDrift, reference );
    
    //  configure bw association policy, unless
    //  bandwidth association is disabled:
    std::unique_ptr< AssociateBandwidth > bwAssociator;
    if( m_bwAssocParam > 0 )
    {
        debugger << "Using bandwidth association regions of width " 
                 << bwRegionWidth() << " Hz" << endl;
        bwAssociator.reset( new AssociateBandwidth( bwRegionWidth(), srate ) );
    }
    else
    {
        debugger << "Bandwidth association disabled" << endl;
    }

    //  reset envelope builders:
    m_ampEnvBuilder->reset();
    m_f0Builder->reset();
    
    m_partials.clear();
        
    try 
    { 
        const double * winMiddle = bufBegin; 

        //  loop over short-time analysis frames:
        while ( winMiddle < bufEnd )
        {
            //  compute the time of this analysis frame:
            const double currentFrameTime = long(winMiddle - bufBegin) / srate;
            
            //  compute reassigned spectrum:
            //  sampsBegin is the position of the first sample to be transformed,
            //  sampsEnd is the position after the last sample to be transformed.
            //  (these computations work for odd length windows only)
            const double * sampsBegin = std::max( winMiddle - (winlen / 2), bufBegin );
            const double * sampsEnd = std::min( winMiddle + (winlen / 2) + 1, bufEnd );
            spectrum.transform( sampsBegin, winMiddle, sampsEnd );
            
             
            //  extract peaks from the spectrum, and thin
            Peaks peaks = selector.selectPeaks( spectrum, m_freqFloor ); 
			Peaks::iterator rejected = thinPeaks( peaks, currentFrameTime );

            //	fix the stored bandwidth values
            //	KLUDGE: need to do this before the bandwidth
            //	associator tries to do its job, because the mixed
            //	derivative is temporarily stored in the Breakpoint 
            //	bandwidth!!! FIX!!!!
            fixBandwidth( peaks );
            
            if ( m_bwAssocParam > 0 )
            {
                bwAssociator->associateBandwidth( peaks.begin(), rejected, peaks.end() );
            }
            
            //  remove rejected Breakpoints (needed above to 
            //  compute bandwidth envelopes):
            peaks.erase( rejected, peaks.end() );
            
            //  estimate the amplitude in this frame:
            m_ampEnvBuilder->build( peaks, currentFrameTime );
                        
            //  collect amplitudes and frequencies and try to 
            //  estimate the fundamental
            m_f0Builder->build( peaks, currentFrameTime );          

            //  form Partials from the extracted Breakpoints:
            builder.buildPartials( peaks, currentFrameTime );
            
            //  slide the analysis window:
            winMiddle += long( m_hopTime * srate ); //  hop in samples, truncated

        }   //  end of loop over short-time frames
        
        //  unwarp the Partial frequency envelopes:
        builder.finishBuilding( m_partials );
        
        //  fix the frequencies and phases to be consistent.
        if ( m_phaseCorrect )
        {
            fixFrequency( m_partials.begin(), m_partials.end() );
        }
        
        
        //  for debugging:
        /*
        if ( ! m_ampEnv.empty() )
        {
            LinearEnvelope::iterator peakpos = 
                std::max_element( m_ampEnv.begin(), m_ampEnv.end(), 
                                  compare2nd<LinearEnvelope::iterator::value_type> );
            notifier << "Analyzer found amp peak at time : " << peakpos->first
                     << " value: " << peakpos->second << endl;
        }
        */
    }
    catch ( Exception & ex ) 
    {
        ex.append( "analysis failed." );
        throw;
    }
}
Example #19
0
	/// TODO: add trivial marker for tagtypes
	bool isTrivial(const TypePtr& type) {
		auto ttype = type.isa<TagTypePtr>();
		if(!ttype) {
			if (core::lang::isArray(type)) {
				// in case of an array, check the enclosed type for triviality
				return isTrivial(core::lang::ArrayType(type).getElementType());
			}
			// non-tag-type & non-array types are always trivial
			return true;
		}

		auto record = ttype->getRecord();

		IRBuilder builder(type->getNodeManager());

		auto containsCtor = [&](const LambdaExprPtr& ctor)->bool {
			return any(record->getConstructors(), [&](const ExpressionPtr& cur) {
				return *builder.normalize(cur) == *builder.normalize(ctor);
			});
		};

		auto containsMemberFunction = [&](const MemberFunctionPtr& member)->bool {
			return any(record->getMemberFunctions(), [&](const MemberFunctionPtr& cur) {
				return *builder.normalize(cur) == *builder.normalize(member);
			});
		};

		auto thisType = builder.refType(builder.tagTypeReference(record->getName()));

		ParentsPtr parents =
				(record.isa<StructPtr>()) ?
				record.as<StructPtr>()->getParents() :
				builder.parents();

		// check for trivial constructors
		bool trivialDefaultConstructor = containsCtor(builder.getDefaultConstructor(thisType, parents, record->getFields()));
		if (!trivialDefaultConstructor) return false;

		bool trivialCopyConstructor = containsCtor(builder.getDefaultCopyConstructor(thisType, parents, record->getFields()));
		if (!trivialCopyConstructor) return false;

		bool trivialMoveConstructor = containsCtor(builder.getDefaultMoveConstructor(thisType, parents, record->getFields()));
		if (!trivialMoveConstructor) return false;


		// check for trivial copy and move assignments
		bool trivialCopyAssignment = containsMemberFunction(builder.getDefaultCopyAssignOperator(thisType, parents, record->getFields()));
		if (!trivialCopyAssignment) return false;

		bool trivialMoveAssignment = containsMemberFunction(builder.getDefaultMoveAssignOperator(thisType, parents, record->getFields()));
		if (!trivialMoveAssignment) return false;

		// check for trivial, non-virtual destructor
		if(record->getDestructor().as<LambdaExprPtr>()->getBody().size() != 0 || record->getDestructorVirtual().getValue()) return false;

		// check for virtual member functions
		for(auto memFun : record->getMemberFunctions()) {
			if(memFun->getVirtualFlag().getValue()) return false;
		}

		if(!record->getPureVirtualMemberFunctions().empty()) return false;

		// check for virtual & non-trivial base classes
		if(ttype->isStruct()) {
			auto stype = ttype->getStruct();
			for(auto par : stype->getParents()) {
				if(par->getVirtual().getValue()) return false;
				// if our direct base class is non-trivial, we cannot be trivial per-se
				if(!isTrivial(par->getType())) return false;
			}
		}

		// check that all non-static members are trivial
		for(auto field : record->getFields()) {
			auto fieldType = field->getType();
			if(!isTrivial(fieldType)) return false;
			//check cpp_ref field types
			if(analysis::isRefType(fieldType) && lang::isCppReference(fieldType)) {
				//TODO this is an over approximation which has to be refined
				return false;
			}
		}

		return true;
	}
/*!
    Service finds existing objects or spawns new object instances and registers them on DBus using a
    hash of the unique instance ID. This registered object has a special metaobject representation
    of the service that is compatible with the QDBus type system.
    
    Client receives a package containing the information to connect an interface to the registered
    DBus object.
*/
void ObjectEndPoint::objectRequest(const QServicePackage& p)
{
    if (p.d->responseType != QServicePackage::NotAResponse ) {
        // Client side
        Q_ASSERT(d->endPointType == ObjectEndPoint::Client);

        d->serviceInstanceId = p.d->instanceId;
        d->entry = p.d->entry;

        Response* response = openRequests()->value(p.d->messageId);
        if (p.d->responseType == QServicePackage::Failed) {
            response->result = 0;
            response->isFinished = true;
            QTimer::singleShot(0, this, SIGNAL(pendingRequestFinished()));
            qWarning() << "Service instantiation failed";
            return;
        }

        // Deserialize meta object and create proxy object
        QServiceProxy* proxy = new QServiceProxy(p.d->payload.toByteArray(), this);
        response->result = reinterpret_cast<void *>(proxy);
        response->isFinished = true;

        // Create DBUS interface by using a hash of the service instance ID
        QString serviceName = "com.nokia.qtmobility.sfw." + p.d->entry.serviceName();
        uint hash = qHash(d->serviceInstanceId.toString());
        QString objPath = "/" + p.d->entry.interfaceName() + "/" + p.d->entry.version() + "/" + QString::number(hash);
        objPath.replace(QString("."), QString("/"));
     
#ifdef DEBUG
        qDebug() << "Client Interface ObjectPath:" << objPath;
#endif
        // Instantiate our DBus interface and its corresponding signals object 
        iface = new QDBusInterface(serviceName, objPath, "", QDBusConnection::sessionBus(), this);
        signalsObject = new QServiceMetaObjectDBus(iface, true);

        // Wake up waiting proxy construction code
        QTimer::singleShot(0, this, SIGNAL(pendingRequestFinished()));

    } else {
        // Service side
        Q_ASSERT(d->endPointType == ObjectEndPoint::Service);

        QServicePackage response = p.createResponse();
        InstanceManager* iManager = InstanceManager::instance();

        // Instantiate service object from type register
        service = iManager->createObjectInstance(p.d->entry, d->serviceInstanceId);
        if (!service) {
            qWarning() << "Cannot instantiate service object";
            dispatch->writePackage(response);
            return;
        }

        // Start DBus connection and register proxy service
	connection = new QDBusConnection(QDBusConnection::sessionBus());
        if (!connection->isConnected()) {
            qWarning() << "Cannot connect to DBus";
        }

        // DBus registration path uses a hash of the service instance ID
        QString serviceName = "com.nokia.qtmobility.sfw." + p.d->entry.serviceName();
        uint hash = qHash(d->serviceInstanceId.toString());
        QString objPath = "/" + p.d->entry.interfaceName() + "/" + p.d->entry.version() + "/" + QString::number(hash);
        objPath.replace(QString("."), QString("/"));

        QServiceMetaObjectDBus *serviceDBus = new QServiceMetaObjectDBus(service);
        connection->registerObject(objPath, serviceDBus, QDBusConnection::ExportAllContents);
       
        // Add new instance to client ownership list
        ClientInstance c;
        c.clientId = p.d->payload.toString();
        c.entry = p.d->entry;
        c.instanceId = d->serviceInstanceId;
        d->clientList << c;

#ifdef DEBUG
        qDebug() << "Service Interface ObjectPath:" << objPath;
        
        const QMetaObject *s_meta = service->metaObject();
        qDebug() << "+++++++++++++++++++++SERVICE+++++++++++++++++++++++";
        qDebug() << s_meta->className();
        qDebug() << "METHOD COUNT: " << s_meta->methodCount();
        for (int i=0; i<s_meta->methodCount(); i++) {
            QMetaMethod mm = s_meta->method(i);

            QString type;
            switch(mm.methodType()) {
                case QMetaMethod::Method:
                    type = "Q_INVOKABLE";
                    break;
                case QMetaMethod::Signal:
                    type = "SIGNAL";
                    break;
                case QMetaMethod::Slot:
                    type = "SLOT";
                    break;
                default:
                    break;
            }

            QString returnType = mm.typeName();
            if (returnType == "") returnType = "void";

            qDebug() << "METHOD" << type << ":" << returnType << mm.signature();
        }
        qDebug() << "++++++++++++++++++++++++++++++++++++++++++++++++++++";
        
        iface = new QDBusInterface(serviceName, objPath, "", QDBusConnection::sessionBus(), this);
        const QMetaObject *i_meta = iface->metaObject();
        qDebug() << "++++++++++++++++++++DBUS SERVICE++++++++++++++++++++";
        qDebug() << i_meta->className();
        qDebug() << "METHOD COUNT: " << i_meta->methodCount();
        for (int i=0; i<i_meta->methodCount(); i++) {
            QMetaMethod mm = i_meta->method(i);

            QString type;
            switch(mm.methodType()) {
                case QMetaMethod::Method:
                    type = "Q_INVOKABLE";
                    break;
                case QMetaMethod::Signal:
                    type = "SIGNAL";
                    break;
                case QMetaMethod::Slot:
                    type = "SLOT";
                    break;
                default:
                    break;
            }

            QString returnType = mm.typeName();
            if (returnType == "") returnType = "void";

            qDebug() << "METHOD" << type << ":" << returnType << mm.signature();
        }
        qDebug() << "+++++++++++++++++++++++++++++++++++++++++++++++++++";
#endif
        
        // Get meta object from type register
        const QMetaObject* meta = iManager->metaObject(p.d->entry);
        if (!meta) {
            qDebug() << "Unknown type" << p.d->entry;
            dispatch->writePackage(response);
            return;
        }

        // Serialize meta object
        QByteArray data;
        QDataStream stream( &data, QIODevice::WriteOnly | QIODevice::Append );
        QMetaObjectBuilder builder(meta);
        builder.serialize(stream);
        
        // Send meta object and instance ID to the client for processing 
        d->entry = p.d->entry;
        response.d->instanceId = d->serviceInstanceId;
        response.d->entry = p.d->entry;
        response.d->responseType = QServicePackage::Success;
        response.d->payload = QVariant(data);
        dispatch->writePackage(response);
    }
}
Example #21
0
void MangoIndex::prepare (Scanner &molfile, Output &output,
                          OsLock *lock_for_exclusive_access)
{
    QS_DEF(Molecule, mol);

    QS_DEF(Array<int>, gross);

    MoleculeAutoLoader loader(molfile);
    _context->setLoaderSettings(loader);
    loader.loadMolecule(mol);

    // Skip all SGroups
    mol.clearSGroups();

    if (_context->allow_non_unique_dearomatization)
        MoleculeDearomatizer::restoreHydrogens(mol, false);

    if (_context->zero_unknown_aromatic_hydrogens)
    {
        mol.restoreAromaticHydrogens();
        for (int i : mol.vertices())
        {
            if (mol.isRSite(i) || mol.isPseudoAtom(i))
                continue;

            if (mol.getAtomAromaticity(i) == ATOM_AROMATIC && mol.getImplicitH_NoThrow(i, -1) == -1)
                mol.setImplicitH(i, 0);
        }
    }

    Molecule::checkForConsistency(mol);

    // Make aromatic molecule
    MoleculeAromatizer::aromatizeBonds(mol, AromaticityOptions::BASIC);

    MangoExact::calculateHash(mol, _hash);

    if (!skip_calculate_fp)
    {
        MoleculeFingerprintBuilder builder(mol, _context->fp_parameters);
        profTimerStart(tfing, "moleculeIndex.createFingerprint");
        builder.process();
        profTimerStop(tfing);

        _fp.copy(builder.get(), _context->fp_parameters.fingerprintSize());
        _fp_sim_bits_count = builder.countBits_Sim();
        output.writeBinaryWord((word)_fp_sim_bits_count);

        const byte *fp_sim_ptr = builder.getSim();
        int fp_sim_size = _context->fp_parameters.fingerprintSizeSim();

        ArrayOutput fp_sim_output(_fp_sim_str);

        for (int i = 0; i < fp_sim_size; i++)
            fp_sim_output.printf("%02X", fp_sim_ptr[i]);

        fp_sim_output.writeChar(0);
    }

    ArrayOutput output_cmf(_cmf);
    {
        // CmfSaver modifies _context->cmf_dict and
        // requires exclusive access for this
        OsLockerNullable locker(lock_for_exclusive_access);

        CmfSaver saver(_context->cmf_dict, output_cmf);

        saver.saveMolecule(mol);

        if (mol.have_xyz)
        {
            ArrayOutput output_xyz(_xyz);
            saver.saveXyz(output_xyz);
        }
        else
            _xyz.clear();
    }

    output.writeArray(_cmf);

    // Save gross formula
    GrossFormula::collect(mol, gross);
    GrossFormula::toString(gross, _gross_str);

    _counted_elems_str.clear();
    _counted_elem_counters.clear();

    ArrayOutput ce_output(_counted_elems_str);

    for (int i = 0; i < (int)NELEM(counted_elements); i++)
    {
        _counted_elem_counters.push(gross[counted_elements[i]]);
        ce_output.printf(", %d", gross[counted_elements[i]]);
    }

    ce_output.writeByte(0);

    // Calculate molecular mass
    MoleculeMass mass_calulator;
    mass_calulator.relative_atomic_mass_map = &_context->relative_atomic_mass_map;
    _molecular_mass = mass_calulator.molecularWeight(mol);
}
Example #22
0
TempStringExprAST::~TempStringExprAST()
{
	llvm::IRBuilder<>	builder(ctx.block);
	llvm::Constant * func_free = qbc::getbuiltinprotype(ctx,"free");
	builder.CreateCall(func_free,this->val);
}
Example #23
0
uint32 CreatureTextMgr::SendChat(Creature* source, uint8 textGroup, uint64 whisperGuid /*= 0*/, ChatMsg msgType /*= CHAT_MSG_ADDON*/, Language language /*= LANG_ADDON*/, CreatureTextRange range /*= TEXT_RANGE_NORMAL*/, uint32 sound /*= 0*/, Team team /*= TEAM_OTHER*/, bool gmOnly /*= false*/, Player* srcPlr /*= NULL*/)
{
    if (!source)
        return 0;

    CreatureTextMap::const_iterator sList = mTextMap.find(source->GetEntry());
    if (sList == mTextMap.end())
    {
        TC_LOG_ERROR(LOG_FILTER_SQL, "CreatureTextMgr: Could not find Text for Creature(%s) Entry %u in 'creature_text' table. Ignoring.", source->GetName().c_str(), source->GetEntry());
        return 0;
    }

    CreatureTextHolder const& textHolder = sList->second;
    CreatureTextHolder::const_iterator itr = textHolder.find(textGroup);
    if (itr == textHolder.end())
    {
        TC_LOG_ERROR(LOG_FILTER_SQL, "CreatureTextMgr: Could not find TextGroup %u for Creature(%s) GuidLow %u Entry %u. Ignoring.", uint32(textGroup), source->GetName().c_str(), source->GetGUIDLow(), source->GetEntry());
        return 0;
    }

    CreatureTextGroup const& textGroupContainer = itr->second;  //has all texts in the group
    CreatureTextRepeatIds repeatGroup = GetRepeatGroup(source, textGroup);//has all textIDs from the group that were already said
    CreatureTextGroup tempGroup;//will use this to talk after sorting repeatGroup

    for (CreatureTextGroup::const_iterator giter = textGroupContainer.begin(); giter != textGroupContainer.end(); ++giter)
        if (std::find(repeatGroup.begin(), repeatGroup.end(), giter->id) == repeatGroup.end())
            tempGroup.push_back(*giter);

    if (tempGroup.empty())
    {
        CreatureTextRepeatMap::iterator mapItr = mTextRepeatMap.find(source->GetGUID());
        if (mapItr != mTextRepeatMap.end())
        {
            CreatureTextRepeatGroup::iterator groupItr = mapItr->second.find(textGroup);
            groupItr->second.clear();
        }

        tempGroup = textGroupContainer;
    }

    uint8 count = 0;
    float lastChance = -1;
    bool isEqualChanced = true;

    float totalChance = 0;

    for (CreatureTextGroup::const_iterator iter = tempGroup.begin(); iter != tempGroup.end(); ++iter)
    {
        if (lastChance >= 0 && lastChance != iter->probability)
            isEqualChanced = false;

        lastChance = iter->probability;
        totalChance += iter->probability;
        ++count;
    }

    int32 offset = -1;
    if (!isEqualChanced)
    {
        for (CreatureTextGroup::const_iterator iter = tempGroup.begin(); iter != tempGroup.end(); ++iter)
        {
            uint32 chance = uint32(iter->probability);
            uint32 r = urand(0, 100);
            ++offset;
            if (r <= chance)
                break;
        }
    }

    uint32 pos = 0;
    if (isEqualChanced || offset < 0)
        pos = urand(0, count - 1);
    else if (offset >= 0)
        pos = offset;

    CreatureTextGroup::const_iterator iter = tempGroup.begin() + pos;

    ChatMsg finalType = (msgType == CHAT_MSG_ADDON) ? iter->type : msgType;
    Language finalLang = (language == LANG_ADDON) ? iter->lang : language;
    uint32 finalSound = sound ? sound : iter->sound;

    if (finalSound)
        SendSound(source, finalSound, finalType, whisperGuid, range, team, gmOnly);

    Unit* finalSource = source;
    if (srcPlr)
        finalSource = srcPlr;

    if (iter->emote)
        SendEmote(finalSource, iter->emote);

    if (srcPlr)
    {
        PlayerTextBuilder builder(source, finalSource, finalType, iter->group, iter->id, finalLang, whisperGuid);
        SendChatPacket(finalSource, builder, finalType, whisperGuid, range, team, gmOnly);
    }
    else
    {
        CreatureTextBuilder builder(finalSource, finalType, iter->group, iter->id, finalLang, whisperGuid);
        SendChatPacket(finalSource, builder, finalType, whisperGuid, range, team, gmOnly);
    }
    if (isEqualChanced || (!isEqualChanced && totalChance == 100.0f))
        SetRepeatId(source, textGroup, iter->id);

    return iter->duration;
}
Example #24
0
/**
 * Updates all the dialogs fields.
 * Should be called on dialog opening as it closes the dialog when the
 * target does not exist.
 */
void
FlarmTrafficDetailsWidget::Update()
{
  TCHAR tmp[200], tmp_id[7];
  const TCHAR *value;

  // Set the dialog caption
  StringFormatUnsafe(tmp, _T("%s (%s)"),
                     _("FLARM Traffic Details"), target_id.Format(tmp_id));
  dialog.SetCaption(tmp);

  // Try to find the target in the FLARMnet database
  /// @todo: make this code a little more usable
  const FlarmNetRecord *record = FlarmDetails::LookupRecord(target_id);
  if (record) {
    // Fill the pilot name field
    SetText(PILOT, record->pilot);

    // Fill the frequency field
    if (!StringIsEmpty(record->frequency))
      value = UnsafeBuildString(tmp, record->frequency.c_str(), _T(" MHz"));
    else
      value = _T("--");
    SetText(RADIO, value);

    // Fill the home airfield field
    SetText(AIRPORT, record->airfield);

    // Fill the plane type field
    SetText(PLANE, record->plane_type);
  } else {
    // Fill the pilot name field
    SetText(PILOT, _T("--"));

    // Fill the frequency field
    SetText(RADIO, _T("--"));

    // Fill the home airfield field
    SetText(AIRPORT, _T("--"));

    // Fill the plane type field
    const FlarmTraffic* target =
      CommonInterface::Basic().flarm.traffic.FindTraffic(target_id);

    const TCHAR* actype;
    if (target == nullptr ||
        (actype = FlarmTraffic::GetTypeString(target->type)) == nullptr)
      actype = _T("--");

    SetText(PLANE, actype);
  }

  // Fill the callsign field (+ registration)
  // note: don't use target->Name here since it is not updated
  //       yet if it was changed
  const TCHAR* cs = FlarmDetails::LookupCallsign(target_id);
  if (cs != nullptr && cs[0] != 0) {
    StringBuilder<TCHAR> builder(tmp, ARRAY_SIZE(tmp));
    builder.Append(cs);
    if (record)
      builder.Append(_T(" ("), record->registration.c_str(), _T(")"));
    value = tmp;
  } else
    value = _T("--");
  SetText(CALLSIGN, value);

  // Update the frequently changing fields too
  UpdateChanging(CommonInterface::Basic());
}
        TEST(TermTableBuilder, GeneralCases)
        {
            // Construct a test environment that provides the ITermTreatment
            // and DocumentFrequencyTable to be used by the TermTableBuilder.
            // The test environment also provides a hand-constructed expected
            // TermTable for verification purposes.
            TestEnvironment environment;

            // Run the TermTableBuilder to configure a TermTable.
            ITermTreatment const & treatment = environment.GetTermTreatment();
            DocumentFrequencyTable const & terms =
                environment.GetDocFrequencyTable();
            IFactSet const & facts = environment.GetFactSet();
            TermTable termTable;
            double density = 0.1;
            double adhocFrequency = 0.0001;
            unsigned c_randomSkipDistance = 0;
            TermTableBuilder builder(density,
                                     adhocFrequency,
                                     treatment,
                                     terms,
                                     facts,
                                     termTable,
                                     c_randomSkipDistance);

            // builder.Print(std::cout);

            //
            // Verify that configured TermTable is the same as the expected
            // TermTable provided by the environment.
            //

            // Ensure that all known terms have the same RowIdSequences.
            // NOTE: This test relies on the existence of a separate unit test
            // for TermTable that ensures that RowIds and Terms are added
            // correctly. Without such a test, a bogus TermTable that ignores
            // all RowId additions would allow TermTableBuilderTest to pass
            // (because they will both return the empty set of rows).
            for (auto term : terms)
            {
                RowIdSequence expected(term.GetTerm(),
                                       environment.GetTermTable());
                RowIdSequence observed(term.GetTerm(), termTable);

                EXPECT_TRUE(std::equal(observed.begin(),
                                       observed.end(),
                                       expected.begin()));
                EXPECT_TRUE(std::equal(expected.begin(),
                                       expected.end(),
                                       observed.begin()));
            }


            // NOTE: This test relies on the existence of a separate unit test
            // for TermTable that ensures that row counts are recorded
            // correctly. Without such a test, a bogus TermTable that ignores
            // all SetRowCounts would allow TermTableBuilderTest to pass.
            for (Rank rank = 0; rank <= c_maxRankValue; ++rank)
            {
                EXPECT_EQ(environment.GetTermTable().GetTotalRowCount(rank),
                          termTable.GetTotalRowCount(rank));
            }

            // TODO: Verify adhoc
            // TODO: Verify facts
            // TODO: Verify row counts.
        }
FXint
GUILoadThread::run() {
    GUINet* net = 0;
    int simStartTime = 0;
    int simEndTime = 0;
    std::vector<std::string> guiSettingsFiles;
    bool osgView = false;
    OptionsCont& oc = OptionsCont::getOptions();

    // within gui-based applications, nothing is reported to the console
    MsgHandler::getMessageInstance()->removeRetriever(&OutputDevice::getDevice("stdout"));
    MsgHandler::getWarningInstance()->removeRetriever(&OutputDevice::getDevice("stderr"));
    MsgHandler::getErrorInstance()->removeRetriever(&OutputDevice::getDevice("stderr"));
    // register message callbacks
    MsgHandler::getMessageInstance()->addRetriever(myMessageRetriever);
    MsgHandler::getErrorInstance()->addRetriever(myErrorRetriever);
    MsgHandler::getWarningInstance()->addRetriever(myWarningRetriever);

    // try to load the given configuration
    if (!initOptions()) {
        // the options are not valid but maybe we want to quit
        GUIGlobals::gQuitOnEnd = oc.getBool("quit-on-end");
        submitEndAndCleanup(net, simStartTime, simEndTime);
        return 0;
    }
    // do this once again to get parsed options
    MsgHandler::initOutputOptions();
    GUIGlobals::gRunAfterLoad = oc.getBool("start");
    GUIGlobals::gQuitOnEnd = oc.getBool("quit-on-end");

    if (!MSFrame::checkOptions()) {
        MsgHandler::getErrorInstance()->inform("Quitting (on error).", false);
        submitEndAndCleanup(net, simStartTime, simEndTime);
        return 0;
    }

    // initialise global settings
    RandHelper::initRandGlobal();
    RandHelper::initRandGlobal(&MSVehicleControl::myVehicleParamsRNG);
    MSFrame::setMSGlobals(oc);
    gAllowTextures = !oc.getBool("disable-textures");
    MSVehicleControl* vehControl = 0;
#ifdef HAVE_INTERNAL
    GUIVisualizationSettings::UseMesoSim = MSGlobals::gUseMesoSim;
    if (MSGlobals::gUseMesoSim) {
        vehControl = new GUIMEVehicleControl();
    } else
#endif
        vehControl = new GUIVehicleControl();

    net = new GUINet(
        vehControl,
        new GUIEventControl(),
        new GUIEventControl(),
        new GUIEventControl());
    GUIEdgeControlBuilder* eb = new GUIEdgeControlBuilder();
    GUIDetectorBuilder db(*net);
    NLJunctionControlBuilder jb(*net, db);
    GUITriggerBuilder tb;
    NLHandler handler("", *net, db, tb, *eb, jb);
    tb.setHandler(&handler);
    NLBuilder builder(oc, *net, *eb, jb, db, handler);
    try {
        MsgHandler::getErrorInstance()->clear();
        MsgHandler::getWarningInstance()->clear();
        MsgHandler::getMessageInstance()->clear();
        if (!builder.build()) {
            throw ProcessError();
        } else {
            net->initGUIStructures();
            simStartTime = string2time(oc.getString("begin"));
            simEndTime = string2time(oc.getString("end"));
            guiSettingsFiles = oc.getStringVector("gui-settings-file");
#ifdef HAVE_INTERNAL
            osgView = oc.getBool("osg-view");
#endif
        }
    } catch (ProcessError& e) {
        if (std::string(e.what()) != std::string("Process Error") && std::string(e.what()) != std::string("")) {
            WRITE_ERROR(e.what());
        }
        MsgHandler::getErrorInstance()->inform("Quitting (on error).", false);
        delete net;
        net = 0;
#ifndef _DEBUG
    } catch (std::exception& e) {
        WRITE_ERROR(e.what());
        delete net;
        net = 0;
#endif
    }
    if (net == 0) {
        MSNet::clearAll();
    }
    delete eb;
    submitEndAndCleanup(net, simStartTime, simEndTime, guiSettingsFiles, osgView);
    return 0;
}
//--------------------------------------------------------------------------------------------------
/// Render the configured scene using the current Camera
//--------------------------------------------------------------------------------------------------
void Rendering::render(OpenGLContext* oglContext)
{
    CVF_ASSERT(m_camera.notNull() && m_camera->viewport());

    CVF_LOG_DEBUG(m_logger, String("Entering Rendering::render(), renderingName='%1'").arg(m_renderingName));

    CVF_CHECK_OGL(oglContext);

    m_performanceInfo.clear();

    ref<Timer> renderTimer;
    if (m_enablePerformanceTiming)
    {
        renderTimer = new Timer;
    }

    // Update any transforms and bounding boxes if a transform tree is used
    if (m_scene.notNull())
    {
        m_scene->updateTransformTree(m_camera.p());
    }

    // Compute visible parts
    // -------------------------------------------------------------------------
    m_visibleParts->setCountZero();
    if (m_scene.notNull())
    {
        m_scene->findVisibleParts(m_visibleParts.p(), *m_camera.p(), *m_cullSettings, m_enableMask);
    }

    if (renderTimer.notNull())
    {
        m_performanceInfo.computeVisiblePartsTime = renderTimer->lapTime();
    }

    m_performanceInfo.visiblePartsCount = m_visibleParts->count();

    // Setup FBO
    // -------------------------------------------------------------------------
    if (m_targetFramebuffer.notNull())
    {
        // Option to sync FBO size to viewport size
        m_targetFramebuffer->applyOpenGL(oglContext);

        String failReason;
        if (!m_targetFramebuffer->isFramebufferComplete(oglContext, &failReason))
        {
            Trace::show(failReason);
            return;
        }
    }
    else
    {
#ifndef CVF_OPENGL_ES
        if (FramebufferObject::supportedOpenGL(oglContext))
        {
            FramebufferObject::useDefaultWindowFramebuffer(oglContext);
        }
#endif
    }

    // Setup camera and view
    // -------------------------------------------------------------------------
    m_camera->viewport()->applyOpenGL(oglContext, m_clearMode);
    m_camera->applyOpenGL();

    // Update dynamic uniforms and dynamic uniform sets
    // -------------------------------------------------------------------------
    updateDynamicUniformSets();
    updateAndCombineGlobalDynamicUniformSets();


    // Build the render queue
    // -------------------------------------------------------------------------
    RenderQueueBuilder builder(m_visibleParts.p(), oglContext, m_camera.p());
    builder.setFixedEffect(m_effectOverride.p());
    if (m_renderQueueSorter.notNull())
    {
        builder.setRequireDistance(m_renderQueueSorter->requireDistance());
        builder.setRequirePixelArea(m_renderQueueSorter->requirePixelArea());
    }

    RenderQueue renderQueue;
    builder.populateRenderQueue(&renderQueue);

    if (renderTimer.notNull())
    {
        m_performanceInfo.buildRenderQueueTime = renderTimer->lapTime();
    }


    // Sort the render queue
    // -------------------------------------------------------------------------
    if (m_renderQueueSorter.notNull())
    {
        m_renderQueueSorter->sort(&renderQueue);

        if (renderTimer.notNull())
        {
            m_performanceInfo.sortRenderQueueTime = renderTimer->lapTime();
        }
    }


    // Render the scene
    // -------------------------------------------------------------------------
    const UniformSet* globalUniformSet = m_combinedGlobalUniformSet.p();
    size_t numPartsToDraw = std::min(m_maxNumPartsToDraw, renderQueue.count());
    m_renderEngine.render(oglContext, &renderQueue, numPartsToDraw, *m_camera, globalUniformSet);

    if (renderTimer.notNull())
    {
        m_performanceInfo.renderEngineTime = renderTimer->lapTime();
    }

    // Render the overlay items
    // Use software rendering if forced or if no support for Shader Programs
    bool useSoftwareRendering = m_renderEngine.isForcedImmediateModeEnabled() || !ShaderProgram::supportedOpenGL(oglContext);
    renderOverlayItems(oglContext, useSoftwareRendering);

    // Update counters
    m_performanceInfo.renderedPartsCount        = m_renderEngine.renderedPartCount();
    m_performanceInfo.vertexCount               = m_renderEngine.renderedVertexCount();
    m_performanceInfo.triangleCount             = m_renderEngine.renderedTriangleCount();
    m_performanceInfo.openGLPrimitiveCount      = m_renderEngine.renderedOpenGLPrimitiveCount();
    m_performanceInfo.applyRenderStateCount     = m_renderEngine.applyRenderStateCount();
    m_performanceInfo.shaderProgramChangesCount = m_renderEngine.shaderProgramChangesCount();

    // Last update before we exit, total render time for this rendering
    if (renderTimer.notNull())
    {
        m_performanceInfo.totalDrawTime = renderTimer->time();
    }

    CVF_CHECK_OGL(oglContext);

    CVF_LOG_DEBUG(m_logger, String("Exiting Rendering::render(), renderingName='%1'").arg(m_renderingName));
}
Example #28
0
int
SubDriver::parse_pub_arg(const ACE_TString& arg)
{
  DBG_ENTRY("SubDriver","parse_pub_arg");

  size_t pos;

  // Find the first ':' character, and make sure it is in a legal spot.
  if ((pos = std::find(arg.c_str(), arg.c_str() + arg.length(), ACE_TEXT(':')) - arg.c_str()) == arg.length()) {
    ACE_ERROR((LM_ERROR,
               "(%P|%t) Bad -p command-line value (%s). Missing ':' char.\n",
               arg.c_str()));
    return -1;
  }

  if (pos == 0) {
    ACE_ERROR((LM_ERROR,
               "(%P|%t) Bad -p command-line value (%s). "
               "':' char cannot be first char.\n",
               arg.c_str()));
    return -1;
  }

  if (pos == (arg.length() - 1)) {
    ACE_ERROR((LM_ERROR,
               "(%P|%t) Bad -p command-line value  (%s) - "
               "':' char cannot be last char.\n",
               arg.c_str()));
    return -1;
  }

  // Parse the pub_id from left of ':' char, and remainder to right of ':'.
  ACE_TString pub_id_str(arg.c_str(), pos);
  this->pub_addr_str_ = arg.c_str() + pos + 1;

  // RepoIds are conventionally created and managed by the DCPSInfoRepo. Those
  // generated here are for the sole purpose of verifying internal behavior.
  OpenDDS::DCPS::RepoIdBuilder builder(pub_id_);

  builder.participantId(1);
  builder.entityKey(ACE_OS::atoi(pub_id_str.c_str()));
  builder.entityKind(OpenDDS::DCPS::ENTITYKIND_USER_WRITER_WITH_KEY);

  // Find the (only) ':' char in the remainder, and make sure it is in
  // a legal spot.
  if ((pos = std::find(pub_addr_str_.c_str(), pub_addr_str_.c_str() + pub_addr_str_.length(), ACE_TEXT(':')) - pub_addr_str_.c_str()) == pub_addr_str_.length()) {
    ACE_ERROR((LM_ERROR,
               "(%P|%t) Bad -p command-line value (%s). "
               "Missing second ':' char.\n",
               arg.c_str()));
    return -1;
  }

  if (pos == 0) {
    ACE_ERROR((LM_ERROR,
               "(%P|%t) Bad -p command-line value (%s) - "
               "Second ':' char immediately follows first ':' char.\n",
               arg.c_str()));
    return -1;
  }

  if (pos == (arg.length() - 1)) {
    ACE_ERROR((LM_ERROR,
               "(%P|%t) Bad -p command-line value (%s) - "
               "Second ':' char cannot be last char.\n",
               arg.c_str()));
    return -1;
  }

  // Use the remainder as the "stringified" ACE_INET_Addr.
  this->pub_addr_ = ACE_INET_Addr(this->pub_addr_str_.c_str());

  return 0;
}
Example #29
0
void Compiler::run(bool isDump, bool isExecute)
{
    if (!isFileExists(filePath)) {
        console("File not exists: " << filePath.toStdString());
        return;
    }

//    QString functionId = functionList.at(0).toMap().value("id").toString();
//        qDebug() << functionId;
//    QVariantList instructionList = sproutDb.readRecords(QString("SELECT * FROM Instructions WHERE functionId=%1").arg(functionId));
//        qDebug() << instructionList;
//    QString instructionId = instructionList.at(0).toMap().value("id").toString();
//    QString instruction = instructionList.at(0).toMap().value("name").toString();
//        qDebug() << instructionId << instruction;
//    QVariantList argumentList = sproutDb.readRecords(QString("SELECT * FROM Arguments WHERE instructionId=%1").arg(instructionId));
//        qDebug() << argumentList;
//    QString argument = argumentList.at(0).toMap().value("arg").toString();
//        qDebug() << argument;

    llvm::LLVMContext& context = llvm::getGlobalContext();
    std::unique_ptr<llvm::Module> modulePtr = llvm::make_unique<llvm::Module>("top", context);
    llvm::Module* module = modulePtr.get();
    llvm::IRBuilder<> builder(context);

    // 'main' function prototype
    llvm::FunctionType* mainType = llvm::FunctionType::get(builder.getVoidTy(), false);
    llvm::Function* mainFunc = llvm::Function::Create(mainType, llvm::Function::ExternalLinkage, "main", module);
    llvm::BasicBlock* entry = llvm::BasicBlock::Create(context, "entrypoint", mainFunc);
    builder.SetInsertPoint(entry);

    // 'print-line' function prototype
//    if (instruction == "print-line") {
//        auto printArg = builder.CreateGlobalStringPtr(QString(argument).toStdString());

//        std::vector<llvm::Type*> putsArgs;
//        putsArgs.push_back(builder.getInt8Ty()->getPointerTo());
//        llvm::ArrayRef<llvm::Type*>  argsRef(putsArgs);

//        llvm::FunctionType* putsType = llvm::FunctionType::get(builder.getInt32Ty(), argsRef, false);
//        llvm::Constant* putsFunc = module->getOrInsertFunction("puts", putsType);

//        builder.CreateCall(putsFunc, printArg);

//    // 'read-line' function prototype
//    } else if (instruction == "read-line") {
//         qDebug() << "readline " << argument;
//    }

    builder.CreateRetVoid();

    if (isDump) {
        module->dump();
    }

    if (isExecute) {
        llvm::InitializeNativeTarget();
        llvm::InitializeNativeTargetAsmPrinter();
        llvm::InitializeNativeTargetAsmParser();

        llvm::ExecutionEngine* engine = llvm::EngineBuilder(std::move(modulePtr)).create();
        engine->finalizeObject(); // memory for generated code marked executable:
                                  // http://lists.cs.uiuc.edu/pipermail/llvmdev/2013-June/062677.html
        engine->runFunction(mainFunc, std::vector<llvm::GenericValue>());
    } else {
        llvm::InitializeAllTargets();
        llvm::InitializeAllTargetMCs();
        llvm::InitializeAllAsmPrinters();
        llvm::InitializeAllAsmParsers();

        llvm::legacy::PassManager pm;

        llvm::TargetOptions options;

        std::string err;

        llvm::Triple triple(module->getTargetTriple());

//        if (triple.getTriple().empty()) {
//            triple.setTriple(llvm::sys::getDefaultTargetTriple());
//        }

        const llvm::Target* target = llvm::TargetRegistry::lookupTarget(triple.getTriple(), err);

        std::string mcpu, featuresStr;

//        llvm::TargetMachine* machineTarget = target->createTargetMachine(triple.getTriple(), mcpu, featuresStr, options);

        QString objPath = filePath.replace(".sprout", ".o");
    //    qDebug() << objPath;

        std::error_code ec;
        llvm::raw_fd_ostream os(objPath.toStdString(), ec, llvm::sys::fs::F_None);
        llvm::formatted_raw_ostream fos(os);

//        if (machineTarget->addPassesToEmitFile(pm, fos, llvm::TargetMachine::CGFT_ObjectFile, false)) {
//            std::cerr << " target does not support generation of this file type!\n";
//            return;
//        }

        bool result = pm.run(*module);
        if (result) {
            QProcess* process = new QProcess();
            QString binPath = objPath;
            binPath.replace(".o", "");
            process->start(QString("gcc %1 -o %2").arg(objPath).arg(binPath));
        }
    }
}
Example #30
0
void OutdoorPvP::SendDefenseMessage(uint32 zoneId, uint32 id)
{
    DefenseMessageBuilder builder(zoneId, id);
    Trinity::LocalizedPacketDo<DefenseMessageBuilder> localizer(builder);
    BroadcastWorker(localizer, zoneId);
}