示例#1
0
void GraphicsContext::strokeEllipseAsPath(const FloatRect& ellipse)
{
    Path path;
    path.addEllipse(ellipse);
    strokePath(path);
}
void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
{
    Path p;
    p.addLineSegment (line, 1.0f);
    fillPath (p, AffineTransform::identity);
}
示例#3
0
void Oscilloscope::paint(juce::Graphics &g)
{
    g.fillAll (Colours::white);
    
    Path path;
    
    float xOffset = 21.f;
    float yOffset = 120.f;
    
    Rectangle<float> rect = logoPath.getBounds();
    Rectangle<int> rect2 = getLocalBounds();
    
    g.setColour (Colours::black);
    g.fillPath (logoPath, RectanglePlacement (RectanglePlacement::stretchToFit)
                .getTransformToFit (logoPath.getBounds(),
                                    getLocalBounds().toFloat()));
    

    // Horizontal zero line.
    path.addLineSegment(Line<float> (xOffset, yOffset, getLocalBounds().getWidth() - xOffset, yOffset), 1.);
    
    g.setColour (Colours::lightgrey);
    g.fillPath (path);
    
    float xIncrement = (getLocalBounds().getWidth() - 2 * xOffset) / (UIConstants::NUMBER_SCOPE_POINTS - 1);
    
    // Now iterate over points.
    int count = 0;
    float alpha = 0;
    for (auto& points : allPoints)
    {
        if ((currentPointsIndex - count + UIConstants::NUMBER_SCOPE_BUFFERS) % UIConstants::NUMBER_SCOPE_BUFFERS == 0)
        {
            // Current array is 'brightest'
            alpha = 1;
        } else
        {
            // Set older immediately to less than 0.5 alpha.
            alpha = 0.3 - ((currentPointsIndex - count + UIConstants::NUMBER_SCOPE_BUFFERS) % UIConstants::NUMBER_SCOPE_BUFFERS) * 0.03 ;
        }
        
//        g.setColour(Colour::fromFloatRGBA(0, 255 , 0, alpha)) ;
        g.setColour(scopeTraceColour.withAlpha(alpha));
        path.clear();

        float x = 0;
        path.startNewSubPath(xOffset, yOffset);
        for (auto& point : points)
        {
//            g.setPixel(x + xOffset, yOffset - 30 * point.x); // point.x in this case is the right value of the stereo pair.
            path.lineTo(x + xOffset, yOffset - 30 * point.x);
            x += xIncrement;
        }
//        path.closeSubPath();
        g.strokePath (path, PathStrokeType (1.0f));
        count++;
        
    }

    
}
示例#4
0
文件: renddlg.cpp 项目: vata/xarino
void RenderDemoDlg::RenderControl(ReDrawInfoType* ExtraInfo)
{
	// Go get a render region
	DocRect VirtualSize(-ExtraInfo->dx/2, -ExtraInfo->dy/2, ExtraInfo->dx/2, ExtraInfo->dy/2);
	RenderRegion* pRender = CreateGRenderRegion(&VirtualSize, ExtraInfo);
	if (pRender!=NULL)
	{
		DialogColourInfo RedrawColours;		// Get a supplier for default dlg colours

		// Render stuff in here
		// Build a Linear fill attribute
		LinearFillAttribute MyGradFill;
		MyGradFill.Colour = DocColour(255, 255, 0);
		MyGradFill.EndColour = DocColour(0, 255, 255);
		MyGradFill.StartPoint = DocCoord(0, ExtraInfo->dy);
		MyGradFill.EndPoint = DocCoord(ExtraInfo->dx, 0);

		// Build a path
		Path InkPath;
		InkPath.Initialise(12,12);
		InkPath.FindStartOfPath();

		// Get the coords used to build a shape
		INT32 dx = ExtraInfo->dx / 2;
		INT32 dy = ExtraInfo->dy / 2;
		INT32 Midx = ExtraInfo->dx / 4;
		INT32 Midy = ExtraInfo->dy / 4;

		// build a circle in the middle of the control
		InkPath.InsertMoveTo(DocCoord(Midx, dy));
		InkPath.InsertCurveTo(DocCoord(Midx+Midx/2, dy), DocCoord(dx, Midy+Midy/2), DocCoord(dx, Midy));
		InkPath.InsertCurveTo(DocCoord(dx, Midy-Midy/2), DocCoord(Midx+Midx/2, 0), DocCoord(Midx, 0));
		InkPath.InsertCurveTo(DocCoord(Midx-Midx/2, 0), DocCoord(0, Midy-Midy/2), DocCoord(0, Midy));
		InkPath.InsertCurveTo(DocCoord(0, Midy+Midy/2), DocCoord(Midx-Midx/2, dy), DocCoord(Midx, dy));
		InkPath.IsFilled = TRUE;
		
		// A Grey colour [...hmmm, it's not a very grey grey any more... oragnge more like]
		DocColour Grey(255,200,0);

		// Render the attributes and the a rectangle
		pRender->SaveContext();
		pRender->SetLineColour(Grey);

		// Draw a rectangle to fill in the background - Fill with Dialogue Background colour
		DocRect DrawMe(0, 0, ExtraInfo->dx, ExtraInfo->dy);
		pRender->SetFillColour(RedrawColours.DialogBack());
		pRender->DrawRect(&VirtualSize);

		// Draw some shapes and stuff
		pRender->SetFillGeometry(&MyGradFill, FALSE);
		pRender->DrawPath(&InkPath);

		// Build a path
		Path TriPath;
		TriPath.Initialise(12,12);
		TriPath.FindStartOfPath();

		// build a circle in the middle of the control
		TriPath.InsertMoveTo(VirtualSize.lo);
		TriPath.InsertLineTo(DocCoord(VirtualSize.hi.x, VirtualSize.lo.y));
		TriPath.InsertLineTo(DocCoord(0, VirtualSize.hi.y));
		TriPath.InsertLineTo(VirtualSize.lo);
		TriPath.IsFilled = TRUE;

		LinearFillAttribute MyTriFill;
		MyTriFill.Colour = ShowFirst ? First : Second;
		MyTriFill.EndColour = DocColour(0,0,0);
		MyTriFill.StartPoint = DocCoord(ExtraInfo->dx, 0);
		MyTriFill.EndPoint = DocCoord(0, ExtraInfo->dy);

		pRender->SetFillGeometry(&MyTriFill, FALSE);
		pRender->DrawPath(&TriPath);

		pRender->RestoreContext();

		// Get rid of the render region
		DestroyGRenderRegion(pRender);
	}

	// and animate it!
	if (ShowFirst)
	{
		INT32 Red, Green, Blue;
		First.GetRGBValue(&Red, &Green, &Blue);

		if (Blue>0)
		{
			// Set the colour back again
			Blue -= 10;
			First.SetRGBValue(Red, Green, Blue);

			// redraw it
			InvalidateGadget(_R(IDC_REDRAW_ME));
		}
	}
	else
	{
		// Set the colour back to how it was
		First.SetRGBValue(255, 0, 250);
	}
}
	// Evaluate the contributions of the given eye and light paths
	void evaluate(GBDPTWorkResult *wr,
		Path &emitterSubpath, std::vector<Path> &sensorSubpath, std::vector<ShiftPathData> &pathData, int vert_b,
		std::vector<Spectrum> &value,  std::vector<Float> &miWeight, std::vector<Float> &valuePdf,
		std::vector<double> &jacobianLP, std::vector<double> &genGeomTermLP, bool *pathSuccess) {

		/* we use fixed neighborhood kernel! Future work will be to extend this to structurally-adaptive neighbours!!! */
		Vector2 shifts[4] = { Vector2(0, -1), Vector2(-1, 0), Vector2(1, 0), Vector2(0, 1) };
		int neighbourCount = 4;

		Point2 initialSamplePos = sensorSubpath[0].vertex(1)->getSamplePosition();
		int pixelIndex = (int)initialSamplePos[0] + (int)initialSamplePos[1] * m_sensor->getFilm()->getSize().x;

		const Scene *scene = m_scene;
		PathEdge  connectionEdge;

		/* combined weights along the two subpaths */
		Spectrum *importanceWeights = (Spectrum *)alloca(emitterSubpath.vertexCount() * sizeof(Spectrum));
		Spectrum **radianceWeights = (Spectrum **)alloca((neighbourCount + 1) * sizeof(Spectrum*));

		/* combined Pdfs along the two subpaths */
		Float *importancePdf = (Float*)alloca(emitterSubpath.vertexCount() * sizeof(Float));
		Float **radiancePdf = (Float **)alloca((neighbourCount + 1) * sizeof(Float*));

		for (int k = 0; k <= neighbourCount; k++){
			radianceWeights[k] = (Spectrum *)alloca(sensorSubpath[0].vertexCount()  * sizeof(Spectrum));
			radiancePdf[k] = (Float *)alloca(sensorSubpath[0].vertexCount() * sizeof(Float));
		}

		/* Compute the importance and radiance data */
		combineImportanceData(emitterSubpath, importanceWeights, importancePdf);
		combineRadianceData(sensorSubpath, pathData, neighbourCount, radianceWeights, radiancePdf);

		/* Allocate space for gradients */
		Spectrum primal = Spectrum(0.f);

		Spectrum *gradient = (Spectrum *)alloca(neighbourCount * sizeof(Spectrum));
		for (int k = 0; k<neighbourCount; k++){
			gradient[k] = Spectrum(0.f);
		}

		Path offsetEmitterSubpath, connectedBasePath;
		Spectrum geomTermBase, connectionPartsBase, offsetImportanceWeight;
		PathEdge connectionEdgeBase;
		bool successConnectBase, successOffsetGen, lightpathSuccess, samplePosValid;
		Float offsetImportancePdf, offsetImportanceGeom;
		Point2 samplePos;

		
		Spectrum visibility = Spectrum(0.f);
		Spectrum light = Spectrum(0.f);


		for (int s = (int)emitterSubpath.vertexCount() - 1; s >= 0; --s) {

			/* Determine the range of sensor vertices to be traversed, while respecting the specified maximum path length */
			int minT = std::max(2 - s, m_config.lightImage ? 1 : 2), // disable t=0 paths
				maxT = (int)sensorSubpath[0].vertexCount() - 1;
			if (m_config.maxDepth != -1)
				maxT = std::min(maxT, m_config.maxDepth + 1 - s);

			for (int t = maxT; t >= minT; --t) {

				samplePosValid = true;

				/* neighbour count and sample position for non-light paths */
				samplePos = initialSamplePos;

				/* if light path can be computed: recalculate pixel position and neighbours*/
				if (t == 1){
					if (sensorSubpath[0].vertex(t)->isSensorSample()&& !sensorSubpath[0].vertex(t)->getSamplePosition(emitterSubpath.vertex(s), samplePos)
						|| !Path::isConnectable_GBDPT(emitterSubpath.vertex(s), m_config.m_shiftThreshold))
						continue;
				}

				int memPointer;

				for (int k = 0; k <= neighbourCount; k++){

					miWeight[k] = 1.f / (s + t + 1);
					pathSuccess[k] = pathData[k].success;
					value[k] = Spectrum(0.f);
					valuePdf[k] = 0.f;

					/* for radiance make sure that offset light paths have the correct value */
					const Spectrum *importanceWeightTmp = &importanceWeights[s],
						           *radianceWeightTmp = &radianceWeights[t == 1 ? 0 : k][t];
					 
					const Float	 *importancePdfTmp = &importancePdf[s],
								 *radiancePdfTmp = &radiancePdf[t == 1 ? 0 : k][t];

					const Path	 *sensorSubpathTmp = &sensorSubpath[k],
								 *emitterSubpathTmp = &emitterSubpath;

					MutationRecord muRec;
					

					/* create the base path on which the shift is applied. changes for every light tracing path */
					if (t == 1 && k == 0){
						pathSuccess[0] = createShiftablePath(connectedBasePath, emitterSubpath, sensorSubpath[0], s, 1,  memPointer);
						m_offsetGenerator->computeMuRec(connectedBasePath, muRec);
						genGeomTermLP[0] =  connectedBasePath.calcSpecularPDFChange(muRec.extra[2], m_offsetGenerator, true);
					}	

					/* if we have a light tracing path we need to modify the emitter-sub path */
					if (t == 1 && k>0 && !value[0].isZero()){
						if (!pathSuccess[0])
							pathSuccess[k] = false;
						else{
							createShiftedLightPath(connectedBasePath, offsetEmitterSubpath, jacobianLP[k - 1], pathSuccess[k], offsetImportanceWeight, offsetImportancePdf, muRec, samplePos, shifts[k-1]/*nIdxL[k - 1]*/, s);
							if (pathSuccess[k]){
								genGeomTermLP[k] =  offsetEmitterSubpath.calcSpecularPDFChange(muRec.extra[2], m_offsetGenerator, true);
								importanceWeightTmp = &offsetImportanceWeight;
								importancePdfTmp = &offsetImportancePdf;
								emitterSubpathTmp = &offsetEmitterSubpath;
							}
							sensorSubpathTmp = &sensorSubpath[0];
						}
					}

					Spectrum geomTerm = Spectrum(0.0);


					do{ //this should really go away at some point...
						if (pathSuccess[k] && pathSuccess[0] && (k == 0 || (valuePdf[0]>0 && !value[0].isZero()))){

							if (!pathData[k].couldConnectAfterB && t > vert_b)
								break;

							PathVertex
								*vsPred = emitterSubpathTmp->vertexOrNull(s - 1),
								*vtPred = sensorSubpathTmp->vertexOrNull(t - 1),
								*vs = emitterSubpathTmp->vertex(s),						//connecting vertex from emitter side
								*vt = sensorSubpathTmp->vertex(t);						//connecting vertex from sensor side
							PathEdge
								*vsEdge = emitterSubpathTmp->edgeOrNull(s - 1),
								*vtEdge = sensorSubpathTmp->edgeOrNull(t - 1);

							/* Allowed remaining number of ENull vertices that can be bridged via pathConnect (negative=arbitrarily many) */
							int remaining = m_config.maxDepth - s - t + 1;

							/* Account for the terms of the measurement contribution function that are coupled to the connection endpoints, i.e. s==0*/
							if (vs->isEmitterSupernode()) {
								/* If possible, convert 'vt' into an emitter sample */
								if (!vt->cast(scene, PathVertex::EEmitterSample) || vt->isDegenerate()){
									valuePdf[k] = *radiancePdfTmp;
									break;
								}

								Spectrum connectionParts = (k > 0 && t > vert_b + 1) ? connectionPartsBase : vs->eval(scene, vsPred, vt, EImportance)    * vt->eval(scene, vtPred, vs, ERadiance);
								if (k == 0) connectionPartsBase = connectionParts;

								value[k] = *radianceWeightTmp * connectionParts;
								valuePdf[k] = *radiancePdfTmp;
							}
							/* Accounts for direct hits of light-subpaths to sensor, i.e t==0. If this happens do not compute gradients but fall back to the T0 mapping */
							else if (vt->isSensorSupernode()) {
								if (!vs->cast(scene, PathVertex::ESensorSample) || vs->isDegenerate() || k > 0) //Note the k>0...
								{
									valuePdf[k] = *importancePdfTmp;
									break;
								}
								/* Make note of the changed pixel sample position */
								if (!vs->getSamplePosition(vsPred, samplePos)){
									valuePdf[k] = *importancePdfTmp;
									break;
								}
								value[k] = *importanceWeightTmp *  vs->eval(scene, vsPred, vt, EImportance)    * vt->eval(scene, vtPred, vs, ERadiance);
								valuePdf[k] = *importancePdfTmp;
							}
							else {
								if (!Path::isConnectable_GBDPT(vs, m_config.m_shiftThreshold)
									|| !Path::isConnectable_GBDPT(vt, m_config.m_shiftThreshold)
									|| vs->getType() == 0 || vt->getType() == 0){
									valuePdf[k] = *importancePdfTmp    * *radiancePdfTmp;
									break;
								}
								Spectrum connectionParts = (k>0 && t>vert_b + 1) ? connectionPartsBase : vs->eval(scene, vsPred, vt, EImportance)    * vt->eval(scene, vtPred, vs, ERadiance);
								if (k == 0) connectionPartsBase = connectionParts;
								value[k] = *importanceWeightTmp * *radianceWeightTmp * connectionParts;
								valuePdf[k] = *importancePdfTmp    * *radiancePdfTmp ;
								vs->measure = vt->measure = EArea;
							}

							if (value[k].isZero() || valuePdf[k]==0) //early exit
								break;

							/* Attempt to connect the two endpoints, which could result in the creation of additional vertices (index-matched boundaries etc.) */
							//only required when connection segment changed from base to offset path
							int interactions = remaining; // backup
							bool successConnect = (k>0 && t>vert_b) ? successConnectBase : connectionEdge.pathConnectAndCollapse(scene, vsEdge, vs, vt, vtEdge, interactions);
							if (k == 0)	successConnectBase = successConnect;

							if (!successConnect){ //early exit
								value[k] = Spectrum(0.f);
								break; 
							}

							//this is the missing geometry factor in c_{s,t} of f_j mentioned in veach thesis equation 10.8
							geomTerm = (k>0 && t>vert_b) ? geomTermBase : connectionEdge.evalCached(vs, vt, PathEdge::EGeneralizedGeometricTerm);
							value[k] *= geomTerm;
							valuePdf[k] *= (t < 2 ? genGeomTermLP[k] : pathData[k].genGeomTerm[t]);

							if (value[k].isZero() || valuePdf[k]==0) //early exit
								break;


							if (k == 0){
								connectionEdgeBase = connectionEdge;
								geomTermBase = geomTerm;

							// using the original routine Path::miWeight is more efficient, but we use the balance heuristic for numberical stability...
							//	miWeight[0] = Path::miWeight(scene, emitterSubpath, &connectionEdge, sensorSubpath[0], s, t, m_config.sampleDirect, m_config.lightImage) / valuePdf[0];
								miWeight[0] = Path::miWeightBaseNoSweep_GBDPT(scene, emitterSubpath, &connectionEdgeBase, sensorSubpath[0],
										*emitterSubpathTmp, &connectionEdge, *sensorSubpathTmp, s, t, m_config.sampleDirect, m_config.lightImage,
										1.0, 2.0, (t<2 ? genGeomTermLP[0] : pathData[0].genGeomTerm[t]), 0.f, vert_b, m_config.m_shiftThreshold) / valuePdf[0];
							}
							else {
								/* compute MIS weight for gradients: 1/sum(p_st(x)^n+p_st(y)^n)*/
								// Note: we use the balance heuristic, not the power heuristic! The latter may cause numerical errors with long paths (since we compute the pdf explicitly)
								// some smarter computation should be done at some point to handle this
								miWeight[k] = Path::miWeightGradNoSweep_GBDPT(scene, emitterSubpath, &connectionEdgeBase, sensorSubpath[0],
									*emitterSubpathTmp, &connectionEdge, *sensorSubpathTmp, s, t, m_config.sampleDirect,  m_config.lightImage,
									(t<2 ? jacobianLP[k - 1] : pathData[k].jacobianDet[t] ), 1.0, 
									(t<2 ? genGeomTermLP[0] : pathData[0].genGeomTerm[t]), (t<2 ? genGeomTermLP[k] : pathData[k].genGeomTerm[t]), 
									vert_b, m_config.m_shiftThreshold) / valuePdf[0];
							}

						}
					} while (false);

					/* release offset emitter path for light path if needed */
					if (t == 1 && k>0 && pathSuccess[k] && !value[0].isZero())
						offsetEmitterSubpath.release(muRec.l, muRec.m + 1, m_pool);


					/* use T0 if base or offset is occluded with at least one strategy */
					if (value[k].isZero() || value[0].isZero()){
						value[k] = Spectrum(0.f);
						miWeight[k] = miWeight[0];
						valuePdf[k] = valuePdf[0];
					}
				}

				if (t == 1)
					connectedBasePath.release(memPointer, memPointer + 2, m_pool);


				if (value[0].isZero()) //if basepath is zero everything is zero!
					continue;

				/* store primal paths contribution */
				Spectrum mainRad = valuePdf[0] * miWeight[0] * value[0];
				if (t >= 2)
					primal += mainRad;
				else
					wr->putLightSample(samplePos, mainRad, 0);

				/* compute and store gradients */
				Spectrum fx = value[0] * valuePdf[0];
				for (int n = 0; n<neighbourCount; n++)
				{
					Spectrum fy = value[n + 1] * valuePdf[n + 1] * (t<2 ? jacobianLP[n] : pathData[n+1].jacobianDet[t]);
					Spectrum gradVal = Float(2.f)*miWeight[n + 1] * (fy - fx);
					if (t >= 2)
							gradient[n] += gradVal;
					else
							wr->putLightSample(samplePos, gradVal, n + 1);
				}
			}
		}

		/* store accumulated primal and gradient samples with t>=2 */
		wr->putSample(initialSamplePos, primal, 0);
		for (int k = 0; k < neighbourCount; ++k)
			wr->putSample(initialSamplePos , gradient[k], k + 1);
	}
示例#6
0
void GraphicsContext::addPath(const Path& path)
{
    m_data->currentPath = *(path.platformPath());
}
示例#7
0
int main(int argc, char** argv)
{
	if (argc != 4)
	{	
		Log.info() << "Need 3 arguments: <INIFile> <input.pdb> <output.hin>" << endl;
		Log.info() << "Note: exemplary rules can be found in BALL/data/solvation/PARSE.rul." << endl;
		return(1);
	}

	Path path;
	String filename = path.find(argv[1]);
	if (filename == "")
	{
		cerr << "Could not find rule file " << argv[1] << std::endl;
		return(1);
	}

	INIFile charge_rules(filename);
	charge_rules.read();
	RadiusRuleProcessor proc(charge_rules, "RadiusRules");

	PDBFile infile(argv[2]);
	if (!infile)
	{
		// if file does not exist: complain and abort
		Log.error() << "error opening " << argv[2] << " for input." << endl;
		return 2;
	}

	System system;
	infile >> system;
	infile.close();

	Log << "Initializing FragmentDB..." << endl;
	FragmentDB db("");
	Log << "  done." << endl;
	
	Log << "Normalizing names..." << endl;
	system.apply(db.normalize_names);
	Log << "  done." << endl;
	
	Log << "Building Bonds..." << endl;
	system.apply(db.build_bonds);
	Log << "  done." << endl;

	Log << "Applying RadiusRuleProcessor..." << endl;
	system.apply(proc);
	Log << "  done." << endl;

	Log << "Checking results..." << endl;
	// PARANOIA
	ResidueConstIterator res_it = system.beginResidue();

	for (; +res_it; ++res_it)
	{
		AtomConstIterator it = res_it->beginAtom();
		for (; +it; ++it)
		{
			float c = it->getCharge();
			if (fabs(c) > 4.0f)
			{
				Log.warn() << "WARNING: atom " << it->getFullName() << ":"
					<< res_it->getID() << " has suspect charge " << c << endl;
			}
		}
	}
	Log << "  done." << endl;

	HINFile outfile(argv[3], std::ios::out);
	outfile << system;
	outfile.close();	
	Log << "Outputfile " << argv[3] << " written." << endl;

}
示例#8
0
void JobScheduler::startJobs()
{
    static Path rp;
    if (rp.isEmpty()) {
        rp = Rct::executablePath().parentDir() + "rp";
        if (!rp.isFile()) {
            rp = Rct::executablePath();
            rp.resolve();
            rp = rp.parentDir() + "rp";
            if (!rp.isFile()) // should be in $PATH
                rp = "rp";
        }
    }

    const auto &options = Server::instance()->options();
    std::shared_ptr<Node> node = mPendingJobs.first();
    auto cont = [&node, this]() {
        auto tmp = node->next;
        mPendingJobs.remove(node);
        node = tmp;
    };

    while (mActiveByProcess.size() < options.jobCount && node) {
        assert(node);
        assert(node->job);
        assert(!(node->job->flags & (IndexerJob::Running|IndexerJob::Complete|IndexerJob::Crashed|IndexerJob::Aborted)));
        std::shared_ptr<Project> project = Server::instance()->project(node->job->project);
        if (!project) {
            cont();
            debug() << node->job->sourceFile << "doesn't have a project, discarding";
            continue;
        }

        uint32_t headerError = 0;
        if (!mHeaderErrors.isEmpty()) {
            headerError = hasHeaderError(node->job->source.fileId, project);
            if (headerError) {
                // error() << "We got a headerError" << Location::path(headerError) << "for" << node->job->source.sourceFile()
                //         << mHeaderErrorMaxJobs << mHeaderErrorJobIds;
                if (options.headerErrorJobCount <= mHeaderErrorJobIds.size()) {
                    warning() << "Holding off on" << node->job->sourceFile << "it's got a header error from" << Location::path(headerError);
                    node = node->next;
                    continue;
                }
            }
        }

        const uint64_t jobId = node->job->id;
        Process *process = new Process;
        debug() << "Starting process for" << jobId << node->job->source.key() << node->job.get();
        List<String> arguments;
        for (int i=logLevel().toInt(); i>0; --i)
            arguments << "-v";

        process->readyReadStdOut().connect([this](Process *proc) {
                std::shared_ptr<Node> node = mActiveByProcess[proc];
                assert(node);
                node->stdOut.append(proc->readAllStdOut());

                std::regex rx("@CRASH@([^@]*)@CRASH@");
                std::smatch match;
                while (std::regex_search(node->stdOut.ref(), match, rx)) {
                    error() << match[1].str();
                    node->stdOut.remove(match.position(), match.length());
                }
            });

        if (!process->start(rp, arguments)) {
            error() << "Couldn't start rp" << rp << process->errorString();
            delete process;
            node->job->flags |= IndexerJob::Crashed;
            debug() << "job crashed (didn't start)" << jobId << node->job->source.key() << node->job.get();
            std::shared_ptr<IndexDataMessage> msg(new IndexDataMessage(node->job));
            msg->setFlag(IndexDataMessage::ParseFailure);
            jobFinished(node->job, msg);
            rp.clear(); // in case rp was missing for a moment and we fell back to searching $PATH
            cont();
            continue;
        }
        if (headerError) {
            node->job->priority = IndexerJob::HeaderError;
            warning() << "Letting" << node->job->sourceFile << "go even with a headerheader error from" << Location::path(headerError);
            mHeaderErrorJobIds.insert(jobId);
        }
        process->finished().connect([this, jobId](Process *proc) {
                EventLoop::deleteLater(proc);
                auto node = mActiveByProcess.take(proc);
                assert(!node || node->process == proc);
                const String stdErr = proc->readAllStdErr();
                if ((node && !node->stdOut.isEmpty()) || !stdErr.isEmpty()) {
                    error() << (node ? ("Output from " + node->job->sourceFile + ":") : String("Orphaned process:"))
                            << '\n' << stdErr << (node ? node->stdOut : String());
                }

                if (node) {
                    assert(node->process == proc);
                    node->process = 0;
                    assert(!(node->job->flags & IndexerJob::Aborted));
                    if (!(node->job->flags & IndexerJob::Complete) && proc->returnCode() != 0) {
                        auto nodeById = mActiveById.take(jobId);
                        assert(nodeById);
                        assert(nodeById == node);
                        // job failed, probably no IndexDataMessage coming
                        node->job->flags |= IndexerJob::Crashed;
                        debug() << "job crashed" << jobId << node->job->source.key() << node->job.get();
                        std::shared_ptr<IndexDataMessage> msg(new IndexDataMessage(node->job));
                        msg->setFlag(IndexDataMessage::ParseFailure);
                        jobFinished(node->job, msg);
                    }
                }
                mHeaderErrorJobIds.remove(jobId);
                startJobs();
            });


        node->process = process;
        assert(!(node->job->flags & ~IndexerJob::Type_Mask));
        node->job->flags |= IndexerJob::Running;
        process->write(node->job->encode());
        mActiveByProcess[process] = node;
        // error() << "STARTING JOB" << node->job->source.sourceFile();
        mInactiveById.remove(jobId);
        mActiveById[jobId] = node;
        cont();
    }
}
示例#9
0
 virtual bool apply( const Path &p ) {
     if ( !boost::filesystem::exists( p ) )
         return false;
     boostRenameWrapper( p, newPath_ / p.leaf() );
     return true;
 }
void PlatformGraphicsContextSkia::clip(const Path& path)
{
    mCanvas->clipPath(*path.platformPath(), SkRegion::kIntersect_Op, true);
}
void PlatformGraphicsContextSkia::clipOut(const Path& path)
{
    mCanvas->clipPath(*path.platformPath(), SkRegion::kDifference_Op);
}
示例#12
0
Process::ExecState Process::startInternal(const Path &command, const List<String> &a, const List<String> &environment,
                                          int timeout, unsigned int execFlags)
{
    mErrorString.clear();

    const char *path = 0;
    for (const auto &it : environment) {
        if (it.startsWith("PATH=")) {
            path = it.constData() + 5;
            break;
        }
    }
    Path cmd = findCommand(command, path);
    if (cmd.isEmpty()) {
        mErrorString = "Command not found";
        return Error;
    }
    List<String> arguments = a;
    int err;

    int closePipe[2];
    eintrwrap(err, ::pipe(closePipe));
#ifdef HAVE_CLOEXEC
    if (!SocketClient::setFlags(closePipe[1], FD_CLOEXEC, F_GETFD, F_SETFD)) {
        mErrorString = "Unable to set FD_CLOEXEC";
        eintrwrap(err, ::close(closePipe[0]));
        eintrwrap(err, ::close(closePipe[1]));
        return Error;
    }
#else
#warning No CLOEXEC, Process might have problematic behavior
#endif

    eintrwrap(err, ::pipe(mStdIn));
    eintrwrap(err, ::pipe(mStdOut));
    eintrwrap(err, ::pipe(mStdErr));
    if (mMode == Sync)
        eintrwrap(err, ::pipe(mSync));

    const char **args = new const char*[arguments.size() + 2];
    // const char* args[arguments.size() + 2];
    args[arguments.size() + 1] = 0;
    args[0] = cmd.nullTerminated();
    int pos = 1;
    for (List<String>::const_iterator it = arguments.begin(); it != arguments.end(); ++it) {
        args[pos] = it->nullTerminated();
        // printf("arg: '%s'\n", args[pos]);
        ++pos;
    }

    const bool hasEnviron = !environment.empty();

    const char **env = new const char*[environment.size() + 1];
    env[environment.size()] = 0;

    if (hasEnviron) {
        pos = 0;
        //printf("fork, about to exec '%s'\n", cmd.nullTerminated());
        for (List<String>::const_iterator it = environment.begin(); it != environment.end(); ++it) {
            env[pos] = it->nullTerminated();
            //printf("env: '%s'\n", env[pos]);
            ++pos;
        }
    }

    ProcessThread::setPending(1);

    mPid = ::fork();
    if (mPid == -1) {
        //printf("fork, something horrible has happened %d\n", errno);
        // bail out

        ProcessThread::setPending(-1);

        eintrwrap(err, ::close(mStdIn[1]));
        eintrwrap(err, ::close(mStdIn[0]));
        eintrwrap(err, ::close(mStdOut[1]));
        eintrwrap(err, ::close(mStdOut[0]));
        eintrwrap(err, ::close(mStdErr[1]));
        eintrwrap(err, ::close(mStdErr[0]));
        eintrwrap(err, ::close(closePipe[1]));
        eintrwrap(err, ::close(closePipe[0]));
        mErrorString = "Fork failed";
        delete[] env;
        delete[] args;
        return Error;
    } else if (mPid == 0) {
        //printf("fork, in child\n");
        // child, should do some error checking here really
        eintrwrap(err, ::close(closePipe[0]));
        eintrwrap(err, ::close(mStdIn[1]));
        eintrwrap(err, ::close(mStdOut[0]));
        eintrwrap(err, ::close(mStdErr[0]));

        eintrwrap(err, ::close(STDIN_FILENO));
        eintrwrap(err, ::close(STDOUT_FILENO));
        eintrwrap(err, ::close(STDERR_FILENO));

        eintrwrap(err, ::dup2(mStdIn[0], STDIN_FILENO));
        eintrwrap(err, ::close(mStdIn[0]));
        eintrwrap(err, ::dup2(mStdOut[1], STDOUT_FILENO));
        eintrwrap(err, ::close(mStdOut[1]));
        eintrwrap(err, ::dup2(mStdErr[1], STDERR_FILENO));
        eintrwrap(err, ::close(mStdErr[1]));

        int ret;
        if (!mChRoot.isEmpty() && ::chroot(mChRoot.constData())) {
            goto error;
        }
        if (!mCwd.isEmpty() && ::chdir(mCwd.constData())) {
            goto error;
        }
        if (hasEnviron) {
            ret = ::execve(cmd.nullTerminated(), const_cast<char* const*>(args), const_cast<char* const*>(env));
        } else {
            ret = ::execv(cmd.nullTerminated(), const_cast<char* const*>(args));
        }
        // notify the parent process
  error:
        const char c = 'c';
        eintrwrap(err, ::write(closePipe[1], &c, 1));
        eintrwrap(err, ::close(closePipe[1]));
        ::_exit(1);
        (void)ret;
        //printf("fork, exec seemingly failed %d, %d %s\n", ret, errno, Rct::strerror().constData());
    } else {
        delete[] env;
        delete[] args;

        // parent
        eintrwrap(err, ::close(closePipe[1]));
        eintrwrap(err, ::close(mStdIn[0]));
        eintrwrap(err, ::close(mStdOut[1]));
        eintrwrap(err, ::close(mStdErr[1]));

        //printf("fork, in parent\n");

        int flags;
        eintrwrap(flags, fcntl(mStdIn[1], F_GETFL, 0));
        eintrwrap(flags, fcntl(mStdIn[1], F_SETFL, flags | O_NONBLOCK));
        eintrwrap(flags, fcntl(mStdOut[0], F_GETFL, 0));
        eintrwrap(flags, fcntl(mStdOut[0], F_SETFL, flags | O_NONBLOCK));
        eintrwrap(flags, fcntl(mStdErr[0], F_GETFL, 0));
        eintrwrap(flags, fcntl(mStdErr[0], F_SETFL, flags | O_NONBLOCK));

        // block until exec is called in the child or until exec fails
        {
            char c;
            eintrwrap(err, ::read(closePipe[0], &c, 1));
            (void)c;

            if (err == -1) {
                // bad
                eintrwrap(err, ::close(closePipe[0]));
                mErrorString = "Failed to read from closePipe during process start";
                mPid = -1;
                ProcessThread::setPending(-1);
                mReturn = ReturnCrashed;
                return Error;
            } else if (err == 0) {
                // process has started successfully
                eintrwrap(err, ::close(closePipe[0]));
            } else if (err == 1) {
                // process start failed
                eintrwrap(err, ::close(closePipe[0]));
                mErrorString = "Process failed to start";
                mReturn = ReturnCrashed;
                mPid = -1;
                ProcessThread::setPending(-1);
                return Error;
            }
        }

        ProcessThread::addPid(mPid, this, (mMode == Async));

        //printf("fork, about to add fds: stdin=%d, stdout=%d, stderr=%d\n", mStdIn[1], mStdOut[0], mStdErr[0]);
        if (mMode == Async) {
            if (EventLoop::SharedPtr loop = EventLoop::eventLoop()) {
                loop->registerSocket(mStdOut[0], EventLoop::SocketRead, std::bind(&Process::processCallback, this, std::placeholders::_1, std::placeholders::_2));
                loop->registerSocket(mStdErr[0], EventLoop::SocketRead, std::bind(&Process::processCallback, this, std::placeholders::_1, std::placeholders::_2));
            }
        } else {
            // select and stuff
            timeval started, now, timeoutForSelect;
            if (timeout > 0) {
                Rct::gettime(&started);
                timeoutForSelect.tv_sec = timeout / 1000;
                timeoutForSelect.tv_usec = (timeout % 1000) * 1000;
            }
            if (!(execFlags & NoCloseStdIn)) {
                closeStdIn(CloseForce);
                mWantStdInClosed = false;
            }
            for (;;) {
                // set up all the select crap
                fd_set rfds, wfds;
                FD_ZERO(&rfds);
                FD_ZERO(&wfds);
                int max = 0;
                FD_SET(mStdOut[0], &rfds);
                max = std::max(max, mStdOut[0]);
                FD_SET(mStdErr[0], &rfds);
                max = std::max(max, mStdErr[0]);
                FD_SET(mSync[0], &rfds);
                max = std::max(max, mSync[0]);
                if (mStdIn[1] != -1) {
                    FD_SET(mStdIn[1], &wfds);
                    max = std::max(max, mStdIn[1]);
                }
                int ret;
                eintrwrap(ret, ::select(max + 1, &rfds, &wfds, 0, timeout > 0 ? &timeoutForSelect : 0));
                if (ret == -1) { // ow
                    mErrorString = "Sync select failed: ";
                    mErrorString += Rct::strerror();
                    return Error;
                }
                // check fds and stuff
                if (FD_ISSET(mStdOut[0], &rfds))
                    handleOutput(mStdOut[0], mStdOutBuffer, mStdOutIndex, mReadyReadStdOut);
                if (FD_ISSET(mStdErr[0], &rfds))
                    handleOutput(mStdErr[0], mStdErrBuffer, mStdErrIndex, mReadyReadStdErr);
                if (mStdIn[1] != -1 && FD_ISSET(mStdIn[1], &wfds))
                    handleInput(mStdIn[1]);
                if (FD_ISSET(mSync[0], &rfds)) {
                    // we're done
                    {
                        std::lock_guard<std::mutex> lock(mMutex);
                        assert(mSync[1] == -1);

                        // try to read all remaining data on stdout and stderr
                        handleOutput(mStdOut[0], mStdOutBuffer, mStdOutIndex, mReadyReadStdOut);
                        handleOutput(mStdErr[0], mStdErrBuffer, mStdErrIndex, mReadyReadStdErr);

                        closeStdOut();
                        closeStdErr();

                        int w;
                        eintrwrap(w, ::close(mSync[0]));
                        mSync[0] = -1;
                    }
                    mFinished(this);
                    return Done;
                }
                if (timeout) {
                    Rct::gettime(&now);

                    // lasted is the amount of time we spent until now in ms
                    const int lasted = Rct::timevalDiff(&now, &started);
                    if (lasted >= timeout) {
                        // timeout, we're done
                        kill(); // attempt to kill

                        // we need to remove this Process object from
                        // ProcessThread, because ProcessThread will try to
                        // finish() this object. However, this object may
                        // already have been deleted *before* ProcessThread
                        // runs, creating a segfault.
                        ProcessThread::removePid(mPid);

                        mErrorString = "Timed out";
                        return TimedOut;
                    }

                    // (timeout - lasted) is guaranteed to be > 0 because of
                    // the check above.
                    timeoutForSelect.tv_sec = (timeout - lasted) / 1000;
                    timeoutForSelect.tv_usec = ((timeout - lasted) % 1000) * 1000;
                }
            }
        }
    }
    return Done;
}
示例#13
0
QVector<Path> Switchers::viewsToSwitch()
{
    QVector<Path> urls;

    auto doc = ICore::self()->documentController()->activeDocument();
    if (!doc) {
        return urls;
    }

    const QUrl &url = doc->url();
    QFileInfo file(url.toLocalFile());
    if (!file.exists()) {
        return urls;
    }

    const QString &ext = file.completeSuffix();
    QString name = file.baseName();
    QString switchTo = "";

    if (isViewExtension(ext)) {
        switchTo = file.dir().dirName();
    } else if (ext == "rb") {
        switchTo = name.remove(QRegExp("_controller$"));
        switchTo = switchTo.remove(QRegExp("_controller_test$"));
        switchTo = switchTo.remove(QRegExp("_test$"));
    }

    if (switchTo.isEmpty()) {
        return urls;
    }
    if (switchTo.endsWith("s")) {
        switchTo = switchTo.mid(0, switchTo.length() - 1);
    }

    Path root = Helpers::findRailsRoot(url);
    if (!root.isValid()) {
        return urls;
    }

    Path viewsUrl(root, QStringLiteral("app/views"));
    Path viewsUrlS(viewsUrl, switchTo);
    Path viewsUrlP(viewsUrl, switchTo + "s");

    if (QFile::exists(viewsUrlS.toLocalFile())) {
        viewsUrl = viewsUrlS;
    } else if (QFile::exists(viewsUrlP.toLocalFile())) {
        viewsUrl = viewsUrlP;
    } else {
        return urls;
    }

    QDir viewsDir(viewsUrl.toLocalFile());
    const QStringList &views = viewsDir.entryList();
    const Path base(viewsDir.absolutePath());

    foreach (const QString &name, views) {
        if (!(name.endsWith("~") || name == "." || name == "..")) {
            urls << KDevelop::Path(base, name);
        }
    }
    return urls;
}
示例#14
0
int BuddhabrotSketch::GetGroup(double th, Complex *pts, GLcolor *cols, int n)
{
	ColorSet colorset;
	colorset.fromHues(BASIC_HUE_SET, 10, 0.9, 1.0);
	colorset.offsetHues(270);	// ?

	// shorthand path
	Path *pPath = ((Path*)(m_pPath.get()));

	ASSERT(n>=GetGroupSize());
	int count = 0;
	Complex c, z;
	for(int j=0; j<pPath->getGroupSize(); ++j)
	{
		c = pPath->get(th, j);
		z = c;

		int i;
		for(i=0; i<m_nMaxIter; ++i)
		{
			z = (z*z + c);
			if(normal(z) > 4.0)
				break;
		}

		// slight alteration here:
		// we're not going to plot short orbits, only
		// interesting ones whose length is at least MinIter.
		if(i < m_nMaxIter && i >= m_nMinIter)
		{
			// plot this point's orbit, until it hits the bailout value

			int nStopIter = i;

			z = c;
			for(i=0; i<=nStopIter; ++i)		// was i<=m_nMaxIter
			{
				z = (z*z) + c;
				pts[count] = z;
				// color according to...
				switch(m_nColorScheme)
				{
				case 0:
					// abs(c)?
					cols[count].SetHSV(360*log(abs(c)), 0.9, 0.9, m_fBrightness);
					break;
				case 1:
					// iter? (busy)
//					cols[count].SetHSV((i-m_nMinIter)*360.0/(m_nMaxIter-m_nMinIter+1), 0.9, 0.9, m_fBrightness);
					cols[count].SetHSV((i*360.0/m_nMaxIter), 0.9, 0.9, m_fBrightness);
					break;
				case 2:
					// c.arg?
					cols[count].SetHSV(arg(c)*360.0/6.283, 0.9, 0.9, m_fBrightness);
					break;
				case 3:
					// ring index? (this makes bright figures with little or no blur)
					cols[count].SetHSV(j*360.0/pPath->getGroupSize(), 0.9, 0.9, m_fBrightness);
					break;
				case 4:
					// stopiter?
					cols[count].SetHSV((nStopIter-m_nMinIter)*360.0/(m_nMaxIter-m_nMinIter+1), 0.9, 0.9, m_fBrightness);
				}

				++count;
			}
		}
	}

	ASSERT(count <= n);
	return count;
}
示例#15
0
std::string View_types::get_mime(const Path& p) const
{
	std::lock_guard<std::mutex> lk {m_mtx};
	const char* m = magic_file(m_magic_guard->magic_cookie, p.c_str());
	return m ? m : std::string {};
}
示例#16
0
    Status MMAPV1Engine::repairDatabase( OperationContext* txn,
                                         const std::string& dbName,
                                         bool preserveClonedFilesOnFailure,
                                         bool backupOriginalFiles ) {
        // We must hold some form of lock here
        invariant(txn->lockState()->threadState());
        invariant( dbName.find( '.' ) == string::npos );

        scoped_ptr<RepairFileDeleter> repairFileDeleter;
        doingRepair dr;

        log() << "repairDatabase " << dbName << endl;

        BackgroundOperation::assertNoBgOpInProgForDb(dbName);

        txn->recoveryUnit()->syncDataAndTruncateJournal(); // Must be done before and after repair

        intmax_t totalSize = dbSize( dbName );
        intmax_t freeSize = File::freeSpace(storageGlobalParams.repairpath);

        if ( freeSize > -1 && freeSize < totalSize ) {
            return Status( ErrorCodes::OutOfDiskSpace,
                           str::stream() << "Cannot repair database " << dbName
                           << " having size: " << totalSize
                           << " (bytes) because free disk space is: " << freeSize << " (bytes)" );
        }

        txn->checkForInterrupt();

        Path reservedPath =
            uniqueReservedPath( ( preserveClonedFilesOnFailure || backupOriginalFiles ) ?
                                "backup" : "_tmp" );
        MONGO_ASSERT_ON_EXCEPTION( boost::filesystem::create_directory( reservedPath ) );
        string reservedPathString = reservedPath.string();

        if ( !preserveClonedFilesOnFailure )
            repairFileDeleter.reset( new RepairFileDeleter( txn,
                                                            dbName,
                                                            reservedPathString,
                                                            reservedPath ) );

        {
            Database* originalDatabase =
                            dbHolder().get(txn, dbName);
            if (originalDatabase == NULL) {
                return Status(ErrorCodes::NamespaceNotFound, "database does not exist to repair");
            }

            scoped_ptr<MMAPV1DatabaseCatalogEntry> dbEntry;
            scoped_ptr<Database> tempDatabase;
            {
                dbEntry.reset( new MMAPV1DatabaseCatalogEntry( txn,
                                                               dbName,
                                                               reservedPathString,
                                                               storageGlobalParams.directoryperdb,
                                                               true ) );
                invariant( !dbEntry->exists() );
                tempDatabase.reset( new Database( txn,
                                                  dbName,
                                                  dbEntry.get() ) );

            }

            map<string,CollectionOptions> namespacesToCopy;
            {
                string ns = dbName + ".system.namespaces";
                Client::Context ctx(txn,  ns );
                Collection* coll = originalDatabase->getCollection( txn, ns );
                if ( coll ) {
                    scoped_ptr<RecordIterator> it( coll->getIterator( txn,
                                                                      DiskLoc(),
                                                                      false,
                                                                      CollectionScanParams::FORWARD ) );
                    while ( !it->isEOF() ) {
                        DiskLoc loc = it->getNext();
                        BSONObj obj = coll->docFor( loc );

                        string ns = obj["name"].String();

                        NamespaceString nss( ns );
                        if ( nss.isSystem() ) {
                            if ( nss.isSystemDotIndexes() )
                                continue;
                            if ( nss.coll() == "system.namespaces" )
                                continue;
                        }

                        if ( !nss.isNormal() )
                            continue;

                        CollectionOptions options;
                        if ( obj["options"].isABSONObj() ) {
                            Status status = options.parse( obj["options"].Obj() );
                            if ( !status.isOK() )
                                return status;
                        }
                        namespacesToCopy[ns] = options;
                    }
                }
            }

            for ( map<string,CollectionOptions>::const_iterator i = namespacesToCopy.begin();
                  i != namespacesToCopy.end();
                  ++i ) {
                string ns = i->first;
                CollectionOptions options = i->second;

                Collection* tempCollection = NULL;
                {
                    Client::Context tempContext(txn, ns, tempDatabase );
                    tempCollection = tempDatabase->createCollection( txn, ns, options, true, false );
                }

                Client::Context readContext(txn, ns, originalDatabase);
                Collection* originalCollection = originalDatabase->getCollection( txn, ns );
                invariant( originalCollection );

                // data

                MultiIndexBlock indexBlock(txn, tempCollection );
                {
                    vector<BSONObj> indexes;
                    IndexCatalog::IndexIterator ii =
                        originalCollection->getIndexCatalog()->getIndexIterator( false );
                    while ( ii.more() ) {
                        IndexDescriptor* desc = ii.next();
                        indexes.push_back( desc->infoObj() );
                    }

                    Client::Context tempContext(txn, ns, tempDatabase);
                    Status status = indexBlock.init( indexes );
                    if ( !status.isOK() )
                        return status;

                }

                scoped_ptr<RecordIterator> iterator(
                    originalCollection->getIterator( txn, DiskLoc(), false,
                                                     CollectionScanParams::FORWARD ));
                while ( !iterator->isEOF() ) {
                    DiskLoc loc = iterator->getNext();
                    invariant( !loc.isNull() );

                    BSONObj doc = originalCollection->docFor( loc );

                    Client::Context tempContext(txn, ns, tempDatabase);
                    StatusWith<DiskLoc> result = tempCollection->insertDocument( txn, doc, indexBlock );
                    if ( !result.isOK() )
                        return result.getStatus();

                    txn->recoveryUnit()->commitIfNeeded();
                    txn->checkForInterrupt(false);
                }

                {
                    Client::Context tempContext(txn, ns, tempDatabase);
                    Status status = indexBlock.commit();
                    if ( !status.isOK() )
                        return status;
                }

            }

            txn->recoveryUnit()->syncDataAndTruncateJournal();
            globalStorageEngine->flushAllFiles(true); // need both in case journaling is disabled

            txn->checkForInterrupt(false);
        }

        // at this point if we abort, we don't want to delete new files
        // as they might be the only copies

        if ( repairFileDeleter.get() )
            repairFileDeleter->success();

        dbHolder().close( txn, dbName );

        if ( backupOriginalFiles ) {
            _renameForBackup( dbName, reservedPath );
        }
        else {
            // first make new directory before deleting data
            Path newDir = Path(storageGlobalParams.dbpath) / dbName;
            MONGO_ASSERT_ON_EXCEPTION(boost::filesystem::create_directory(newDir));

            // this deletes old files
            _deleteDataFiles( dbName );

            if ( !boost::filesystem::exists(newDir) ) {
                // we deleted because of directoryperdb
                // re-create
                MONGO_ASSERT_ON_EXCEPTION(boost::filesystem::create_directory(newDir));
            }
        }

        _replaceWithRecovered( dbName, reservedPathString.c_str() );

        if ( !backupOriginalFiles )
            MONGO_ASSERT_ON_EXCEPTION( boost::filesystem::remove_all( reservedPath ) );

        return Status::OK();
    }
示例#17
0
 void PushPath(vector<Point> & OutPath){
     if (LastPath != NULL)
         LastPath->PushPath(OutPath);
     OutPath.push_back(P);
 }
示例#18
0
int main_mod(int argc, char** argv) {

    if (argc == 2) {
        help_mod(argv);
        return 1;
    }

    string path_name;
    bool remove_orphans = false;
    string aln_file;
    string loci_file;
    bool called_genotypes_only = false;
    bool label_paths = false;
    bool compact_ids = false;
    bool prune_complex = false;
    int path_length = 0;
    int edge_max = 0;
    int chop_to = 0;
    bool add_start_and_end_markers = false;
    bool prune_subgraphs = false;
    bool kill_labels = false;
    bool simplify_graph = false;
    bool unchop = false;
    bool normalize_graph = false;
    bool sort_graph = false;
    bool remove_non_path = false;
    bool remove_path = false;
    bool compact_ranks = false;
    bool drop_paths = false;
    bool force_path_match = false;
    set<string> paths_to_retain;
    bool retain_complement = false;
    vector<int64_t> root_nodes;
    int32_t context_steps;
    bool remove_null;
    bool strong_connect = false;
    uint32_t unfold_to = 0;
    bool break_cycles = false;
    uint32_t dagify_steps = 0;
    uint32_t dagify_to = 0;
    uint32_t dagify_component_length_max = 0;
    bool orient_forward = false;
    int64_t destroy_node_id = 0;
    bool bluntify = false;
    int until_normal_iter = 0;
    string translation_file;
    bool flip_doubly_reversed_edges = false;
    bool cactus = false;
    string vcf_filename;
    string loci_filename;

    int c;
    optind = 2; // force optind past command positional argument
    while (true) {
        static struct option long_options[] =

        {
            {"help", no_argument, 0, 'h'},
            {"include-aln", required_argument, 0, 'i'},
            {"include-loci", required_argument, 0, 'q'},
            {"include-gt", required_argument, 0, 'Q'},
            {"compact-ids", no_argument, 0, 'c'},
            {"compact-ranks", no_argument, 0, 'C'},
            {"drop-paths", no_argument, 0, 'D'},
            {"keep-path", required_argument, 0, 'k'},
            {"remove-orphans", no_argument, 0, 'o'},
            {"prune-complex", no_argument, 0, 'p'},
            {"prune-subgraphs", no_argument, 0, 'S'},
            {"length", required_argument, 0, 'l'},
            {"edge-max", required_argument, 0, 'e'},
            {"chop", required_argument, 0, 'X'},
            {"kill-labels", no_argument, 0, 'K'},
            {"markers", no_argument, 0, 'm'},
            {"threads", no_argument, 0, 't'},
            {"label-paths", no_argument, 0, 'P'},
            {"simplify", no_argument, 0, 's'},
            {"unchop", no_argument, 0, 'u'},
            {"normalize", no_argument, 0, 'n'},
            {"until-normal", required_argument, 0, 'U'},
            {"sort", no_argument, 0, 'z'},
            {"remove-non-path", no_argument, 0, 'N'},
            {"remove-path", no_argument, 0, 'A'},
            {"orient-forward", no_argument, 0, 'O'},
            {"unfold", required_argument, 0, 'f'},
            {"force-path-match", no_argument, 0, 'F'},
            {"retain-path", required_argument, 0, 'r'},
            {"subgraph", required_argument, 0, 'g'},
            {"context", required_argument, 0, 'x'},
            {"remove-null", no_argument, 0, 'R'},
            {"strong-connect", no_argument, 0, 'T'},
            {"dagify-steps", required_argument, 0, 'd'},
            {"dagify-to", required_argument, 0, 'w'},
            {"dagify-len-max", required_argument, 0, 'L'},
            {"bluntify", no_argument, 0, 'B'},
            {"break-cycles", no_argument, 0, 'b'},
            {"orient-forward", no_argument, 0, 'O'},
            {"destroy-node", required_argument, 0, 'y'},
            {"translation", required_argument, 0, 'Z'},
            {"unreverse-edges", required_argument, 0, 'E'},
            {"cactus", no_argument, 0, 'a'},
            {"sample-vcf", required_argument, 0, 'v'},
            {"sample-graph", required_argument, 0, 'G'},
            {0, 0, 0, 0}
        };

        int option_index = 0;
        c = getopt_long (argc, argv, "hk:oi:q:Q:cpl:e:mt:SX:KPsunzNAf:CDFr:Ig:x:RTU:Bbd:Ow:L:y:Z:Eav:G:",
                long_options, &option_index);


        // Detect the end of the options.
        if (c == -1)
            break;

        switch (c)
        {

        case 'i':
            aln_file = optarg;
            break;

        case 'q':
            loci_file = optarg;
            break;

        case 'Q':
            loci_file = optarg;
            called_genotypes_only = true;
            break;

        case 'Z':
            translation_file = optarg;
            break;

        case 'c':
            compact_ids = true;
            break;

        case 'C':
            compact_ranks = true;
            break;

        case 'k':
            path_name = optarg;
            break;

        case 'r':
            paths_to_retain.insert(optarg);
            break;
            
        case 'I':
            retain_complement = true;
            break;

        case 'o':
            remove_orphans = true;
            break;

        case 'p':
            prune_complex = true;
            break;

        case 'S':
            prune_subgraphs = true;
            break;

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

        case 'X':
            chop_to = atoi(optarg);
            break;

        case 'u':
            unchop = true;
            break;

        case 'E':
            flip_doubly_reversed_edges = true;
            break;

        case 'K':
            kill_labels = true;
            break;

        case 'e':
            edge_max = atoi(optarg);
            break;

        case 'm':
            add_start_and_end_markers = true;
            break;

        case 't':
            omp_set_num_threads(atoi(optarg));
            break;

        case 'f':
            unfold_to = atoi(optarg);
            break;

        case 'O':
            orient_forward = true;
            break;

        case 'F':
            force_path_match = true;
            break;

        case 'P':
            label_paths = true;
            break;

        case 'D':
            drop_paths = true;
            break;

        case 's':
            simplify_graph = true;
            break;

        case 'n':
            normalize_graph = true;
            break;

        case 'N':
            remove_non_path = true;
            break;
            
        case 'A':
            remove_path = true;
            break;

        case 'T':
            strong_connect = true;
            break;

        case 'U':
            until_normal_iter = atoi(optarg);
            break;

        case 'd':
            dagify_steps = atoi(optarg);
            break;

        case 'w':
            dagify_to = atoi(optarg);
            break;

        case 'L':
            dagify_component_length_max = atoi(optarg);
            break;

        case 'B':
            bluntify = true;
            break;

        case 'z':
            sort_graph = true;
            break;

        case 'b':
            break_cycles = true;
            break;

        case 'g':
            root_nodes.push_back(atoi(optarg));
            break;

        case 'x':
            context_steps = atoi(optarg);
            break;

        case 'R':
            remove_null = true;
            break;

        case 'y':
            destroy_node_id = atoi(optarg);
            break;

        case 'a':
            cactus = true;
            break;

        case 'v':
            vcf_filename = optarg;
            break;
            
        case 'G':
            loci_filename = optarg;
            break;

        case 'h':
        case '?':
            help_mod(argv);
            exit(1);
            break;

        default:
            abort ();
        }
    }

    VG* graph;
    get_input_file(optind, argc, argv, [&](istream& in) {
        graph = new VG(in);
    });
    
    if (retain_complement) {
        // Compute the actual paths to retain
        set<string> complement;
        graph->paths.for_each_name([&](const string& name) {
            if (!paths_to_retain.count(name)) {
                // Complement the set the user specified by putting in all the
                // paths they didn't mention.
                complement.insert(name);
            }
        });
        
        // Retain the complement of what we were asking for.
        paths_to_retain = complement;
    }

    if (!vcf_filename.empty()) {
        // We need to throw out the parts of the graph that are on alt paths,
        // but not on alt paths for alts used by the first sample in the VCF.

        // This is matched against the entire path name string to detect alt
        // paths.
        regex is_alt("_alt_.+_[0-9]+");

        // This holds the VCF file we read the variants from. It needs to be the
        // same one used to construct the graph.
        vcflib::VariantCallFile variant_file;
        variant_file.open(vcf_filename);
        if (!variant_file.is_open()) {
            cerr << "error:[vg mod] could not open" << vcf_filename << endl;
            return 1;
        }

        // Now go through and prune down the varaints.

        // How many phases are there?
        size_t num_samples = variant_file.sampleNames.size();
        // TODO: we can only handle single-sample VCFs
        assert(num_samples == 1);

        // This will hold the IDs of all nodes visited by alt paths that aren't used.
        set<vg::id_t> alt_path_ids;

        graph->paths.for_each_name([&](const string& alt_path_name) {
            // For every path name in the graph

            if(regex_match(alt_path_name, is_alt)) {
                // If it's an alt path

                for(auto& mapping : graph->paths.get_path(alt_path_name)) {
                    // Mark all nodes that are part of it as on alt paths
                    alt_path_ids.insert(mapping.position().node_id());
                }

            }
        });

        // We also have a function to handle each variant as it comes in.
        auto handle_variant = [&](vcflib::Variant& variant) {
            // So we have a variant

            if(variant.alleles.size() < 2) {
                // Skip non-variable variants.
                return;
            }

            // Grab its id, or make one by hashing stuff if it doesn't
            // have an ID.
            string var_name = make_variant_id(variant);

            if(!graph->paths.has_path("_alt_" + var_name + "_0")) {
                // There isn't a reference alt path for this variant. Someone messed up.
                cerr << variant << endl;
                throw runtime_error("Reference alt for " + var_name + " not in graph!");
            }

            // For now always work on sample 0. TODO: let the user specify a
            // name and find it.
            int sample_number = 0;

            // What sample is it?
            string& sample_name = variant_file.sampleNames[sample_number];

            // Parse it out and see if it's phased.
            string genotype = variant.getGenotype(sample_name);

            // Tokenize into allele numbers
            // The token iterator can't hold the regex
            regex allele_separator("[|/]");
            for (sregex_token_iterator it(genotype.begin(), genotype.end(), allele_separator, -1);
                it != sregex_token_iterator(); ++it) {
                // For every token separated by / or |
                int allele_number;
                if(it->str() == ".") {
                    // Unknown; pretend it's ref for the purposes of making a
                    // sample graph.
                    allele_number = 0;
                } else {
                    // Parse the allele number
                    allele_number = stoi(it->str());
                }



                // Make the name for its alt path
                string alt_path_name = "_alt_" + var_name + "_" + to_string(allele_number);

                for(auto& mapping : graph->paths.get_path(alt_path_name)) {
                    // Un-mark all nodes that are on this alt path, since it is used by the sample.
                    alt_path_ids.erase(mapping.position().node_id());
                }
            }

        };


        // Allocate a place to store actual variants
        vcflib::Variant var(variant_file);

        while (variant_file.is_open() && variant_file.getNextVariant(var)) {
            // this ... maybe we should remove it as for when we have calls against N
            bool isDNA = allATGC(var.ref);
            for (vector<string>::iterator a = var.alt.begin(); a != var.alt.end(); ++a) {
                if (!allATGC(*a)) isDNA = false;
            }
            // only work with DNA sequences
            if (!isDNA) {
                continue;
            }

            var.position -= 1; // convert to 0-based

            // Handle the variant
            handle_variant(var);
        }


        for(auto& node_id : alt_path_ids) {
            // And delete all the nodes that were used by alt paths that weren't
            // in the genotype of the first sample.

            for(auto& path_name : graph->paths.of_node(node_id)) {
                // For every path that touches the node we're destroying,
                // destroy the path. We can't leave it because it won't be the
                // same path without this node.
                graph->paths.remove_path(path_name);
#ifdef debug
                cerr << "Node " << node_id << " was on path " << path_name << endl;
#endif
            }

            // Actually get rid of the node once its paths are gone.
            graph->destroy_node(node_id);
        }

    }
    
    if (!loci_filename.empty()) {
        // Open the file
        ifstream loci_file(loci_filename);
        assert(loci_file.is_open());
    
        // What nodes and edges are called as present by the loci?
        set<Node*> called_nodes;
        set<Edge*> called_edges;
    
        function<void(Locus&)> lambda = [&](Locus& locus) {
            // For each locus
            
            if (locus.genotype_size() == 0) {
                // No call made here. Just remove all the nodes/edges. TODO:
                // should we keep them all if we don't know if they're there or
                // not? Or should the caller call ref with some low confidence?
                return;
            }
            
            const Genotype& gt = locus.genotype(0);
            
            for (size_t j = 0; j < gt.allele_size(); j++) {
                // For every allele called as present
                int allele_number = gt.allele(j);
                const Path& allele = locus.allele(allele_number);
                
                for (size_t i = 0; i < allele.mapping_size(); i++) {
                    // For every Mapping in the allele
                    const Mapping& m = allele.mapping(i);
                    
                    // Remember to keep this node
                    called_nodes.insert(graph->get_node(m.position().node_id()));
                    
                    if (i + 1 < allele.mapping_size()) {
                        // Look at the next mapping, which exists
                        const Mapping& m2 = allele.mapping(i + 1);
                        
                        // Find the edge from the last Mapping's node to this one and mark it as used
                        called_edges.insert(graph->get_edge(NodeSide(m.position().node_id(), !m.position().is_reverse()),
                            NodeSide(m2.position().node_id(), m2.position().is_reverse())));
                    }
                }
            }
        };
        stream::for_each(loci_file, lambda);
        
        // Collect all the unused nodes and edges (so we don't try to delete
        // while iterating...)
        set<Node*> unused_nodes;
        set<Edge*> unused_edges;
        
        graph->for_each_node([&](Node* n) {
            if (!called_nodes.count(n)) {
                unused_nodes.insert(n);
            }
        });
        
        graph->for_each_edge([&](Edge* e) {
            if (!called_edges.count(e)) {
                unused_edges.insert(e);
            }
        });
        
        
        
        // Destroy all the extra edges (in case they use extra nodes)
        for (auto* e : unused_edges) {
            graph->destroy_edge(e);
        }
        
        for (auto* n : unused_nodes) {
            graph->destroy_node(n);
        }
    }

    if (bluntify) {
        graph->bluntify();
    }

    if (!path_name.empty()) {
        graph->keep_path(path_name);
    }

    if (!paths_to_retain.empty() || retain_complement) {
        graph->paths.keep_paths(paths_to_retain);
    }

    if (drop_paths) {
        graph->paths.clear();
    }

    if (remove_orphans) {
        graph->remove_orphan_edges();
    }

    if (unchop) {
        graph->unchop();
    }

    if (simplify_graph) {
        graph->simplify_siblings();
    }

    if (normalize_graph) {
        graph->normalize();
    }

    if (until_normal_iter) {
        graph->normalize(until_normal_iter);
    }

    if (strong_connect) {
        graph->keep_multinode_strongly_connected_components();
    }

    if (remove_non_path) {
        graph->remove_non_path();
    }
    
    if (remove_path) {
        graph->remove_path();
    }

    if (force_path_match) {
        graph->force_path_match();
    }

    if (orient_forward) {
        algorithms::orient_nodes_forward(graph);
    }

    if (flip_doubly_reversed_edges) {
        graph->flip_doubly_reversed_edges();
    }

    if (dagify_steps) {
        unordered_map<int64_t, pair<int64_t, bool> > node_translation;
        *graph = graph->dagify(dagify_steps, node_translation, 0, dagify_component_length_max);
    }

    if (dagify_to) {
        unordered_map<int64_t, pair<int64_t, bool> > node_translation;
        // use the walk as our maximum number of steps; it's the worst case
        *graph = graph->dagify(dagify_to, node_translation, dagify_to, dagify_component_length_max);
    }

    if (unfold_to) {
        unordered_map<int64_t, pair<int64_t, bool> > node_translation;
        *graph = graph->unfold(unfold_to, node_translation);
    }

    if (remove_null) {
        graph->remove_null_nodes_forwarding_edges();
    }

    if (sort_graph) {
        algorithms::sort(graph);
    }

    if (break_cycles) {
        graph->break_cycles();
    }

    // to subset the graph
    if (!root_nodes.empty()) {
        VG g;
        for (auto root : root_nodes) {
            graph->nonoverlapping_node_context_without_paths(graph->get_node(root), g);
            graph->expand_context(g, max(context_steps, 1));
            g.remove_orphan_edges();
        }
        *graph = g;
    }

    if (!aln_file.empty()) {
        // read in the alignments and save their paths
        vector<Path> paths;
        function<void(Alignment&)> lambda = [&graph, &paths](Alignment& aln) {
            Path path = simplify(aln.path());
            path.set_name(aln.name());
            paths.push_back(path);
        };
        if (aln_file == "-") {
            stream::for_each(std::cin, lambda);
        } else {
            ifstream in;
            in.open(aln_file.c_str());
            stream::for_each(in, lambda);
        }
        if (!label_paths) {
            // execute the edits
            auto translation = graph->edit(paths, true);
            if (!translation_file.empty()) {
                ofstream out(translation_file);
                stream::write_buffered(out, translation, 0);
                out.close();
            }
        } else {
            // just add the path labels to the graph
            for (auto& path : paths) {
                graph->paths.extend(path);
            }
        }
    }

    if (!loci_file.empty()) {
        // read in the alignments and save their paths
        vector<Path> paths;
        function<void(Locus&)> lambda = [&graph, &paths, &called_genotypes_only](Locus& locus) {
            // if we are only doing called genotypes, record so we can filter alleles
            set<int> alleles_in_genotype;
            if (called_genotypes_only) {
                for (int i = 0; i < locus.genotype_size(); ++i) {
                    for (int j = 0; j < locus.genotype(i).allele_size(); ++j) {
                        alleles_in_genotype.insert(locus.genotype(i).allele(j));
                    }
                }
            }
            for (int i = 0; i < locus.allele_size(); ++i) {
                // skip alleles not in the genotype if using only called genotypes
                if (!alleles_in_genotype.empty()) {
                    if (!alleles_in_genotype.count(i)) continue;
                }
                Path path = simplify(locus.allele(i));
                stringstream name;
                name << locus.name() << ":" << i;
                path.set_name(name.str());
                paths.push_back(path);
            }
        };
        if (loci_file == "-") {
            stream::for_each(std::cin, lambda);
        } else {
            ifstream in;
            in.open(loci_file.c_str());
            stream::for_each(in, lambda);
        }
        // execute the edits and produce the translation if requested.
        // Make sure to break at node ends, but don't add any paths because they're just loci alleles and not real paths.
        auto translation = graph->edit(paths, false, false, true);
        if (!translation_file.empty()) {
            ofstream out(translation_file);
            stream::write_buffered(out, translation, 0);
            out.close();
        }
    }

    // and optionally compact ids
    if (compact_ids) {
        algorithms::sort(graph);
        graph->compact_ids();
    }

    if (compact_ranks) {
        graph->paths.compact_ranks();
    }

    if (prune_complex) {
        if (!(path_length > 0 && edge_max > 0)) {
            cerr << "[vg mod]: when pruning complex regions you must specify a --path-length and --edge-max" << endl;
            return 1;
        }
        graph->prune_complex_with_head_tail(path_length, edge_max);
    }

    if (prune_subgraphs) {
        graph->prune_short_subgraphs(path_length);
    }

    if (chop_to) {
        graph->dice_nodes(chop_to);
        graph->paths.compact_ranks();
    }

    if (kill_labels) {
        graph->for_each_node([](Node* n) { n->clear_sequence(); });
    }

    if (add_start_and_end_markers) {
        if (!(path_length > 0)) {
            cerr << "[vg mod]: when adding start and end markers you must provide a --path-length" << endl;
            return 1;
        }
        Node* head_node = NULL;
        Node* tail_node = NULL;
        graph->add_start_end_markers(path_length, '#', '$', head_node, tail_node);
    }

    if (destroy_node_id > 0) {
        graph->destroy_node(destroy_node_id);
    }

    if (cactus) {
        // ensure we're sorted
        algorithms::sort(graph);
        *graph = cactusify(*graph);
        // no paths survive, make sure they are erased
        graph->paths = Paths();
    }

    graph->serialize_to_ostream(std::cout);

    delete graph;

    return 0;
}
示例#19
0
文件: LevelMine.cpp 项目: mrDIMAS/src
LevelMine::LevelMine(unique_ptr<Game> & game, const unique_ptr<PlayerTransfer> & playerTransfer) : Level(game, playerTransfer) {
	mName = LevelName::Mine;

	LoadLocalization("mine.loc");

	mPlayer->mYaw.SetTarget(180.0f);

	LoadSceneFromFile("data/maps/mine.scene");

	mPlayer->SetPosition(GetUniqueObject("PlayerPosition")->GetPosition());

	Vector3 placePos = GetUniqueObject("PlayerPosition")->GetPosition();
	Vector3 playerPos = mPlayer->GetCurrentPosition();

	mPlayer->GetHUD()->SetObjective(mLocalization.GetString("objective1"));

	AddInteractiveObject("Note", make_shared<InteractiveObject>(GetUniqueObject("Note1")), [this] { mPlayer->GetInventory()->AddReadedNote(mLocalization.GetString("note1Desc"), mLocalization.GetString("note1")); });
	AddInteractiveObject("Note", make_shared<InteractiveObject>(GetUniqueObject("Note2")), [this] { mPlayer->GetInventory()->AddReadedNote(mLocalization.GetString("note2Desc"), mLocalization.GetString("note2")); });
	AddInteractiveObject("Note", make_shared<InteractiveObject>(GetUniqueObject("Note3")), [this] { mPlayer->GetInventory()->AddReadedNote(mLocalization.GetString("note3Desc"), mLocalization.GetString("note3")); });
	AddInteractiveObject("Note", make_shared<InteractiveObject>(GetUniqueObject("Note4")), [this] { mPlayer->GetInventory()->AddReadedNote(mLocalization.GetString("note4Desc"), mLocalization.GetString("note4")); });
	AddInteractiveObject("Note", make_shared<InteractiveObject>(GetUniqueObject("Note5")), [this] { mPlayer->GetInventory()->AddReadedNote(mLocalization.GetString("note5Desc"), mLocalization.GetString("note5")); });
	AddInteractiveObject("Note", make_shared<InteractiveObject>(GetUniqueObject("Note6")), [this] { mPlayer->GetInventory()->AddReadedNote(mLocalization.GetString("note6Desc"), mLocalization.GetString("note6")); });
	AddInteractiveObject("Note", make_shared<InteractiveObject>(GetUniqueObject("Note7")), [this] { mPlayer->GetInventory()->AddReadedNote(mLocalization.GetString("note7Desc"), mLocalization.GetString("note7")); });
	AddInteractiveObject("Note", make_shared<InteractiveObject>(GetUniqueObject("Note8")), [this] { mPlayer->GetInventory()->AddReadedNote(mLocalization.GetString("note8Desc"), mLocalization.GetString("note8")); });

	mStoneFallZone = GetUniqueObject("StoneFallZone");

	mNewLevelZone = GetUniqueObject("NewLevel");

	auto soundSystem = mGame->GetEngine()->GetSoundSystem();

	soundSystem->SetReverbPreset(ReverbPreset::Cave);

	AddSound(mMusic = soundSystem->LoadMusic("data/music/chapter2.ogg"));

	mConcreteWall = GetUniqueObject("ConcreteWall");
	mDeathZone = GetUniqueObject("DeadZone");
	mDetonator = GetUniqueObject("Detonator");

	AddSound(mAlertSound = soundSystem->LoadSound3D("data/sounds/alert.ogg"));
	mAlertSound->Attach(mDetonator);

	AddSound(mExplosionSound = soundSystem->LoadSound3D("data/sounds/blast.ogg"));
	mExplosionSound->SetReferenceDistance(10);

	mDetonatorActivated = 0;

	mExplosionFlashAnimator = 0;

	// Create detonator places
	AddItemPlace(mDetonatorPlace[0] = make_shared<ItemPlace>(GetUniqueObject("DetonatorPlace1"), Item::Type::Explosives));
	AddItemPlace(mDetonatorPlace[1] = make_shared<ItemPlace>(GetUniqueObject("DetonatorPlace2"), Item::Type::Explosives));
	AddItemPlace(mDetonatorPlace[2] = make_shared<ItemPlace>(GetUniqueObject("DetonatorPlace3"), Item::Type::Explosives));
	AddItemPlace(mDetonatorPlace[3] = make_shared<ItemPlace>(GetUniqueObject("DetonatorPlace4"), Item::Type::Explosives));

	mWireModels[0] = GetUniqueObject("WireModel1");
	mWireModels[1] = GetUniqueObject("WireModel2");
	mWireModels[2] = GetUniqueObject("WireModel3");
	mWireModels[3] = GetUniqueObject("WireModel4");

	mDetonatorModels[0] = GetUniqueObject("DetonatorModel1");
	mDetonatorModels[1] = GetUniqueObject("DetonatorModel2");
	mDetonatorModels[2] = GetUniqueObject("DetonatorModel3");
	mDetonatorModels[3] = GetUniqueObject("DetonatorModel4");

	mExplosivesModels[0] = GetUniqueObject("ExplosivesModel1");
	mExplosivesModels[1] = GetUniqueObject("ExplosivesModel2");
	mExplosivesModels[2] = GetUniqueObject("ExplosivesModel3");
	mExplosivesModels[3] = GetUniqueObject("ExplosivesModel4");

	mFindItemsZone = GetUniqueObject("FindItemsZone");

	AddAmbientSound(soundSystem->LoadSound3D("data/sounds/ambient/mine/ambientmine1.ogg"));
	AddAmbientSound(soundSystem->LoadSound3D("data/sounds/ambient/mine/ambientmine2.ogg"));
	AddAmbientSound(soundSystem->LoadSound3D("data/sounds/ambient/mine/ambientmine3.ogg"));
	AddAmbientSound(soundSystem->LoadSound3D("data/sounds/ambient/mine/ambientmine4.ogg"));
	AddAmbientSound(soundSystem->LoadSound3D("data/sounds/ambient/mine/ambientmine5.ogg"));

	mExplosionTimer = ITimer::Create();
	mBeepSoundTimer = ITimer::Create();
	mBeepSoundTiming = 1.0f;

	CreateItems();

	mReadyExplosivesCount = 0;

	MakeLadder("LadderBegin", "LadderEnd", "LadderEnter", "LadderBeginLeavePoint", "LadderEndLeavePoint");
	MakeDoor("Door1", 90);
	MakeDoor("Door3", 90);
	MakeDoor("DoorToAdministration", 90);
	MakeDoor("Door6", 90);
	MakeDoor("DoorToDirectorsOffice", 90);
	MakeDoor("DoorToResearchFacility", 90);

	MakeKeypad("Keypad1", "Keypad1Key0", "Keypad1Key1", "Keypad1Key2", "Keypad1Key3", "Keypad1Key4", "Keypad1Key5", "Keypad1Key6", "Keypad1Key7", "Keypad1Key8", "Keypad1Key9", "Keypad1KeyCancel", MakeDoor("StorageDoor", 90), "7854");
	MakeKeypad("Keypad2", "Keypad2Key0", "Keypad2Key1", "Keypad2Key2", "Keypad2Key3", "Keypad2Key4", "Keypad2Key5", "Keypad2Key6", "Keypad2Key7", "Keypad2Key8", "Keypad2Key9", "Keypad2KeyCancel", MakeDoor("DoorToResearchFacility", 90), "1689");
	MakeKeypad("Keypad3", "Keypad3Key0", "Keypad3Key1", "Keypad3Key2", "Keypad3Key3", "Keypad3Key4", "Keypad3Key5", "Keypad3Key6", "Keypad3Key7", "Keypad3Key8", "Keypad3Key9", "Keypad3KeyCancel", MakeDoor("DoorMedical", 90), "9632");

	mMusic->Play();

	mStages["ConcreteWallExp"] = false;
	mStages["FindObjectObjectiveSet"] = false;
	mStages["FoundObjectsForExplosion"] = false;

	// create paths
	const char * ways[] = {
		"WayA", "WayB", "WayC", "WayD", "WayE", "WayF", "WayG",
		"WayH", "WayI", "WayJ", "WayK"
	};
	Path p;
	for(auto w : ways) {
		p += Path(mScene, w);
	}

	p.Get("WayB1")->AddEdge(p.Get("WayA004"));
	p.Get("WayC1")->AddEdge(p.Get("WayA019"));
	p.Get("WayD1")->AddEdge(p.Get("WayA019"));
	p.Get("WayE1")->AddEdge(p.Get("WayA040"));
	p.Get("WayF1")->AddEdge(p.Get("WayA042"));
	p.Get("WayF009")->AddEdge(p.Get("WayG1"));
	p.Get("WayH1")->AddEdge(p.Get("WayA059"));
	p.Get("WayI1")->AddEdge(p.Get("WayA097"));
	p.Get("WayJ1")->AddEdge(p.Get("WayA073"));
	p.Get("WayK1")->AddEdge(p.Get("WayA027"));

	vector<shared_ptr<GraphVertex>> patrolPoints = {
		p.Get("WayA1"), p.Get("WayC024"), p.Get("WayB012"),
		p.Get("WayB012"), p.Get("WayD003"), p.Get("WayK005"),
		p.Get("WayE006"), p.Get("WayF019"), p.Get("WayG007"),
		p.Get("WayH010"), p.Get("WayA110"), p.Get("WayI009")
	};

	mEnemy = make_unique<Enemy>(mGame, p.mVertexList, patrolPoints);
	mEnemy->SetPosition(GetUniqueObject("EnemyPosition")->GetPosition());

	mExplosivesDummy[0] = GetUniqueObject("ExplosivesModel5");
	mExplosivesDummy[1] = GetUniqueObject("ExplosivesModel6");
	mExplosivesDummy[2] = GetUniqueObject("ExplosivesModel7");
	mExplosivesDummy[3] = GetUniqueObject("ExplosivesModel8");

	mExplodedWall = GetUniqueObject("ConcreteWallExploded");
	mExplodedWall->Hide();

	mExplosionFlashPosition = GetUniqueObject("ExplosionFlash");

	mPlayer->GetInventory()->RemoveItem(Item::Type::Crowbar, 1);

	DoneInitialization();
}
示例#20
0
	void makeScreenshot(const Path& filename) override
	{
		bgfx::saveScreenShot(filename.c_str());
	}
示例#21
0
文件: CmdShow.cpp 项目: SEJeff/task
int CmdShow::execute (std::string& output)
{
  int rc = 0;
  std::stringstream out;

  // Obtain the arguments from the description.  That way, things like '--'
  // have already been handled.
  std::vector <std::string> words = context.a3.extract_words ();
  if (words.size () > 2)
    throw std::string (STRING_CMD_SHOW_ARGS);

  int width = context.getWidth ();

  // Complain about configuration variables that are not recognized.
  // These are the regular configuration variables.
  // Note that there is a leading and trailing space, to make it easier to
  // search for whole words.
  std::string recognized =
    " abbreviation.minimum"
    " active.indicator"
    " avoidlastcolumn"
    " bulk"
    " burndown.bias"
    " calendar.details"
    " calendar.details.report"
    " calendar.holidays"
    " calendar.legend"
    " calendar.offset"
    " calendar.offset.value"
    " color"
    " color.active"
    " color.alternate"
    " color.blocked"
    " color.burndown.done"
    " color.burndown.pending"
    " color.burndown.started"
    " color.calendar.due"
    " color.calendar.due.today"
    " color.calendar.holiday"
    " color.calendar.overdue"
    " color.calendar.today"
    " color.calendar.weekend"
    " color.calendar.weeknumber"
    " color.completed"
    " color.debug"
    " color.deleted"
    " color.due"
    " color.due.today"
    " color.footnote"
    " color.header"
    " color.history.add"
    " color.history.delete"
    " color.history.done"
    " color.label"
    " color.overdue"
    " color.pri.H"
    " color.pri.L"
    " color.pri.M"
    " color.pri.none"
    " color.recurring"
    " color.summary.background"
    " color.summary.bar"
    " color.sync.added"
    " color.sync.changed"
    " color.sync.rejected"
    " color.tagged"
    " color.undo.after"
    " color.undo.before"
    " column.padding"
    " complete.all.projects"
    " complete.all.tags"
    " confirmation"
    " data.location"
    " dateformat"
    " dateformat.annotation"
    " dateformat.holiday"
    " dateformat.report"
    " debug"
    " default.command"
    " default.due"
    " default.priority"
    " default.project"
    " defaultheight"
    " defaultwidth"
    " dependency.confirmation"
    " dependency.indicator"
    " dependency.reminder"
    " detection"
    " displayweeknumber"
    " dom"
    " due"
    " echo.command"                      // Deprecated 2.0
    " edit.verbose"                      // Deprecated 2.0
    " editor"
    " exit.on.missing.db"
    " expressions"
    " extensions"
    " fontunderline"
    " gc"
    " hyphenate"
    " indent.annotation"
    " indent.report"
    " journal.info"
    " journal.time"
    " journal.time.start.annotation"
    " journal.time.stop.annotation"
    " json.array"
    " list.all.projects"
    " list.all.tags"
    " locale"
    " locking"
    " merge.autopush"
    " merge.default.uri"
    " monthsperline"
    " nag"
    " patterns"
    " pull.default.uri"
    " push.default.uri"
    " recurrence.indicator"
    " recurrence.limit"
    " regex"
    " row.padding"
    " rule.precedence.color"
    " search.case.sensitive"
    " shadow.command"
    " shadow.file"
    " shadow.notify"
    " shell.prompt"
    " tag.indicator"
    " taskd.server"
    " taskd.credentials"
    " undo.style"
    " urgency.active.coefficient"
    " urgency.annotations.coefficient"
    " urgency.blocked.coefficient"
    " urgency.blocking.coefficient"
    " urgency.due.coefficient"
    " urgency.next.coefficient"
    " urgency.priority.coefficient"
    " urgency.project.coefficient"
    " urgency.tags.coefficient"
    " urgency.waiting.coefficient"
    " urgency.age.coefficient"
    " urgency.age.max"
    " verbose"
    " weekstart"
    " xterm.title"
    " ";

  // This configuration variable is supported, but not documented.  It exists
  // so that unit tests can force color to be on even when the output from task
  // is redirected to a file, or stdout is not a tty.
  recognized += "_forcecolor ";

  std::vector <std::string> all;
  context.config.all (all);

  std::vector <std::string> unrecognized;
  std::vector <std::string>::iterator i;
  for (i = all.begin (); i != all.end (); ++i)
  {
    // Disallow partial matches by tacking a leading and trailing space on each
    // variable name.
    std::string pattern = " " + *i + " ";
    if (recognized.find (pattern) == std::string::npos)
    {
      // These are special configuration variables, because their name is
      // dynamic.
      if (i->substr (0, 14) != "color.keyword."        &&
          i->substr (0, 14) != "color.project."        &&
          i->substr (0, 10) != "color.tag."            &&
          i->substr (0,  8) != "holiday."              &&
          i->substr (0,  7) != "report."               &&
          i->substr (0,  6) != "alias."                &&
          i->substr (0,  5) != "hook."                 &&
          i->substr (0,  5) != "push."                 &&
          i->substr (0,  5) != "pull."                 &&
          i->substr (0,  6) != "merge."                &&
          i->substr (0,  4) != "uda."                  &&
          i->substr (0, 21) != "urgency.user.project." &&
          i->substr (0, 17) != "urgency.user.tag.")
      {
        unrecognized.push_back (*i);
      }
    }
  }

  // Find all the values that match the defaults, for highlighting.
  std::vector <std::string> default_values;
  Config default_config;
  default_config.setDefaults ();

  for (i = all.begin (); i != all.end (); ++i)
    if (context.config.get (*i) != default_config.get (*i))
      default_values.push_back (*i);

  // Create output view.
  ViewText view;
  view.width (width);
  view.add (Column::factory ("string", STRING_CMD_SHOW_CONF_VAR));
  view.add (Column::factory ("string", STRING_CMD_SHOW_CONF_VALUE));

  Color error ("bold white on red");
  Color warning ("black on yellow");

  std::string section;

  // Look for the first plausible argument which could be a pattern 
  if (words.size ())
    section = words[0];

  if (section == "all")
    section = "";

  for (i = all.begin (); i != all.end (); ++i)
  {
    std::string::size_type loc = i->find (section, 0);
    if (loc != std::string::npos)
    {
      // Look for unrecognized.
      Color color;
      if (std::find (unrecognized.begin (), unrecognized.end (), *i) != unrecognized.end ())
        color = error;
      else if (std::find (default_values.begin (), default_values.end (), *i) != default_values.end ())
        color = warning;

      std::string value = context.config.get (*i);
      // hide sensible information
      if ( (i->substr (0, 5) == "push."   ||
            i->substr (0, 5) == "pull."   ||
            i->substr (0, 6) == "merge.") && (i->find (".uri") != std::string::npos) ) {

        Uri uri (value);
        uri.parse ();
        value = uri.ToString ();
      }

      int row = view.addRow ();
      view.set (row, 0, *i, color);
      view.set (row, 1, value, color);
    }
  }

  out << "\n"
      << view.render ()
      << (view.rows () == 0 ? STRING_CMD_SHOW_NONE : "")
      << (view.rows () == 0 ? "\n\n" : "\n");

  if (default_values.size ())
  {
    out << STRING_CMD_SHOW_DIFFER;

    if (context.color ())
      out << "  "
          << format (STRING_CMD_SHOW_DIFFER_COLOR, warning.colorize ("color"))
          << "\n\n";
  }

  // Display the unrecognized variables.
  if (unrecognized.size ())
  {
    out << STRING_CMD_SHOW_UNREC << "\n";

    for (i = unrecognized.begin (); i != unrecognized.end (); ++i)
      out << "  " << *i << "\n";

    if (context.color ())
      out << "\n  " << format (STRING_CMD_SHOW_DIFFER_COLOR, error.colorize ("color"));

    out << "\n\n";
  }

  out << legacyCheckForDeprecatedVariables ();
  out << legacyCheckForDeprecatedColor ();
  out << legacyCheckForDeprecatedColumns ();

  // TODO Check for referenced but missing theme files.
  // TODO Check for referenced but missing string files.
  // TODO Check for referenced but missing tips files.

  // Check for referenced but missing hook scripts.
#ifdef HAVE_LIBLUA
  std::vector <std::string> missing_scripts;
  for (i = all.begin (); i != all.end (); ++i)
  {
    if (i->substr (0, 5) == "hook.")
    {
      std::string value = context.config.get (*i);
      Nibbler n (value);

      // <path>:<function> [, ...]
      while (!n.depleted ())
      {
        std::string file;
        std::string function;
        if (n.getUntil (':', file) &&
            n.skip (':')           &&
            n.getUntil (',', function))
        {
          Path script (file);
          if (!script.exists () || !script.readable ())
            missing_scripts.push_back (file);

          (void) n.skip (',');
        }
      }
    }
  }

  if (missing_scripts.size ())
  {
    out << STRING_CMD_SHOW_HOOKS << "\n";

    for (i = missing_scripts.begin (); i != missing_scripts.end (); ++i)
      out << "  " << *i << "\n";

    out << "\n";
  }
#endif

  // Check for bad values in rc.annotations.
  // TODO Deprecated.
  std::string annotations = context.config.get ("annotations");
  if (annotations != "full"   &&
      annotations != "sparse" &&
      annotations != "none")
    out << format (STRING_CMD_SHOW_CONFIG_ERROR, "annotations", annotations)
        << "\n";

  // Check for bad values in rc.calendar.details.
  std::string calendardetails = context.config.get ("calendar.details");
  if (calendardetails != "full"   &&
      calendardetails != "sparse" &&
      calendardetails != "none")
    out << format (STRING_CMD_SHOW_CONFIG_ERROR, "calendar.details", calendardetails)
        << "\n";

  // Check for bad values in rc.calendar.holidays.
  std::string calendarholidays = context.config.get ("calendar.holidays");
  if (calendarholidays != "full"   &&
      calendarholidays != "sparse" &&
      calendarholidays != "none")
    out << format (STRING_CMD_SHOW_CONFIG_ERROR, "calendar.holidays", calendarholidays)
        << "\n";

  // Check for bad values in rc.default.priority.
  std::string defaultPriority = context.config.get ("default.priority");
  if (defaultPriority != "H" &&
      defaultPriority != "M" &&
      defaultPriority != "L" &&
      defaultPriority != "")
    out << format (STRING_CMD_SHOW_CONFIG_ERROR, "default.priority", defaultPriority)
        << "\n";

  // Verify installation.  This is mentioned in the documentation as the way
  // to ensure everything is properly installed.

  if (all.size () == 0)
  {
    out << STRING_CMD_SHOW_EMPTY << "\n";
    rc = 1;
  }
  else
  {
    Directory location (context.config.get ("data.location"));

    if (location._data == "")
      out << STRING_CMD_SHOW_NO_LOCATION << "\n";

    if (! location.exists ())
      out << STRING_CMD_SHOW_LOC_EXIST << "\n";
  }

  output = out.str ();
  return rc;
}
void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::Scope* scope) const
{
    path.startNewSubPath (startPos.resolve (scope));
}
示例#23
0
文件: AntWar.cpp 项目: beanhome/dev
//makes the bots moves for the turn
void AntWar::MakeMoves()
{
	NavDijkstra m_oNavDijkstra(m_oWorld.GetGrid());
	NavAStar m_oNavAStar(m_oWorld.GetGrid());

	int   iExplMin = 5;
	float fExplCoeff = 0.1f;

	int iAntCount = m_oWorld.GetAntCount();
	int iExpl = max(min(iExplMin, iAntCount), (int)(iAntCount * fExplCoeff));
	int iProtect = 0;//max<int>(0, min<int>(m_oWorld.GetMinDistCount(), (int)m_oWorld.GetAntCount() - iExpl));
	int iGuard = max<int>(0, iAntCount - (iExpl + iProtect));

	DistAntMap::const_reverse_iterator begin = m_oWorld.GetAntByDist().rbegin();
	DistAntMap::const_reverse_iterator end = m_oWorld.GetAntByDist().rend();
	DistAntMap::const_reverse_iterator it;

	// Default Explore / Guard / Protect
	int i;
	for (i=0, it=begin  ; it != end ; ++it, ++i)
	{
		Ant* pAnt = it->second;
		if (pAnt->GetPlayer() > 0)
			continue;

		Vector2 loc = pAnt->GetLocation();
		
		if (i<iExpl)
			pAnt->SetRole(Explore);
		
		if (i>=iExpl && i<iExpl+iGuard)
			pAnt->SetRole(Guard);

		if (i>=iExpl+iGuard)
			pAnt->SetRole(Protect);
	}


	// Attack
	for (uint i=0 ; i<m_oWorld.GetAntCount() ; ++i)
	{
		Ant& oAnt = m_oWorld.GetAnt(i);
		if (oAnt.GetPlayer() == 0)
			oAnt.TestAnts(m_oWorld);
	}

	for (uint i=0 ; i<m_oWorld.GetAntCount() ; ++i)
	{
		Ant& oAnt = m_oWorld.GetAnt(i);
		if (oAnt.GetPlayer() == 0)
			oAnt.ReachAllies(m_oWorld);
	}

	// Loot
	vector<Vector2> aLootLoc;
	aLootLoc.reserve(m_oWorld.GetEnemyHills().size() + m_oWorld.GetFoods().size());
	for (uint i=0 ; i<m_oWorld.GetEnemyHills().size() ; ++i)
	{
		aLootLoc.push_back(m_oWorld.GetEnemyHills()[i]);
	}
	for (uint i=0 ; i<m_oWorld.GetFoods().size() ; ++i)
	{
		aLootLoc.push_back(m_oWorld.GetFoods()[i]);
	}

	if (aLootLoc.size())
	{
		vector<Vector2> aLootAnt;
		for (uint i=0 ; i<m_oWorld.GetAntCount() ; ++i)
		{
			Ant& oAnt = m_oWorld.GetAnt(i);
			if (oAnt.GetPlayer() > 0) continue;
			if (oAnt.GetRole() == Attack) continue;

			aLootAnt.push_back(oAnt.GetLocation());
		}
	
		m_oNavDijkstra.Explore(aLootLoc, aLootAnt, 0, m_oWorld.GetTurn());

#ifdef MYDEBUG
		//m_oNavDijkstra.PrintDebug();
#endif

		typedef map<Vector2, set<Path>> AllPathMap;
		typedef pair<Vector2, set<Path>> AllPathPair;
		AllPathMap aAllPath;
		for (uint i=0 ; i<aLootAnt.size() ; ++i)
		{
			Path oPath;
			if (m_oNavDijkstra.GetPath(aLootAnt[i], oPath))
			{
				Vector2 start = oPath.GetStart();
				AllPathMap::iterator it = aAllPath.find(start);
				if (it == aAllPath.end())
				{
					pair<AllPathMap::iterator, bool> res = aAllPath.insert(AllPathPair(start, set<Path>()));
					it = res.first;
				}
				it->second.insert(oPath);
			}
		}

		for (AllPathMap::const_iterator it = aAllPath.begin() ; it != aAllPath.end() ; ++it)
		{
			const Path& oPath = *(it->second.begin());
			Ant& oAnt = m_oWorld.GetAnt(oPath.GetTarget());
			ASSERT(oAnt.GetPlayer() == 0);
			if (oAnt.GetPath().GetLength() == 0)
			{
				oAnt.SetPath(oPath.GetInverse());
				oAnt.SetRole(Loot);
			}
		}
	}



	// Compute Path
	for (i=0 ; i<(int)m_oWorld.GetAntCount() ; ++i)
	{
		Ant& oAnt = m_oWorld.GetAnt(i);

		if (oAnt.GetPlayer() > 0)
			continue;

		if (oAnt.GetRole() == Explore)
		{
			if (m_oNavDijkstra.FindNearest(oAnt.GetLocation(), NavDijkstra::Undiscovered, oAnt.GetPath(), m_oWorld.GetTurn()) == false)
				oAnt.SetRole(Guard);
		}

		if (oAnt.GetRole() == Guard)
		{
			if (m_oNavDijkstra.FindNearest(oAnt.GetLocation(), NavDijkstra::Unvisible, oAnt.GetPath(), m_oWorld.GetTurn()) == false)
				oAnt.SetRole(Protect);
		}

		if (oAnt.GetRole() == Attack || oAnt.GetRole() == Help)
		{
			m_oNavAStar.FindPath(oAnt.GetLocation(), oAnt.GetFirstEnemy(), m_oWorld.GetAttackRadiusSq(), oAnt.GetPath(), m_oWorld.GetTurn());
		}

		if (oAnt.GetRole() == Flee)
		{
			if (m_oNavAStar.FindPath(oAnt.GetLocation(), m_oWorld.GetFriendHills()[0], 0, oAnt.GetPath(), m_oWorld.GetTurn()) == false)
			{
				// ?
			}
		}

		//if (oAnt.GetRole() == Protect)
		//{
		//	if (m_oNavDijkstra.FindNearest(oAnt.GetLocation(), m_oWorld.GetBestDistCase(), oAnt.GetPath(), m_oWorld.GetTurn()) == false)
		//	{

		//	}
		//}

		if (oAnt.GetPath().GetLength() == 0 && m_oWorld.GetGrid().GetCase(oAnt.GetLocation()).GetAntInfluence() <= 0)
		{
			m_oNavDijkstra.FindNearest(oAnt.GetLocation(), NavDijkstra::Safe, oAnt.GetPath(), m_oWorld.GetTurn());
		}
	}

	// Exec Move
	for (it=begin, i=0 ; it != m_oWorld.GetAntByDist().rend(); ++it, ++i)
	{
		Ant* pAnt = it->second;
		if (pAnt->GetPlayer() == 0 && pAnt->GetPath().GetLength() > 0)
		{
			EDirection dir;
			Vector2 target = pAnt->GetPath()[0];
			if (m_oWorld.IsEmpty(target))
			{
				dir = m_oWorld.GetDirection(pAnt->GetLocation(), target);
 				ExecMove(pAnt->GetLocation(), dir);
			}
		}
	}
};
void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::Scope*) const
{
    path.closeSubPath();
}
	void process(const WorkUnit *workUnit, WorkResult *workResult, const bool &stop) {
		const RectangularWorkUnit *rect = static_cast<const RectangularWorkUnit *>(workUnit);
		GBDPTWorkResult *result = static_cast<GBDPTWorkResult *>(workResult);
		bool needsTimeSample = m_sensor->needsTimeSample();
		Float time = m_sensor->getShutterOpen();

		result->setOffset(rect->getOffset());
		result->setSize(rect->getSize());
		result->clear();
		m_hilbertCurve.initialize(TVector2<uint8_t>(rect->getSize()));

		Path emitterSubpath;
		Path sensorSubpath;

		/*shift direction is hard-coded. future releases should support arbitrary kernels. */
		Vector2 shifts[4] = { Vector2(0, -1), Vector2(-1, 0), Vector2(1, 0), Vector2(0, 1) };

		if (m_config.maxDepth == -1){
			Log(EWarn, "maxDepth is unlimited, set to 12!");
			m_config.maxDepth = 12;
		}

		/* Determine the necessary random walk depths based on properties of
		the endpoints */
		int emitterDepth = m_config.maxDepth,
			sensorDepth = m_config.maxDepth;

		//marco: ensure some required properties (temporary solution)
		m_config.sampleDirect = false;

		/* Go one extra step if the sensor can be intersected */
		if (!m_scene->hasDegenerateSensor() && emitterDepth != -1)
			++emitterDepth;

		/* Sensor subpath legth +1 if there are emitters that can be intersected (to allow very direct sensor paths)*/
		if (!m_scene->hasDegenerateEmitters() && sensorDepth != -1)
			++sensorDepth;


		/*loop over pixels in block*/
		for (size_t i = 0; i<m_hilbertCurve.getPointCount(); ++i) {


			int neighborCount = m_config.nNeighbours;
			std::vector<ShiftPathData> pathData(neighborCount+1, sensorDepth+3);
			pathData[0].success = true;
			pathData[0].couldConnectAfterB = true;

			/*allocate memory depending on number of neighbours*/
			std::vector<Path> emitterSubpath(neighborCount + 1);
			std::vector<Path> sensorSubpath(neighborCount + 1);
			std::vector<double>	jacobianLP(neighborCount);
			std::vector<double>	genGeomTermLP(neighborCount + 1);
			std::vector<Spectrum> value(neighborCount + 1);
			std::vector<Float> miWeight(neighborCount + 1);
			std::vector<Float> valuePdf(neighborCount + 1);
			bool *pathSuccess = (bool *)alloca((neighborCount + 1) * sizeof(bool));

			Point2 samplePos;

			Point2i offset = Point2i(m_hilbertCurve[i]) + Vector2i(rect->getOffset());
			m_sampler->generate(offset);

			int spp = m_sampler->getSampleCount();

			/* For each sample */
			for (size_t j = 0; j<spp; j++) {
				if (stop)
					break;

				if (needsTimeSample)
					time = m_sensor->sampleTime(m_sampler->next1D());


				/* Start new emitter and sensor subpaths */
				emitterSubpath[0].initialize(m_scene, time, EImportance, m_pool);
				sensorSubpath[0].initialize(m_scene, time, ERadiance, m_pool);

				/* Perform a random walk using alternating steps on each path */
				Path::alternatingRandomWalkFromPixel(m_scene, m_sampler,
					emitterSubpath[0], emitterDepth, sensorSubpath[0],
					sensorDepth, offset, m_config.rrDepth, m_pool);


				samplePos = sensorSubpath[0].vertex(1)->getSamplePosition();

				double jx, jy;

				//marco: Hack- Required to store negative gradients...
				for (size_t i = 0; i < (1 + m_config.nNeighbours); ++i){
					const_cast<ImageBlock *>(result->getImageBlock(i))->setAllowNegativeValues(true);
					if (m_config.lightImage)
						const_cast<ImageBlock *>(result->getLightImage(i))->setAllowNegativeValues(true);
				}
				Path connectPath;
				int ptx;

				/* create shift-able path  */
				bool couldConnect = createShiftablePath(connectPath, emitterSubpath[0], sensorSubpath[0], 1, sensorSubpath[0].vertexCount() - 1, ptx);

				/*  geometry term(s) of base  */
				m_offsetGenerator->computeMuRec(connectPath, pathData[0].muRec);
				int idx = 0;
				for (int v = pathData[0].muRec.extra[0] - 1; v >= 0; v--){
					int idx = connectPath.vertexCount() - 1 - v;
					if (Path::isConnectable_GBDPT(connectPath.vertex(v), m_config.m_shiftThreshold) && v >= pathData[0].muRec.extra[2])
						pathData[0].genGeomTerm.at(idx) = connectPath.calcSpecularPDFChange(v, m_offsetGenerator);
					else
						pathData[0].genGeomTerm.at(idx) = pathData[0].genGeomTerm.at(idx - 1);
				}

				/*shift base path if possible*/
				for (int k = 0; k<neighborCount; k++){
					//we cannot shift very direct paths!
					pathData[k + 1].success = pathData[0].muRec.extra[0] <= 2 ? false : m_offsetGenerator->generateOffsetPathGBDPT(connectPath, sensorSubpath[k + 1], pathData[k + 1].muRec, shifts[k], pathData[k + 1].couldConnectAfterB, false);
					
					//if shift successful, compute jacobian and geometry term for each possible connection strategy that affects the shifted sub path
					//for the manifold exploration shift there are only two connectible vertices in the affected chain (v_b and v_c)
					if (pathData[k + 1].success){

						int idx = 0; int a, b, c;
						for (int v = pathData[k + 1].muRec.extra[0] - 1; v >= 0; v--){
							int idx = connectPath.vertexCount() - 1 - v;
							if (Path::isConnectable_GBDPT(connectPath.vertex(v), m_config.m_shiftThreshold) && v >= pathData[k + 1].muRec.extra[2]){
								a = pathData[k + 1].muRec.extra[0];
								b = v >= pathData[k + 1].muRec.extra[1] ? v : pathData[k + 1].muRec.extra[1];
								c = v >= pathData[k + 1].muRec.extra[1] ? v - 1 : pathData[k + 1].muRec.extra[2];
								jx = connectPath.halfJacobian_GBDPT(a, b, c, m_offsetGenerator);
								jy = sensorSubpath[k + 1].halfJacobian_GBDPT(a, b, c, m_offsetGenerator);
								pathData[k+1].jacobianDet.at(idx) = jy / jx;
								pathData[k+1].genGeomTerm.at(idx) = sensorSubpath[k + 1].calcSpecularPDFChange(v, m_offsetGenerator);
							}
							else{
								pathData[k + 1].jacobianDet.at(idx) = pathData[k + 1].jacobianDet.at(idx - 1);
								pathData[k + 1].genGeomTerm.at(idx) = pathData[k + 1].genGeomTerm.at(idx - 1);
							}
						}
					}
					sensorSubpath[k + 1].reverse();
				}

				/*save index of vertex b for evaluation (indexing is reversed)*/
				int v_b = connectPath.vertexCount() - 1 - pathData[0].muRec.extra[1];

				/* evaluate base and offset paths */
				evaluate(result, emitterSubpath[0], sensorSubpath, pathData, v_b,
					value, miWeight, valuePdf, jacobianLP, genGeomTermLP, pathSuccess);

				/* clean up memory */
				connectPath.release(ptx, ptx + 2, m_pool);
				for (int k = 0; k<neighborCount; k++){
					if (pathData[k+1].success){
						sensorSubpath[k + 1].reverse();
						sensorSubpath[k + 1].release(pathData[k + 1].muRec.l, pathData[k + 1].muRec.m + 1, m_pool);
					}
				}
				sensorSubpath[0].release(m_pool);
				emitterSubpath[0].release(m_pool);
				
				for (size_t i = 0; i < (1 + m_config.nNeighbours); ++i){
					const_cast<ImageBlock *>(result->getImageBlock(i))->setAllowNegativeValues(false);
					if (m_config.lightImage)
						const_cast<ImageBlock *>(result->getLightImage(i))->setAllowNegativeValues(false);
				}

				m_sampler->advance();
			}
		}
		/* Make sure that there were no memory leaks */
		Assert(m_pool.unused());
	}
void RelativePointPath::LineTo::addToPath (Path& path, Expression::Scope* scope) const
{
    path.lineTo (endPoint.resolve (scope));
}
示例#27
0
void ArrangeAlignment::RedrawDiagram(ReDrawInfoType* ExtraInfo)
{
	// objects drawn in the render region must be relatively large in the given coord space
	// else Gavin's curve flattening results in visible straight lines
	// so every dimension is scaled by scale
	INT32 scale=1000;

	// make a render region
	DocRect VirtRendRect;
	VirtRendRect.lo.x=-1*scale;
	VirtRendRect.lo.y=-2*scale;
	VirtRendRect.hi.x=(DiagWidth +1)*scale;
	VirtRendRect.hi.y=(DiagHeight+2)*scale;
	RenderRegion* pRender=CreateGRenderRegion(&VirtRendRect,ExtraInfo);

	if (pRender!=NULL)
	{
		pRender->SaveContext();

		// currently this must be set here before any colour tables calculated
		Quality             AntiAliasQuality(Quality::QualityMax);
		QualityAttribute    AntiAliasQualityAttr(AntiAliasQuality);
		pRender->SetQuality(&AntiAliasQualityAttr,FALSE);

		// Render the background rectangle
		DialogColourInfo RedrawColours;
		pRender->SetLineColour(RedrawColours.DialogBack());
		pRender->SetFillColour(RedrawColours.DialogBack());
		pRender->DrawRect(&VirtRendRect);

		// declared at this scope else RestoreContext() dies!
		RadialFillAttribute Fill;		

		// set up some defaults used by all objects
		Fill.MakeElliptical();
		Fill.Colour=DocColour(255,255,255);
		pRender->SetLineColour(BLACK);
		pRender->SetLineWidth(0);

		for (INT32 i=0; i<DiagRects; i++)
		{
			// reverse order in which objets are rendered (now filled!)
			INT32 j=DiagRects-1-i;

			// set fill colour of each object
			switch (j)
			{
				case  0: Fill.EndColour=DocColour(255,255,0); break;
				case  1: Fill.EndColour=DocColour(0,0,255);   break;
				case  2: Fill.EndColour=DocColour(255,0,0);   break;
				case  3: Fill.EndColour=DocColour(0,160,0);   break;
				default: Fill.EndColour=DocColour(0,0,0);     break;
			}

			// get bound rect of object to be drawn
			INT32 x=DiagRectX[Align.h][j].lo*scale;
			INT32 w=DiagRectX[Align.h][j].hi*scale-x;
			INT32 y=DiagRectY[Align.v][j].lo*scale;
			INT32 h=DiagRectY[Align.v][j].hi*scale-y;

			// create shape and fill geometries
			Path shape;
			shape.Initialise(16,8);
			shape.IsFilled=TRUE;
			shape.FindStartOfPath();
			switch (j)
			{
				case 0:
				{
					// create a rectangle
					shape.InsertMoveTo(DocCoord(x,y));
					shape.InsertLineTo(DocCoord(x,y+h));
					shape.InsertLineTo(DocCoord(x+w,y+h));
					shape.InsertLineTo(DocCoord(x+w,y));
					shape.InsertLineTo(DocCoord(x,y));

//					// create a radial fill
//					Fill.StartPoint=DocCoord(x+w*3/16,y+h*3/4);
//					Fill.EndPoint  =DocCoord(x+w*3/8,y+h/2);
//					Fill.EndPoint2 =DocCoord(x+w*3/8,y+h);
					break;
				}

				case 1:
				{
					// create a pseudo ellipse
					shape.InsertMoveTo( DocCoord(x,y+h/2));
					shape.InsertCurveTo(DocCoord(x,y+h*3/4),  DocCoord(x+w/4,y+h),  DocCoord(x+w/2,y+h));
					shape.InsertCurveTo(DocCoord(x+w*3/4,y+h),DocCoord(x+w,y+h*3/4),DocCoord(x+w,y+h/2));
					shape.InsertCurveTo(DocCoord(x+w,y+h/4),  DocCoord(x+w*3/4,y),  DocCoord(x+w/2,y));
					shape.InsertCurveTo(DocCoord(x+w/4,y),    DocCoord(x,y+h/4),    DocCoord(x,y+h/2));

// 					// create a radial fill
//					Fill.StartPoint=DocCoord(x+w*3/8,y+h*5/8);
//					Fill.EndPoint  =DocCoord(x+w*6/8,y+h/4);
//					Fill.EndPoint2 =DocCoord(x+w*6/8,y+h);
					break;
				}

				default:
				{
					// create a rounded rectangle
					shape.InsertMoveTo( DocCoord(x,y+h/2));
					shape.InsertCurveTo(DocCoord(x,y+h),  DocCoord(x,y+h),  DocCoord(x+w/2,y+h));
					shape.InsertCurveTo(DocCoord(x+w,y+h),DocCoord(x+w,y+h),DocCoord(x+w,y+h/2));
					shape.InsertCurveTo(DocCoord(x+w,y),  DocCoord(x+w,y),  DocCoord(x+w/2,y));
					shape.InsertCurveTo(DocCoord(x,y),    DocCoord(x,y),    DocCoord(x,y+h/2));

// 					// create a radial fill
//					Fill.StartPoint=DocCoord(x+w*3/16,y+h*3/4);
//					Fill.EndPoint  =DocCoord(x+w*3/8,y+h/2);
//					Fill.EndPoint2 =DocCoord(x+w*3/8,y+h);
					break;
				}

			}
//			pRender->SetFillGeometry(&Fill,FALSE);
			pRender->SetFillColour(Fill.EndColour);
			pRender->DrawPath(&shape);
		}

		pRender->RestoreContext();
		DestroyGRenderRegion(pRender);	// also blt's to screen
	}
}
void RelativePointPath::CubicTo::addToPath (Path& path, Expression::Scope* scope) const
{
    path.cubicTo (controlPoints[0].resolve (scope),
                  controlPoints[1].resolve (scope),
                  controlPoints[2].resolve (scope));
}
示例#29
0
 explicit NarrowPathName(Path _value)
   :value(Value::Donate(ConvertWideToACP(_value.c_str()))) {}
示例#30
0
void GraphicsContext::fillEllipseAsPath(const FloatRect& ellipse)
{
    Path path;
    path.addEllipse(ellipse);
    fillPath(path);
}