Example #1
0
int main()
{
	Span sp = Span(5);
	Span sp1 = Span(10000);
	Span sp2 = Span(10000);
	Span sp3 = Span(10);
	Span sp4 = Span(1);

	srand(time(NULL));
	sp.addNumber(5);
	sp.addNumber(3);
	sp.addNumber(17);
	sp.addNumber(9);
	sp.addNumber(11);
	std::cout << sp.shortestSpan() << std::endl;
	std::cout << sp.longestSpan() << std::endl;

	sp1.RandInterval(9000);
	std::cout << sp1.shortestSpan() << std::endl;
	std::cout << sp1.longestSpan() << std::endl;

	sp2.Interval(42, 9000);
	std::cout << sp2.shortestSpan() << std::endl;
	std::cout << sp2.longestSpan() << std::endl;

	sp3.RandInterval(9000);
	std::cout << sp3.shortestSpan() << std::endl;
	std::cout << sp3.longestSpan() << std::endl;

	sp4.addNumber(5);
	sp4.addNumber(6);
	std::cout << sp4.shortestSpan() << std::endl;
	std::cout << sp4.longestSpan() << std::endl;
	return (0);
}
Example #2
0
bool IPAddress::TryParse(RCString s, IPAddress& ip) {
	uint8_t buf[16];
	if (CCheck(::inet_pton(AF_INET, s, buf))) {
		ip = IPAddress(Span(buf, 4));
		return true;
	}
	if (CCheck(::inet_pton(AF_INET6, s, buf))) {
		ip = IPAddress(Span(buf, 16));
		return true;
	}
	return false;
}
Example #3
0
    // ----------------------------------------------------------------------------
    //  Draws all of the spans for 2 edges
    // ----------------------------------------------------------------------------
    void drawSpansBetweenEdges(std::shared_ptr<TransferMap> & map, Edge & e1, Edge & e2)
    {
        // Calculate differences between the y coordinates
        float e1ydiff = (float)(e1.p2[1] - e1.p1[1]);
        if (e1ydiff == 0.0f) return;
        float e2ydiff = (float)(e2.p2[1] - e2.p1[1]);
        if (e2ydiff == 0.0f) return;

        // Calculate differences between the x coordinates
        float e1xdiff = (float)(e1.p2[0] - e1.p1[0]);
        float e2xdiff = (float)(e2.p2[0] - e2.p1[0]);

        // Calculate factors to use for interpolation
        // with the edges and the step values to increase
        // them by after drawing each span
        float factor1 = (float)(e2.p1[1] - e1.p1[1]) / e1ydiff;
        float factorStep1 = 1.0f / e1ydiff;
        float factor2 = 0.0f;
        float factorStep2 = 1.0f / e2ydiff;

        // Loop through the lines between the edges and draw spans
        for(int y = e2.p1[1]; y < e2.p2[1]; y++) 
        {
            // Draw the span
            auto m1 = interp(*e1.m1, *e1.m2, factor1);
            auto m2 = interp(*e2.m1, *e2.m2, factor2);
            drawSpan(map, Span(m1, e1.p1[0] + (int)(e1xdiff * factor1),
                               m2, e2.p1[0] + (int)(e2xdiff * factor2)), y);

            // Increase factors
            factor1 += factorStep1;
            factor2 += factorStep2;
        }
    }
Example #4
0
int main()
{
	srand(std::time(0));
	try
	{
		Span sp = Span(5);
		sp.addNumber(5);
		sp.addNumber(3);
		sp.addNumber(17);
		sp.addNumber(9);
		sp.addNumber(11);
		std::cout << sp.shortestSpan() << std::endl;
		std::cout << sp.longestSpan() << std::endl;

		Span big(10000);
		big.initAll(randNumber);
		std::cout << big.shortestSpan() << std::endl;
		std::cout << big.longestSpan() << std::endl;

		Span sp2(1);
		std::cout << sp2.shortestSpan() << std::endl;
	}
	catch (std::exception & e)
	{
		std::cout << e.what() << std::endl;
	}
}
Example #5
0
// Preset Load
bool SweepSettings::Load(QSettings &s)
{
    mode = (OperationalMode)(s.value("Mode", (int)Mode()).toInt());

    start = s.value("Sweep/Start", Start().Val()).toDouble();
    stop = s.value("Sweep/Stop", Stop().Val()).toDouble();
    center = s.value("Sweep/Center", Center().Val()).toDouble();
    span = s.value("Sweep/Span", Span().Val()).toDouble();
    step = s.value("Sweep/Step", Step().Val()).toDouble();
    rbw = s.value("Sweep/RBW", RBW().Val()).toDouble();
    vbw = s.value("Sweep/VBW", VBW().Val()).toDouble();

    auto_rbw = s.value("Sweep/AutoRBW", AutoRBW()).toBool();
    auto_vbw = s.value("Sweep/AutoVBW", AutoVBW()).toBool();
    native_rbw = s.value("Sweep/NativeRBW", NativeRBW()).toBool();

    refLevel.Load(s, "Sweep/RefLevel");
    div = s.value("Sweep/Division", Div()).toDouble();
    attenuation = s.value("Sweep/Attenuation", Atten()).toInt();
    gain = s.value("Sweep/Gain", Gain()).toInt();
    preamp = s.value("Sweep/Preamp", Preamp()).toInt();

    sweepTime = s.value("Sweep/SweepTime", SweepTime().Val()).toDouble();
    processingUnits = s.value("Sweep/ProcessingUnits", ProcessingUnits()).toInt();
    detector = s.value("Sweep/Detector", Detector()).toInt();
    rejection = s.value("Sweep/Rejection", Rejection()).toBool();

    tgSweepSize = s.value("Sweep/TgSweepSize", tgSweepSize).toInt();
    tgHighRangeSweep = s.value("Sweep/TgHighRangeSweep", tgHighRangeSweep).toBool();
    tgPassiveDevice = s.value("Sweep/TgPassiveDevice", tgPassiveDevice).toBool();

    UpdateProgram();
    return true;
}
VFPProdProperties::ADB VFPProdProperties::bhp(const std::vector<int>& table_id,
                                              const Wells& wells,
                                              const ADB& qs,
                                              const ADB& thp_arg,
                                              const ADB& alq) const {
    const int nw = wells.number_of_wells;

    //Short-hands for water / oil / gas phases
    //TODO enable support for two-phase.
    assert(wells.number_of_phases == 3);
    const ADB& w = subset(qs, Span(nw, 1, BlackoilPhases::Aqua*nw));
    const ADB& o = subset(qs, Span(nw, 1, BlackoilPhases::Liquid*nw));
    const ADB& g = subset(qs, Span(nw, 1, BlackoilPhases::Vapour*nw));

    return bhp(table_id, w, o, g, thp_arg, alq);
}
Example #7
0
Point CCurve::NearestPoint(const Span& p, double *d)const
{
	double best_dist = 0.0;
	Point best_point = Point(0, 0);
	bool best_point_valid = false;
	Point prev_p = Point(0, 0);
	bool prev_p_valid = false;
	bool first_span = true;
	for(std::list<CVertex>::const_iterator It = m_vertices.begin(); It != m_vertices.end(); It++)
	{
		const CVertex& vertex = *It;
		if(prev_p_valid)
		{
			double dist;
			Point near_point = Span(prev_p, vertex, first_span).NearestPoint(p, &dist);
			first_span = false;
			if(!best_point_valid || dist < best_dist)
			{
				best_dist = dist;
				best_point = near_point;
				best_point_valid = true;
			}
		}
		prev_p = vertex.m_p;
		prev_p_valid = true;
	}
	if(d)*d = best_dist;
	return best_point;
}
    void NewtonIterationBlackoilInterleaved::formInterleavedSystem(const std::vector<ADB>& eqs,
                                                                   const Eigen::SparseMatrix<double, Eigen::RowMajor>& A,
                                                                   Mat& istlA) const
    {
        const int np = eqs.size();

        // Find sparsity structure as union of basic block sparsity structures,
        // corresponding to the jacobians with respect to pressure.
        // Use addition to get to the union structure.
        Eigen::SparseMatrix<double> structure = eqs[0].derivative()[0];
        for (int phase = 0; phase < np; ++phase) {
            structure += eqs[phase].derivative()[0];
        }
        Eigen::SparseMatrix<double, Eigen::RowMajor> s = structure;

        // Create ISTL matrix with interleaved rows and columns (block structured).
        assert(np == 3);
        istlA.setSize(s.rows(), s.cols(), s.nonZeros());
        istlA.setBuildMode(Mat::row_wise);
        const int* ia = s.outerIndexPtr();
        const int* ja = s.innerIndexPtr();
        for (Mat::CreateIterator row = istlA.createbegin(); row != istlA.createend(); ++row) {
            int ri = row.index();
            for (int i = ia[ri]; i < ia[ri + 1]; ++i) {
                row.insert(ja[i]);
            }
        }
        const int size = s.rows();
        Span span[3] = { Span(size, 1, 0),
                         Span(size, 1, size),
                         Span(size, 1, 2*size) };
        for (int row = 0; row < size; ++row) {
            for (int col_ix = ia[row]; col_ix < ia[row + 1]; ++col_ix) {
                const int col = ja[col_ix];
                MatrixBlockType block;
                for (int p1 = 0; p1 < np; ++p1) {
                    for (int p2 = 0; p2 < np; ++p2) {
                        block[p1][p2] = A.coeff(span[p1][row], span[p2][col]);
                    }
                }
                istlA[row][col] = block;
            }
        }
    }
Example #9
0
void View::dfs(
               const std::vector<Atom>::const_iterator & now,
               const std::vector<Atom>::const_iterator & end,
               std::vector<Span> & deque,
               const std::vector<int> & groups,
               std::vector<Column> & newCols,
               const std::vector<Text_token> & tokens,
               const std::string & text
               ) {
    if (now == end) {
        unsigned p, q, k, h;
        for (unsigned i = 0; i < newCols.size(); ++i) {
            newCols[i].spans.push_back(
                                       Span(
                                            "",
                                            deque[groups[i << 1]].from,
                                            deque[groups[(i << 1) + 1] - 1].to
                                            )
                                       );
            for (unsigned j = groups[i << 1]; j < groups[(i << 1) + 1]; ++j) {
                if (j > groups[i << 1]) {
                    q = query(tokens, deque[j-1].to - 1);
                    p = query(tokens, deque[j].from);
                    for (k = q + 1; k < p; ++k) {
                        for (h = tokens[k-1].to; h < tokens[k].from; ++h)
                            newCols[i].spans.back().value.push_back(text[h]);
                        newCols[i].spans.back().value += tokens[k].value;
                    }
                    for (h = tokens[p-1].to; h < tokens[p].from; ++h)
                        newCols[i].spans.back().value.push_back(text[h]);
                }
                newCols[i].spans.back().value += deque[j].value;
            }
        }
    } else {
        unsigned p, q;
        if (!deque.empty())
            q = query(tokens, deque.back().to - 1);
        for (
             std::vector<Span>::const_iterator i = now->column.spans.begin();
             i != now->column.spans.end();
             ++i
             ) {
            p = query(tokens, i->from);
            if (
                deque.empty()
                || p - q > (now - 1)->interval_from
                && p - q - 1 <= (now - 1)->interval_to
                ) {
                deque.push_back(*i);
                dfs(now + 1, end, deque, groups, newCols, tokens, text);
                deque.pop_back();
            }
        }
    }
}
Example #10
0
Statman::Statman(uintptr_t start, Size_type num_bytes)
{
    if(num_bytes < 0)
        throw Stats_exception{"Creating Statman: A negative number of bytes has been given"};

    Size_type num_stats_in_span = num_bytes / sizeof(Stat);

    num_bytes_ = sizeof(Stat) * num_stats_in_span;
    stats_ = Span(reinterpret_cast<Stat*>(start), num_stats_in_span);
}
Example #11
0
void
RasterCallback(const int y,
               const int count,
               const FT_Span * const spans,
               void * const user) 
{
	Spans *sptr = (Spans *)user;
	for (int i = 0; i < count; ++i) 
	  sptr->push_back(Span(spans[i].x, y, spans[i].len, spans[i].coverage));
}
Example #12
0
IPAddress IPAddress::Parse(RCString ipString) {
	uint8_t buf[16];
	if (CCheck(::inet_pton(AF_INET, ipString, buf)))
		return IPAddress(Span(buf, 4));
	if (CCheck(::inet_pton(AF_INET6, ipString, buf)))
		return IPAddress(Span(buf, 16));
	/*!!!R
#if UCFG_USE_REGEX
#	if UCFG_WIN32
	if (regex_search(ipString, *s_reDomainName)) {
#	else
	if (regex_search(ipString.c_str(), s_reDomainName)) {
#	endif
		IPAddress r;
		r.AddressFamily = Ext::AddressFamily(AF_DOMAIN_NAME);
		r.m_domainname = ipString;
		return r;
	}
#endif */
	Throw(HRESULT_FROM_WIN32(DNS_ERROR_INVALID_IP_ADDRESS));
}
Example #13
0
void CCurve::GetSpans(std::list<Span> &spans)const
{
	const Point *prev_p = NULL;
	for(std::list<CVertex>::const_iterator It = m_vertices.begin(); It != m_vertices.end(); It++)
	{
		const CVertex& vertex = *It;
		if(prev_p)
		{
			spans.push_back(Span(*prev_p, vertex));
		}
		prev_p = &(vertex.m_p);
	}
}
Example #14
0
size_t IPAddress::GetHashCode() const {
	size_t r = std::hash<uint16_t>()((uint16_t)get_AddressFamily());
	switch ((int)get_AddressFamily()) {
	case AF_INET:
		r += std::hash<uint32_t>()(*(uint32_t*)&m_sin.sin_addr);
		break;
	case AF_INET6:
		r += hash_value(Span((const uint8_t*)&m_sin6.sin6_addr, 16));
		break;
	default:
		Throw(ExtErr::UnknownHostAddressType);
	}
	return r;
}
Example #15
0
void CCurve::GetBox(CBox2D &box)
{
	Point prev_p = Point(0, 0);
	bool prev_p_valid = false;
	for(std::list<CVertex>::iterator It = m_vertices.begin(); It != m_vertices.end(); It++)
	{
		CVertex& vertex = *It;
		if(prev_p_valid)
		{
			Span(prev_p, vertex).GetBox(box);
		}
		prev_p = vertex.m_p;
		prev_p_valid = true;
	}
}
Example #16
0
void View::extract_regex(string regex,
                         vector<int> groups,
                         vector<string> column_names,
                         string text) {
    vector<vector<int> > result = findall(regex.c_str(), text.c_str());
    columns.clear();
    for (int col = 0; col < groups.size(); col++) {
        columns.push_back(Column(column_names[col]));
        for (int i = 0; i < result.size(); i++) {
            int from = result[i][groups[col]*2]
            ,to = result[i][groups[col]*2+1];
            columns[col].spans.push_back(Span(text.substr(from, to-from), from, to));
        }
    }
}
Example #17
0
int main()
{
    std::srand(time(0));
    Span sp = Span(10000);
    try
    {
        while (1)
            sp.addNumber(rand());
    }
    catch(std::exception &e)
    {
        std::cout	<< e.what() << std::endl;
    }
    std::cout << sp.shortestSpan() << std::endl;
    std::cout << sp.longestSpan() << std::endl;
}
Example #18
0
CIsect Plane::intersect(const Ray& ray)
{
	float angle = dot(mNormal, ray.getDir());
	if (fabs(angle) < FLOAT_ZERO) 
	{
		return CIsect(false);
	}
	float t = (-(dot(ray.getOrg(), mNormal) + mD) / angle);
	if (t > 0.f)
	{
		CIsect res(true, t, this, getNormal(ray, t));
		res.Dst.push_back(t);
		res.InsideIntervals.push_back(Span(t, t));
		return res;
	}
	return CIsect(false);
}
Example #19
0
double CCurve::GetArea()const
{
	double area = 0.0;
	Point prev_p = Point(0, 0);
	bool prev_p_valid = false;
	for(std::list<CVertex>::const_iterator It = m_vertices.begin(); It != m_vertices.end(); It++)
	{
		const CVertex& vertex = *It;
		if(prev_p_valid)
		{
			area += Span(prev_p, vertex).GetArea();
		}
		prev_p = vertex.m_p;
		prev_p_valid = true;
	}
	return area;
}
Example #20
0
void Table::GetValueRects(int zoom, Draw& w, int x, int& y, int cx, Vector<ValueRect>& vr)
const {
	int zfw = DocZoomLn(zoom, GetFrameWidth());
	int li = 0;
	cx -= 2 * zfw + DocZoom(zoom, GetLm()) + DocZoom(zoom, GetRm());
	y += zfw;
	while(li < GetRows()) {
		Vector<Line> line;
		int span = 0;
		for(;;) {
			int k = li + line.GetCount();
			if(k >= GetRows() || line.GetCount() && !KeepLine(k) && span <= 0)
				break;
			span = max((line.Add() = GetLine(zoom, k, cx, NULL)).span, span);
			span--;
		}
		y += Span(line);
		RectLines(zoom, w, x, y, li, line, vr);
		li += line.GetCount();
	}
	y += zfw;
}
Example #21
0
int  Table::GetHeight(int zoom, int cx) const {
	int cy = 0;
	int ln = 0;
	cx -= DocZoomLn(zoom, GetFrameWidth()) + DocZoomLn(zoom, GetFrameWidth()) +
		  DocZoom(zoom, GetLm()) + DocZoom(zoom, GetRm());
	cy += 2 * DocZoomLn(zoom, GetFrameWidth());
	while(ln < GetRows()) {
		Vector<Line> line;
		int span = 0;
		for(;;) {
			int k = ln + line.GetCount();
			if(ln + line.GetCount() >= GetRows() ||
			   line.GetCount() && !KeepLine(k) && span <= 0)
				break;
			span = max((line.Add() = GetLine(zoom, k, cx, NULL)).span, span);
			span--;
		}
		cy += Span(line);
		ln += line.GetCount();
	}
	return cy;
}
Example #22
0
bool Table::Paint(int zoom, Draw& w, int x, int y, int cx, int ymax, PaintInfo& pi) const {
	int j;
	Vector<Line> header;
	int zfw = DocZoomLn(zoom, GetFrameWidth());
	int tcx = cx - 2 * zfw - DocZoom(zoom, GetLm()) - DocZoom(zoom, GetRm());
	bool breakpage = pi.line != pi.oline;
	int  pgcy = ymax - y;
	pi.oline = pi.line;
	if(pi.line) {
		int m = min(GetHeaderRows(), cell.GetCount());
		for(j = 0; j < m; j++)
			header.Add() = GetLine(zoom, j, tcx, NULL);
	}
	int hdrcy = Span(header);
	if(hdrcy > ymax - y) {
		header.Clear();
		hdrcy = 0;
	}
	int hg = hdrcy;
	int yp = y;
	y += zfw;
	bool was = false;
	if(y >= ymax) {
		pi.ypos = y;
		return true;
	}
	while(pi.line < GetRows() && y < ymax) {
		Vector<Line> line;
		Vector<int> *yl = &pi.yl;
		int span = 0;
		bool nospan = true;
		for(;;) {
			int k = pi.line + line.GetCount();
			if(k >= GetRows() || line.GetCount() && !KeepLine(k) && span <= 0)
				break;
			span = max((line.Add() = GetLine(zoom, k, tcx, yl)).span, span);
			if(span) nospan = false;
			yl = NULL;
			span--;
		}
		hg += Span(line);
		int lhg = line.Top().height;
		if(hg + y + zfw > ymax) {
			if((!breakpage ||
				lhg > style.breakcy && ymax - (y + hg - lhg) - zfw > style.breakpgcy)
			   && nospan && line.GetCount() && hg + y + zfw - lhg <= ymax) {
				int yy = y + hdrcy;
				PaintLines(zoom, w, x, yy, 0, header, 0);
				yy = y + hdrcy;
				int i;
				for(i = 0; i < line.GetCount() - 1; i++) {
					DrawLine(zoom, w, x, yy, pi.line++, line[i], ymax, NULL);
					yy += line[i].height;
				}
				DrawLine(zoom, w, x, yy, pi.line, line[i], ymax, &pi.yl);
				breakpage = was = true;
				y = ymax;
			}
			if(breakpage) {
				FrameTab(zoom, w, was, x, y, yp, cx);
				pi.ypos = y;
				return true;
			}
		}
		y += hg;
		int yy = y;
		PaintLines(zoom, w, x, yy, pi.line, line, &pi.yl);
		PaintLines(zoom, w, x, yy, 0, header, 0);
		pi.yl.Clear();
		header.Clear();
		hg = 0;
		breakpage = was = true;
		pi.line += line.GetCount();
	}
	FrameTab(zoom, w, was, x, y, yp, cx);
	pi.ypos = y + zfw;
	return false;
}
Example #23
0
TypeRef Parse_Type_Int(TokenStream& lex, bool allow_trait_list)
{
    //TRACE_FUNCTION;
    auto ps = lex.start_span();

    Token tok;

    switch( GET_TOK(tok, lex) )
    {
    case TOK_INTERPOLATED_TYPE:
        return mv$(tok.frag_type());
    // '!' - Only ever used as part of function prototypes, but is kinda a type... not allowed here though
    case TOK_EXCLAM:
        return TypeRef( Span(tok.get_pos()), TypeData::make_Bang({}) );
    // '_' = Wildcard (type inferrence variable)
    case TOK_UNDERSCORE:
        return TypeRef(Span(tok.get_pos()));

    // 'unsafe' - An unsafe function type
    case TOK_RWORD_UNSAFE:
    // 'extern' - A function type with an ABI
    case TOK_RWORD_EXTERN:
    // 'fn' - Rust function
    case TOK_RWORD_FN:
        PUTBACK(tok, lex);
        return Parse_Type_Fn(lex);

    case TOK_RWORD_IMPL:
        return Parse_Type_ErasedType(lex, allow_trait_list);

    // '<' - An associated type cast
    case TOK_LT:
    case TOK_DOUBLE_LT: {
        PUTBACK(tok, lex);
        auto path = Parse_Path(lex, PATH_GENERIC_TYPE);
        return TypeRef(TypeRef::TagPath(), lex.end_span(mv$(ps)), mv$(path));
        }
    //
    case TOK_RWORD_FOR: {
        auto hrls = Parse_HRB(lex);
        switch(LOOK_AHEAD(lex))
        {
        case TOK_RWORD_UNSAFE:
        case TOK_RWORD_EXTERN:
        case TOK_RWORD_FN:
            return Parse_Type_Fn(lex, hrls);
        default:
            return Parse_Type_Path(lex, hrls, true);
        }
        }
    // <ident> - Either a primitive, or a path
    case TOK_IDENT:
        if( lex.lookahead(0) == TOK_EXCLAM )
        {
            lex.getToken();
            // TODO: path macros
            return TypeRef(TypeRef::TagMacro(), Parse_MacroInvocation(ps, mv$(tok.str()), lex));
        }
        // or a primitive
        //if( auto ct = coretype_fromstring(tok.str()) )
        //{
        //    return TypeRef(TypeRef::TagPrimitive(), Span(tok.get_pos()), ct);
        //}
        PUTBACK(tok, lex);
        return Parse_Type_Path(lex, {}, allow_trait_list);
        // - Fall through to path handling
    // '::' - Absolute path
    case TOK_DOUBLE_COLON:
    // 'self' - This relative path
    case TOK_RWORD_SELF:
    // 'super' - Parent relative path
    case TOK_RWORD_SUPER:
    // ':path' fragment
    case TOK_INTERPOLATED_PATH:
        PUTBACK(tok, lex);
        return Parse_Type_Path(lex, {}, allow_trait_list);

    // HACK! Convert && into & &
    case TOK_DOUBLE_AMP:
        lex.putback(Token(TOK_AMP));
    // '&' - Reference type
    case TOK_AMP: {
        AST::LifetimeRef lifetime;
        // Reference
        tok = lex.getToken();
        if( tok.type() == TOK_LIFETIME ) {
            lifetime = AST::LifetimeRef(/*lex.point_span(), */lex.get_ident(::std::move(tok)));
            tok = lex.getToken();
        }
        bool is_mut = false;
        if( tok.type() == TOK_RWORD_MUT ) {
            is_mut = true;
        }
        else {
            PUTBACK(tok, lex);
        }
        return TypeRef(TypeRef::TagReference(), lex.end_span(mv$(ps)), ::std::move(lifetime), is_mut, Parse_Type(lex, false));
        }
    // '*' - Raw pointer
    case TOK_STAR:
        // Pointer
        switch( GET_TOK(tok, lex) )
        {
        case TOK_RWORD_MUT:
            // Mutable pointer
            return TypeRef(TypeRef::TagPointer(), lex.end_span(mv$(ps)), true, Parse_Type(lex, false));
        case TOK_RWORD_CONST:
            // Immutable pointer
            return TypeRef(TypeRef::TagPointer(), lex.end_span(mv$(ps)), false, Parse_Type(lex, false));
        default:
            throw ParseError::Unexpected(lex, tok, {TOK_RWORD_CONST, TOK_RWORD_MUT});
        }
        throw ParseError::BugCheck("Reached end of Parse_Type:STAR");
    // '[' - Array type
    case TOK_SQUARE_OPEN: {
        // Array
        TypeRef inner = Parse_Type(lex);
        if( GET_TOK(tok, lex)  == TOK_SEMICOLON ) {
            // Sized array
            AST::Expr array_size = Parse_Expr(lex);
            GET_CHECK_TOK(tok, lex, TOK_SQUARE_CLOSE);
            return TypeRef(TypeRef::TagSizedArray(), lex.end_span(mv$(ps)), mv$(inner), array_size.take_node());
        }
        else if( tok.type() == TOK_SQUARE_CLOSE )
        {
            return TypeRef(TypeRef::TagUnsizedArray(), lex.end_span(mv$(ps)), mv$(inner));
        }
        else {
            throw ParseError::Unexpected(lex, tok/*, "; or ]"*/);
        }
        }

    // '(' - Tuple (or lifetime bounded trait)
    case TOK_PAREN_OPEN: {
        DEBUG("Tuple");
        if( GET_TOK(tok, lex) == TOK_PAREN_CLOSE )
            return TypeRef(TypeRef::TagTuple(), lex.end_span(mv$(ps)), {});
        PUTBACK(tok, lex);

        TypeRef inner = Parse_Type(lex, true);
        if( LOOK_AHEAD(lex) == TOK_PAREN_CLOSE )
        {
            // Type in parens, NOT a tuple
            GET_CHECK_TOK(tok, lex, TOK_PAREN_CLOSE);
            return inner;
        }
        else
        {
            ::std::vector<TypeRef>  types;
            types.push_back( mv$(inner) );
            while( GET_TOK(tok, lex) == TOK_COMMA )
            {
                if( GET_TOK(tok, lex) == TOK_PAREN_CLOSE )
                    break;
                else
                    PUTBACK(tok, lex);
                types.push_back( Parse_Type(lex) );
            }
            CHECK_TOK(tok, TOK_PAREN_CLOSE);
            return TypeRef(TypeRef::TagTuple(), lex.end_span(mv$(ps)), mv$(types)); }
        }
    default:
        throw ParseError::Unexpected(lex, tok);
    }
    throw ParseError::BugCheck("Reached end of Parse_Type");
}
Example #24
0
TypeRef Parse_Type_Fn(TokenStream& lex, ::AST::HigherRankedBounds hrbs)
{
    auto ps = lex.start_span();
    TRACE_FUNCTION;
    Token   tok;

    ::std::string   abi = "";
    bool    is_unsafe = false;

    GET_TOK(tok, lex);

    // `unsafe`
    if( tok.type() == TOK_RWORD_UNSAFE )
    {
        is_unsafe = true;
        GET_TOK(tok, lex);
    }
    // `exern`
    if( tok.type() == TOK_RWORD_EXTERN )
    {
        if( GET_TOK(tok, lex) == TOK_STRING ) {
            abi = tok.str();
            if( abi == "" )
                ERROR(lex.point_span(), E0000, "Empty ABI");
            GET_TOK(tok, lex);
        }
        else {
            abi = "C";
        }
    }
    // `fn`
    CHECK_TOK(tok, TOK_RWORD_FN);

    ::std::vector<TypeRef>  args;
    bool is_variadic = false;
    GET_CHECK_TOK(tok, lex, TOK_PAREN_OPEN);
    while( LOOK_AHEAD(lex) != TOK_PAREN_CLOSE )
    {
        if( LOOK_AHEAD(lex) == TOK_TRIPLE_DOT ) {
            GET_TOK(tok, lex);
            is_variadic = true;
            break;
        }
        // Handle `ident: `
        if( (lex.lookahead(0) == TOK_IDENT || lex.lookahead(0) == TOK_UNDERSCORE) && lex.lookahead(1) == TOK_COLON ) {
            GET_TOK(tok, lex);
            GET_TOK(tok, lex);
        }
        args.push_back( Parse_Type(lex) );
        if( GET_TOK(tok, lex) != TOK_COMMA ) {
            PUTBACK(tok, lex);
            break;
        }
    }
    GET_CHECK_TOK(tok, lex, TOK_PAREN_CLOSE);

    // `-> RetType`
    TypeRef ret_type = TypeRef(TypeRef::TagUnit(), Span(tok.get_pos()));
    if( GET_TOK(tok, lex) == TOK_THINARROW )
    {
        ret_type = Parse_Type(lex, false);
    }
    else {
        PUTBACK(tok, lex);
    }

    return TypeRef(TypeRef::TagFunction(), lex.end_span(mv$(ps)), mv$(hrbs), is_unsafe, mv$(abi), mv$(args), is_variadic, mv$(ret_type));
}
Example #25
0
 Span()
 {
     Span(0, 0);
 }
Example #26
0
File: Ui.hpp Project: mfichman/sfr
 static Span fill() { return Span(100, Span::PERCENT); }
Example #27
0
void Expand_TestHarness(::AST::Crate& crate)
{
    // Create the following module:
    // ```
    // mod `#test` {
    //   extern crate std;
    //   extern crate test;
    //   fn main() {
    //     self::test::test_main_static(&::`#test`::TESTS);
    //   }
    //   static TESTS: [test::TestDescAndFn; _] = [
    //     test::TestDescAndFn { desc: test::TestDesc { name: "foo", ignore: false, should_panic: test::ShouldPanic::No }, testfn: ::path::to::foo },
    //     ];
    // }
    // ```

    // ---- main function ----
    auto main_fn = ::AST::Function { Span(), {}, ABI_RUST, false, false, false, TypeRef(TypeRef::TagUnit(), Span()), {} };
    {
        auto call_node = NEWNODE(_CallPath,
                ::AST::Path("test", { ::AST::PathNode("test_main_static") }),
                ::make_vec1(
                    NEWNODE(_UniOp, ::AST::ExprNode_UniOp::REF,
                        NEWNODE(_NamedValue, ::AST::Path("", { ::AST::PathNode("test#"), ::AST::PathNode("TESTS") }))
                        )
                    )
                );
        main_fn.set_code( mv$(call_node) );
    }


    // ---- test list ----
    ::std::vector< ::AST::ExprNodeP>    test_nodes;

    for(const auto& test : crate.m_tests)
    {
        // HACK: Don't emit should_panic tests
        if( test.panic_type != ::AST::TestDesc::ShouldPanic::No )
            continue ;

        ::AST::ExprNode_StructLiteral::t_values   desc_vals;
        // `name: "foo",`
        desc_vals.push_back({ {}, "name", NEWNODE(_CallPath,
                        ::AST::Path("test", { ::AST::PathNode("StaticTestName") }),
                        ::make_vec1( NEWNODE(_String,  test.name) )
                        ) });
        // `ignore: false,`
        desc_vals.push_back({ {}, "ignore", NEWNODE(_Bool,  test.ignore) });
        // `should_panic: ShouldPanic::No,`
        {
            ::AST::ExprNodeP    should_panic_val;
            switch(test.panic_type)
            {
            case ::AST::TestDesc::ShouldPanic::No:
                should_panic_val = NEWNODE(_NamedValue,  ::AST::Path("test", { ::AST::PathNode("ShouldPanic"), ::AST::PathNode("No") }));
                break;
            case ::AST::TestDesc::ShouldPanic::Yes:
                should_panic_val = NEWNODE(_NamedValue,  ::AST::Path("test", { ::AST::PathNode("ShouldPanic"), ::AST::PathNode("Yes") }));
                break;
            case ::AST::TestDesc::ShouldPanic::YesWithMessage:
                should_panic_val = NEWNODE(_CallPath,
                        ::AST::Path("test", { ::AST::PathNode("ShouldPanic"), ::AST::PathNode("YesWithMessage") }),
                        make_vec1( NEWNODE(_String, test.expected_panic_message) )
                        );
                break;
            }
            desc_vals.push_back({ {}, "should_panic", mv$(should_panic_val) });
        }
        auto desc_expr = NEWNODE(_StructLiteral,  ::AST::Path("test", { ::AST::PathNode("TestDesc")}), nullptr, mv$(desc_vals));

        ::AST::ExprNode_StructLiteral::t_values   descandfn_vals;
        descandfn_vals.push_back({ {}, ::std::string("desc"), mv$(desc_expr) });

        auto test_type_var_name  = test.is_benchmark ? "StaticBenchFn" : "StaticTestFn";
        descandfn_vals.push_back({ {}, ::std::string("testfn"), NEWNODE(_CallPath,
                        ::AST::Path("test", { ::AST::PathNode(test_type_var_name) }),
                        ::make_vec1( NEWNODE(_NamedValue, AST::Path(test.path)) )
                        ) });

        test_nodes.push_back( NEWNODE(_StructLiteral,  ::AST::Path("test", { ::AST::PathNode("TestDescAndFn")}), nullptr, mv$(descandfn_vals) ) );
    }
    auto* tests_array = new ::AST::ExprNode_Array(mv$(test_nodes));

    size_t test_count = tests_array->m_values.size();
    auto tests_list = ::AST::Static { ::AST::Static::Class::STATIC,
        TypeRef(TypeRef::TagSizedArray(), Span(),
                TypeRef(Span(), ::AST::Path("test", { ::AST::PathNode("TestDescAndFn") })),
                ::std::shared_ptr<::AST::ExprNode>( new ::AST::ExprNode_Integer(test_count, CORETYPE_UINT) )
               ),
        ::AST::Expr( mv$(tests_array) )
        };

    // ---- module ----
    auto newmod = ::AST::Module { ::AST::Path("", { ::AST::PathNode("test#") }) };
    // - TODO: These need to be loaded too.
    //  > They don't actually need to exist here, just be loaded (and use absolute paths)
    newmod.add_ext_crate(false, "std", "std", {});
    newmod.add_ext_crate(false, "test", "test", {});

    newmod.add_item(false, "main", mv$(main_fn), {});
    newmod.add_item(false, "TESTS", mv$(tests_list), {});

    crate.m_root_module.add_item(false, "test#", mv$(newmod), {});
    crate.m_lang_items["mrustc-main"] = ::AST::Path("", { AST::PathNode("test#"), AST::PathNode("main") });
}
Example #28
0
CIsect Cylinder::intersect(const Ray& ray)
{
  const Vec3D& origin    = ray.getOrg();
  const Vec3D& direction = ray.getDir();

	const Vec3D& CO = origin - mBottom;
	
	const Vec3D& u = direction - mAxis * (dot(direction, mAxis));
	const Vec3D& v = CO - mAxis * (dot(CO, mAxis));

	CIsect res = CIsect(true);
	// Let a, b and c be coefficients of some square equation
	const float a = dot(u, u);
	float root		= 0.f;
	float closest = -1.f;
	float rayExit = -1.f;
	if (fabs(a) > FLOAT_ZERO)
	{
		const float b = 2 * dot(u, v);
		const float c = dot(v, v) - mRadius2;

		float D = b * b - 4 * a * c;

		// Complete miss
		if (D < 0.f) 
		{
			return CIsect(false);
		}

		D = sqrtf(D);

		// Calculate roots and take closest
		float denom = 1 / (2 * a);

		root = (-b - D) * denom;
		if (root >= 0.f)
		{
			Vec3D toBottom = ray.apply(root) - mBottom;
			Vec3D toTop		= ray.apply(root) - mTop;
			if (dot(mAxis, toBottom) > 0.f && dot(mAxis, toTop) < 0.f)
			{
				res.Dst.push_back(root);
				closest = root;
			}
		}
		root = (-b + D) * denom;
		if (root > 0.f)
		{
			// Awful copy paste :(
			Vec3D toBottom = ray.apply(root) - mBottom;
			Vec3D toTop		= ray.apply(root) - mTop;
			if (dot(mAxis, toBottom) > 0.f && dot(mAxis, toTop) < 0.f)
			{
				res.Dst.push_back(root);
				if (closest < 0.f)
				{
					root = closest;
				}
				else if (root < closest)
				{
					rayExit = closest;
					closest = root;
				}
				else
				{
					rayExit = root;
				}
			}
		}
	}
	
	// dot(va, (q - p1)) = 0   t = (dot(va, p1) - dot(va, p)) / dot(va, v)

	// Find intersection with caps
	// Bottom one
	float axisToDir = dot(mAxis, direction);

	if (fabs(axisToDir) < FLOAT_ZERO)
	{
		if (closest > 0.f)
		{
			res.Distance = closest;
			res.Object   = this;
			res.Normal	 = getNormal(ray, closest);
			if (rayExit < 0.f) 
			{
				res.InsideIntervals.push_back(Span(0.f, closest));
				res.Dst.insert(res.Dst.begin(), 0.f);
			}
			else
			{
				res.InsideIntervals.push_back(Span(closest, rayExit));
			}
			return res;
		}

		return CIsect(false);
	}

	float axisToOrg		= dot(mAxis, origin);
	//root = (dot(mAxis, mBottom) - axisToOrg) / axisToDir;
	float CODotAxis = dot(CO, mAxis);
	root = -CODotAxis / axisToDir;
	if (root > 0.f)
	{
		Vec3D toBottom = ray.apply(root) - mBottom;
		if (dot(toBottom, toBottom) < mRadius2)
		{
			res.Dst.push_back(root);
			// Awful copy paste :(
			if (closest < 0.f)
			{
				closest = root;
			}
			else if (root < closest)
			{
				rayExit = closest;
				closest = root;
			}
			else
			{
				rayExit = root;
			}
		}
	}
	// Top one
	//root = (dot(mAxis, mTop) - axisToOrg) / axisToDir;
	float CTDotAxis = dot(origin - mTop, -mAxis);
	root = CTDotAxis / axisToDir;
	if (root > 0.f)
	{
		// Awful copy paste :(
		Vec3D toTop = ray.apply(root) - mTop;
		if (dot(toTop, toTop) < mRadius2)
		{
			res.Dst.push_back(root);
			if (closest < 0.f)
			{
				closest = root;
			}
			else if (root < closest)
			{
				rayExit = closest;
				closest = root;
			}
			else
			{
				rayExit = root;
			}
		}
	}
	
	if (closest >= 0.f)
	{
		res.Distance = closest;
		res.Object   = this;
		res.Normal	 = getNormal(ray, closest);
		if (rayExit < 0.f) 
		{
			res.InsideIntervals.push_back(Span(0.f, closest));
			res.Dst.insert(res.Dst.begin(), 0.f);
		}
		else
		{
			res.InsideIntervals.push_back(Span(closest, rayExit));
		}
		return res;
	}
  return CIsect(false);
}
Example #29
0
int KBlocksAIPlanner::process(KBlocks_PieceType_Detail pieceValue)
{
    // board size
    int w = mpField->getWidth();
    int h = mpField->getHeight();
    // piece bound
    Spans p_Col_Height = Spans(w);
    // board rect
    Lines b_Col_maxHeight = Lines(w);

    // board info - max height per column
    for (int x = 0; x < w; x++) {
        int y = 0;
        for (y = 0; y < h; y++) {
            if (mpField->getCell(x, y)) {
                break;
            }
        }
        b_Col_maxHeight[x] = y;
    }

    // init next_states list
    mNextPieceValues.clear();

    // init piece state
    KBlocksPiece piece;
    piece.fromValue(pieceValue);

    int loopCount = piece.getRotationCount();
    // scan all possible rotation
    for (int rotation = 0; rotation < loopCount; rotation++) {
        // piece info - min/max height per column
        piece.setRotation(rotation);

        // scan all possible x position - put piece on board
        for (int x = 0; x < w; x++) {
            bool invalidPos = false;
            piece.setPosX(x);
            piece.setPosY(0);

            // init
            for (int i = 0; i < w; i++) {
                p_Col_Height[i] = Span(h, -1);
            }
            for (int i = 0; i < KBlocksPiece_CellCount; i++) {
                int cx = piece.getCellPosX(i);
                int cy = piece.getCellPosY(i);
                if (mpField->getCell(cx, cy)) {
                    invalidPos = true;
                    break;
                }
                if (p_Col_Height[cx].min > cy) {
                    p_Col_Height[cx].min = cy;
                }
                if (p_Col_Height[cx].max < cy) {
                    p_Col_Height[cx].max = cy;
                }
            }
            if (invalidPos) {
                continue;
            }

            // get response height
            int y = h;
            for (int px = 0; px < w; px++) {
                if (p_Col_Height[px].min == h) {
                    continue;
                }
                int dy = b_Col_maxHeight[px] - 1 - p_Col_Height[px].max;
                if (dy < y) {
                    y = dy;
                }
            }

            if ((y < 0) || (y >= h)) {
                continue;
            }

            // state
            piece.setPosY(y);
            // insert to list
            mNextPieceValues.push_back(piece);
        }
    }

    return (int)(mNextPieceValues.size());
}
Example #30
0
const Span State::span() const {
	return Span(_frontier);
}