Example #1
0
    public virtual Algebraic divExponential(Algebraic x, FunctionVariable fv, int n)
    {
        var a = new Algebraic[2];

        a[1] = x;

        Algebraic xk = Zahl.ZERO;

        for (int i = n; i >= 0; i--)
        {
            var kf = FunctionVariable.create("exp", fv.arg).pow_n(i);

            a[0] = a[1];
            a[1] = kf;

            Poly.polydiv(a, fv);

            if (!a[0].Equals(Zahl.ZERO))
            {
                var kfi = FunctionVariable.create("exp", fv.arg.mult(Zahl.MINUS)).pow_n(n - i);

                xk = xk.add(a[0].mult(kfi));
            }

            if (a[1].Equals(Zahl.ZERO))
            {
                break;
            }
        }

        return(f_exakt(xk));
    }
Example #2
0
    public override int Eval(Stack st)
    {
        int narg = GetNarg(st);

        var dgl = GetAlgebraic(st);
        var y   = GetVariable(st);
        var x   = GetVariable(st);

        var p = Poly.Coefficient(dgl, y, 1);
        var q = Poly.Coefficient(dgl, y, 0);

        var pi = LambdaINTEGRATE.Integrate(p, x);

        if (pi is Rational && !pi.IsNumber())
        {
            pi = (new LambdaRAT()).SymEval(pi);
        }

        Variable vexp = new FunctionVariable("exp", pi, new LambdaEXP());

        Algebraic dn = new Polynomial(vexp);

        var qi = LambdaINTEGRATE.Integrate(q / dn, x);

        if (qi is Rational && !qi.IsNumber())
        {
            qi = (new LambdaRAT()).SymEval(qi);
        }

        Algebraic cn = new Polynomial(new SimpleVariable("C"));

        var res = (qi + cn) * dn;

        res = (new ExpandUser()).SymEval(res);

        Debug("User Function expand: " + res);

        res = (new TrigExpand()).SymEval(res);

        Debug("Trigexpand: " + res);

        res = (new NormExp()).SymEval(res);

        Debug("Norm: " + res);

        if (res is Rational)
        {
            res = (new LambdaRAT()).SymEval(res);
        }

        res = (new TrigInverseExpand()).SymEval(res);

        Debug("Triginverse: " + res);

        res = (new SqrtExpand()).SymEval(res);

        st.Push(res);

        return(0);
    }
Example #3
0
    public virtual Algebraic divExponential(Algebraic x, FunctionVariable fv, int n)
    {
        var a = new Algebraic[2];

        a[1] = x;

        Algebraic xk = Symbolic.ZERO;

        for (int i = n; i >= 0; i--)
        {
            var kf = FunctionVariable.Create("exp", fv.Var).Pow(i);

            a[0] = a[1];
            a[1] = kf;

            Poly.polydiv(a, fv);

            if (!a[0].Equals(Symbolic.ZERO))
            {
                var kfi = FunctionVariable.Create("exp", -fv.Var) ^ (n - i);

                xk = xk + a[0] * kfi;
            }

            if (Equals(a[1], Symbolic.ZERO))
            {
                break;
            }
        }

        return(SymEval(xk));
    }
Example #4
0
        //QRコードから読み取ったデータをPuzzle型に変換する.
        public Puzzle ReadFromQRCode(Procon2017MCTProtocol.QRCodeData QRCode)
        {
            Puzzle puzzle = new Puzzle(new List <Poly>(), new List <Poly>(), new List <Line>());
            int    i, j;

            //枠
            for (i = 0; i < QRCode.Frames.Count; i++)
            {
                puzzle.wakus.Add(Poly.ParsePolyFromQRCode(QRCode.Frames[i], false, -1));
            }

            //ピース
            for (i = 0; i < QRCode.Polygons.Count; i++)
            {
                puzzle.pieces.Add(Poly.ParsePolyFromQRCode(QRCode.Polygons[i], true, (sbyte)i));
            }

            //枠辺
            for (i = 0; i < puzzle.wakus.Count; i++)
            {
                for (j = 0; j < puzzle.wakus[i].Count; j++)
                {
                    puzzle.wakuLines.Add(new Line(puzzle.wakus[i].points[j], puzzle.wakus[i].points[j + 1], -1));
                }
            }

            //初期ピース数, 盤面評価値, 盤面ハッシュ
            puzzle.setInitPieceNum(puzzle.pieces.Count);
            puzzle.setBoardScore(0);
            puzzle.setBoardHash();
            return(puzzle);
        }
Example #5
0
        public static void TestParsePoly(string p)
        {
            Poly poly = new Poly();

            poly.ParsePoly(p);
            Console.WriteLine("Test ParsePoly");
            foreach (var c in poly.Coefficients)
            {
                Console.WriteLine(c.Value + " :: x^" + c.Key);
            }

            poly.FindInterval();
            for (int i = 0; i < 500; i++)
            {
                poly.ComputeHalley();
            }

            foreach (var x in poly.roots)
            {
                System.Console.WriteLine(x.Value);
            }

            //Test write in file
            //poly.WriteSolutionInFile("test1");
        }
Example #6
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static Algebraic remove_constant(Algebraic expr, Variable x)throws JasymcaException
    internal static Algebraic remove_constant(Algebraic expr, Variable x)
    {
        if (!expr.depends(x))
        {
            return(Zahl.ZERO);
        }
        if (expr is Polynomial)
        {
            ((Polynomial)expr).a[0] = remove_constant(((Polynomial)expr).a[0], x);
            return(expr);
        }
        if (expr is Rational)
        {
            Polynomial den = ((Rational)expr).den;
            Algebraic  nom = ((Rational)expr).nom;
            if (!den.depends(x))
            {
                return(remove_constant(nom, x).div(den));
            }
            if (nom is Polynomial)
            {
                Algebraic[] a = new Algebraic[] { nom, den };
                Poly.polydiv(a, den.v);
                if (!a[0].depends(x))
                {
                    return(a[1].div(den));
                }
            }
        }
        return(expr);
    }
Example #7
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public Algebraic integrate(Variable var) throws JasymcaException
    public override Algebraic integrate(Variable @var)
    {
        if (!den.depends(@var))
        {
            return(nom.integrate(@var).div(den));
        }
        Algebraic quot = den.deriv(@var).div(nom);

        if (quot.deriv(@var).Equals(Zahl.ZERO))
        {
            return(FunctionVariable.create("log", den).div(quot));
        }
        Algebraic[] q = new Algebraic[] { nom, den };
        Poly.polydiv(q, @var);
        if (!q[0].Equals(Zahl.ZERO) && nom.ratfunc(@var) && den.ratfunc(@var))
        {
            return(q[0].integrate(@var).add(q[1].div(den).integrate(@var)));
        }
        if (ratfunc(@var))
        {
            Algebraic r = Zahl.ZERO;
            Vektor    h = horowitz(nom, den, @var);
            if (h.get(0) is Rational)
            {
                r = r.add(h.get(0));
            }
            if (h.get(1) is Rational)
            {
                r = r.add((new TrigInverseExpand()).f_exakt(((Rational)h.get(1)).intrat(@var)));
            }
            return(r);
        }
        throw new JasymcaException("Could not integrate Function " + this);
    }
        public void All()
        {
            var x = Poly.All().Skip(1000).First();
            var s = Poly.ToString(x);

            Assert.AreEqual("−1 + 2𝑛 + 𝑛⁴", s);
        }
Example #9
0
        public void PolyMultiTest()
        {
            RandomNumberGenerator rng = new RandomNumberGenerator();

            byte[] iv   = rng.Generate(16);
            byte[] key  = rng.Generate(32);
            byte[] data = rng.Generate(100);

            Poly pmac = new Poly(Common.AesFactory);

            pmac.Init(key, iv, 16);
            pmac.Process(new ArraySegment <byte>(data));
            byte[] mac1 = pmac.Compute();

            pmac = new Poly(Common.AesFactory);
            pmac.Init(key, iv, 16);
            pmac.Process(new ArraySegment <byte>(data, 0, 50));
            pmac.Process(new ArraySegment <byte>(data, 50, 50));
            byte[] mac2 = pmac.Compute();

            pmac = new Poly(Common.AesFactory);
            pmac.Init(key, iv, 16);
            pmac.Process(new ArraySegment <byte>(data, 0, 33));
            pmac.Process(new ArraySegment <byte>(data, 33, 33));
            pmac.Process(new ArraySegment <byte>(data, 66, 34));
            byte[] mac3 = pmac.Compute();

            Assert.Equal(mac1, mac2);
            Assert.Equal(mac1, mac3);
        }
Example #10
0
        public class Tria : Poly { }            // Производный класс

        static void TestAsIs()
        {
            Console.Clear();

            Tria tria  = new Tria();
            Poly poly1 = new Poly(),
                 poly2 = tria;                          // poly2 ссылается на объект производного класса

            Console.WriteLine("\t\tTest 'as' operator");

            Poly p = poly1 as Poly;
            Tria t = poly1 as Tria;             // poly1 ссылается на объект базового класса

            Console.Write(
                "\npoly1 " + (p != null ? "is" : "is not") + " a Poly" +
                "\npoly1 " + (t != null ? "is" : "is not") + " a Tria");

            p = poly2 as Poly;
            t = poly2 as Tria;
            Console.Write(
                "\npoly2 " + (p != null ? "is" : "is not") + " a Poly" +
                "\npoly2 " + (t != null ? "is" : "is not") + " a Tria");

            Console.WriteLine("\n\n\t\tTest 'is' operator");
            Console.Write(
                "\npoly1 " + (poly1 is Poly ? "is" : "is not") + " a Poly" +
                "\npoly1 " + (poly1 is Tria ? "is" : "is not") + " a Tria" +
                "\npoly2 " + (poly2 is Poly ? "is" : "is not") + " a Poly" +
                "\npoly2 " + (poly2 is Tria ? "is" : "is not") + " a Tria");

            Console.WriteLine("\n\t\tPress any key to go to main menu\n");
            Console.ReadKey(true);
        }
 /// <summary>
 /// Clamps the edges of all <see cref="shapes"/> to fit within the provided bounds.
 /// </summary>
 /// <param name="bounds">The greater bounds.</param>
 public void ConfineToBounds(Poly bounds)
 {
     foreach (Poly p in polys)
     {
         p.ClampShapeToShape(bounds);
     }
 }
Example #12
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public Algebraic add(Algebraic p) throws JasymcaException
    public override Algebraic add(Algebraic p)
    {
        if (p is Rational)
        {
            return(p.add(this));
        }
        if (p is Polynomial)
        {
            if (v.Equals(((Polynomial)p).v))
            {
                int         len  = Math.Max(a.Length, ((Polynomial)p).a.Length);
                Algebraic[] csum = new Algebraic[len];
                for (int i = 0; i < len; i++)
                {
                    csum[i] = coefficient(i).add(((Polynomial)p).coefficient(i));
                }
                return((new Polynomial(v, csum)).reduce());
            }
            else if (v.smaller(((Polynomial)p).v))
            {
                return(p.add(this));
            }
        }
        Algebraic[] _csum = Poly.clone(a);
        _csum[0] = a[0].add(p);
        return((new Polynomial(v, _csum)).reduce());
    }
Example #13
0
        /// <summary>
        /// Find the distance from a point to a triangle.
        /// </summary>
        /// <param name="tile">Current mesh tile</param>
        /// <param name="indexPoly">Current polygon's index</param>
        /// <param name="pos">Current position</param>
        /// <param name="h">Resulting height</param>
        /// <returns>True, if a height is found. False, if otherwise.</returns>
        public static bool ClosestHeight(MeshTile tile, int indexPoly, Vector3 pos, out float h)
        {
            Poly poly = tile.Polys[indexPoly];

            PolyMeshDetail.MeshData pd = tile.DetailMeshes[indexPoly];

            //find height at the location
            for (int j = 0; j < tile.DetailMeshes[indexPoly].TriangleCount; j++)
            {
                PolyMeshDetail.TriangleData t = tile.DetailTris[pd.TriangleIndex + j];
                Vector3[] v = new Vector3[3];

                for (int k = 0; k < 3; k++)
                {
                    if (t[k] < poly.VertCount)
                    {
                        v[k] = tile.Verts[poly.Verts[t[k]]];
                    }
                    else
                    {
                        v[k] = tile.DetailVerts[pd.VertexIndex + (t[k] - poly.VertCount)];
                    }
                }

                if (Distance.PointToTriangle(pos, v[0], v[1], v[2], out h))
                {
                    return(true);
                }
            }

            h = float.MaxValue;
            return(false);
        }
Example #14
0
        /// <summary>
        /// The calculate method.
        /// </summary>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <param name="numEcc">
        /// The number of <c>ecc</c> codes.
        /// </param>
        /// <returns>
        /// The <see cref="byte"/> array.
        /// </returns>
        public byte[] Calculate(Poly message, int numEcc)
        {
            // Get message poly coefficients
            int[] messageCoefficients = new int[message.Terms.Length];

            for (int i = 0; i < message.Terms.Length; i++)
            {
                messageCoefficients[i] = message.Terms[i].Coefficient;
            }

            // Convert message poly coefficients into Galois Field (get a coefficients from numbers)
            QrGaloisFieldPoly info = new QrGaloisFieldPoly(this.field, messageCoefficients);

            // Increase level of the poly by number of ECC
            info = info.MultiplyByMonomial(numEcc, 1);

            // Get generator poly
            QrGaloisFieldPoly generatorPoly = this.BuildGeneratorPolynomial(numEcc);

            // Divite by generator poly
            QrGaloisFieldPoly remainder = info.Divide(generatorPoly)[1];

            // Return remainder coefficients in bytes
            int[] coefficients = remainder.GetCoefficients();

            byte[] eccCodes = new byte[coefficients.Length];

            for (int i = 0; i < coefficients.Length; i++)
            {
                eccCodes[i] = Convert.ToByte(coefficients[i]);
            }

            return(eccCodes);
        }
        //類似度計算2
        //アルゴリズム:
        //poly1とpoly2を「面積が1」になるように拡大・縮小する。
        //周の長さl1, l2をそれぞれ求める。
        //Abs(Log(l1 / l2))を返す。
        private double EvalSumLengthLog(Poly poly1, Poly poly2)
        {
            if (Math.Abs(poly1.Area) < 1e-9 || Math.Abs(poly2.Area) < 1e-9)
            {
                return(1145141919);
            }

            Scaling(poly1, 1.0 / Math.Sqrt(Math.Abs(poly1.Area)));
            Scaling(poly2, 1.0 / Math.Sqrt(Math.Abs(poly2.Area)));
            FixPoly(poly1, 0.01);
            FixPoly(poly2, 0.01);

            int    i;
            double sumLength1 = 0;
            double sumLength2 = 0;

            for (i = 0; i < poly1.Count; i++)
            {
                sumLength1 += (poly1[i + 1] - poly1[i]).Abs;
            }
            for (i = 0; i < poly2.Count; i++)
            {
                sumLength2 += (poly2[i + 1] - poly2[i]).Abs;
            }
            if (sumLength1 < 1e-9 || sumLength2 < 1e-9)
            {
                return(1145141919);
            }
            return(Math.Abs(Math.Log(sumLength1 / sumLength2)));
        }
Example #16
0
        private void ComputeBtn_Click(object sender, EventArgs e)
        {
            poly = new Poly();
            try
            {
                poly.ParsePoly(PolyInput.Text);

                poly.FindInterval();
                IntervalOutput.ResetText();
                IntervalOutput.Text = " [ " + poly.interval.Item1 + ", " + poly.interval.Item2 + " ]";

                for (int i = 0; i < 500; i++)
                {
                    poly.ComputeHalley();
                }

                RootsOutput.ResetText();
                foreach (var r in poly.roots)
                {
                    RootsOutput.Text += r.Value.ToString() + '\n';
                }
            }
            catch
            {
                MessageBox.Show("Input is not valid!");
            }
        }
Example #17
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public Algebraic[] square_free_dec(Variable var) throws JasymcaException
    public virtual Algebraic[] square_free_dec(Variable @var)
    {
        if (!ratfunc(@var))
        {
            return(null);
        }
        Algebraic dp      = deriv(@var);
        Algebraic gcd_pdp = Poly.poly_gcd(this, dp);
        Algebraic q       = Poly.polydiv(this, gcd_pdp);
        Algebraic p1      = Poly.polydiv(q, Poly.poly_gcd(q, gcd_pdp));

        if (gcd_pdp is Polynomial && gcd_pdp.depends(@var) && ((Polynomial)gcd_pdp).ratfunc(@var))
        {
            Algebraic[] sq     = ((Polynomial)gcd_pdp).square_free_dec(@var);
            Algebraic[] result = new Algebraic[sq.Length + 1];
            result[0] = p1;
            for (int i = 0; i < sq.Length; i++)
            {
                result[i + 1] = sq[i];
            }
            return(result);
        }
        else
        {
            Algebraic[] result = new Algebraic[] { p1 };
            return(result);
        }
    }
Example #18
0
        public bool IsInsideViewportPoints(Vector2 startPoint, Vector2 endPoint, ISelectable selectable)
        {
            Vector2[] area     = Poly.GetDefaultQuadrilateral(startPoint, endPoint);
            Vector2   position = Camera.main.WorldToViewportPoint(selectable.Position);

            return(Poly.ContainsPoint(area, position));
        }
Example #19
0
        /// <summary>
        /// 获取指定缴费项的缴费策略
        /// </summary>
        /// <param name="ItemID">缴费项</param>
        /// <returns></returns>
        public List <Poly> GetPolyListByItemID(string ItemID)
        {
            List <Poly> polyList = new List <Poly>();
            string      strSql   = "select ID,UnitPrice,LowerBound,HignerBound from T_Poly where ItemID=@ItemID";

            using (DBHelper db = DBHelper.Create())
            {
                Dictionary <string, object> paramList = new Dictionary <string, object>();
                paramList.Add("ItemID", ItemID);
                //polyList=db.GetList<Poly>(" and ItemID=@ItemID ", paramList, "", "");
                using (System.Data.Common.DbDataReader ddr = db.ExecuteReader(strSql, paramList))
                {
                    while (ddr != null && ddr.Read())
                    {
                        Poly p = new Poly();
                        p.ID          = ddr["ID"].ToString();
                        p.UnitPrice   = Convert.ToDecimal(ddr["UnitPrice"]);
                        p.LowerBound  = Convert.ToInt32(ddr["LowerBound"]);
                        p.HignerBound = Convert.ToInt32(ddr["HignerBound"]);
                        polyList.Add(p);
                    }
                }
            }
            return(polyList);
        }
    /// <summary>
    /// Clamps the entire bounds of this shape to the bounds of the given shape.
    /// </summary>
    /// <param name="other">The shape to clamp to.</param>
    public void ClampShapeToShape(Poly other)
    {
        Vector2[] extents     = other.borders;
        bool      sizeChanged = false;

        for (int i = 0; i < points.Length; i++)
        {
            // If any end point is not contained in the target shape, clamp it to that shape.
            if (!other.ContainsPoint(pointsWorldSpace[i]))
            {
                Vector3 clamp  = other.ClampPointToShape(new Vector3(pointsWorldSpace[i].x, 0, pointsWorldSpace[i].y));
                Vector2 newPos = new Vector2(clamp.x, clamp.z);

                // We need to update the local space points as well!
                points[i]          -= (pointsWorldSpace[i] - newPos);
                pointsWorldSpace[i] = newPos;

                sizeChanged = true;
            }
        }

        // Center and borders may have changed.
        if (sizeChanged)
        {
            FindCenter();
            SetBorders();
        }
    }
Example #21
0
 /// <summary>
 /// 增加一条数据
 /// </summary>
 public void Add(Poly model)
 {
     using (DBHelper db = DBHelper.Create())
     {
         db.Insert <Poly>(model);
     }
 }
Example #22
0
        public void PolyReferenceTests(byte[] key, byte[] iv, byte[] data, byte[] expected)
        {
            Poly pmac = new Poly(Common.AesFactory);

            pmac.Init(key, iv, 16);
            pmac.Process(new ArraySegment <byte>(data));
            byte[] mac = pmac.Compute();

            var bcpoly = new Poly1305(new AesEngine());

            bcpoly.Init(new ParametersWithIV(new KeyParameter(key), iv));
            bcpoly.BlockUpdate(data, 0, data.Length);
            byte[] bcmac = new byte[bcpoly.GetMacSize()];
            bcpoly.DoFinal(bcmac, 0);

            var _key      = string.Join(", ", key.Select(b => $"0x{b:x2}"));
            var _iv       = string.Join(", ", iv.Select(b => $"0x{b:x2}"));
            var _data     = string.Join(", ", data.Select(b => $"0x{b:x2}"));
            var _expected = string.Join(", ", bcmac.Select(b => $"0x{b:x2}"));

            Log.Verbose($"[InlineData(new byte[] {{{_key}}}, new byte[] {{{_iv}}}, new byte[] {{{_data}}}, new byte[] {{{_expected}}})]");

            Assert.Equal(expected, mac);
            Assert.Equal(expected, bcmac);
        }
Example #23
0
        public Extremum FindExtremumUniformForUnimodal(double[] poly, double start, double end, double delta)
        {
            double[] xs       = Range.Make(start, end, delta);
            Extremum extremum = new Extremum()
            {
                IsMin = true, X = start
            };

            Predicate <int> breakCondition = i => Poly.Val(poly, xs[i + 1])[0] >= Poly.Val(poly, xs[i])[0];

            if (breakCondition(0))
            {
                breakCondition = i => Poly.Val(poly, xs[i + 1])[0] <= Poly.Val(poly, xs[i])[0];
                extremum.IsMin = false;
            }

            for (int i = 0; i < xs.Length - 1; ++i)
            {
                if (breakCondition(i))
                {
                    extremum.X = xs[i] + delta / 2;
                    return(extremum);
                }
            }

            return(null);
        }
Example #24
0
        public static void DrawNavMesh()
        {
            NavMeshExporter.ExportNavMesh();

            NavMesh navMesh = NavMeshProcessor.GetNavMeshFromRawNavFile(EditorPaths.exportedRawNavMeshPath, false);

            Debug.Log("poly Count:" + navMesh.Polys.Count);
            NavMeshProcessor.WriteProcessedNavFile(navMesh, EditorPaths.processedNavMeshPath, false);

            HashSet <int> polyIndex = new HashSet <int>();

            foreach (HashSet <PolyConnection> connections in navMesh.NearPolys.Values)
            {
                foreach (PolyConnection connection in connections)
                {
                    if (!polyIndex.Contains(connection.A))
                    {
                        polyIndex.Add(connection.A);
                    }
                    if (!polyIndex.Contains(connection.B))
                    {
                        polyIndex.Add(connection.B);
                    }
                }
            }

            foreach (int i in polyIndex)
            {
                Poly poly = navMesh.Polys[i];
                foreach (GeoEdge edge in poly.Edges)
                {
                    Debug.DrawLine(edge.PointA, edge.PointB, new Color(30f / 255, 185f / 255, 246f / 255));
                }
            }
        }
Example #25
0
    public void spawner(Vector2 pos)
    {
        Poly newthing = Instantiate(polygon, pos, Quaternion.Euler(0, 0, 0)).GetComponent <Poly>();

        newthing.t_Rand();
        polys.Add(newthing);
    }
Example #26
0
    public Poly baseFinder()
    {
        Poly selectedPoly;

        for (int i = 0; i < polys.Count; i++)
        {
            if (polys[i].frontlineBase)
            {
                numStorer = i;
            }

            break;
        }
        Poly p = polys[numStorer];

        if (p.availablePolys.Count < 1)
        {
            return(null);
        }
        else if (p.availablePolys.Count > 0)
        {
            selectedPoly = p.availablePolys[0];
            p.availablePolys.Remove(p.availablePolys[0]);

            return(selectedPoly);
        }
        return(null);
    }
        /// <summary>
        /// Generate a straight skeleton for the given input
        /// </summary>
        /// <param name="outer">clockwise wound points indicating the outside of the shape</param>
        /// <param name="holes">clockwise wound points indicating the holes in the shape (or null, if there are no holes)</param>
        /// <returns></returns>
        public static StraightSkeleton Generate(IReadOnlyList <Vector2> outer, IReadOnlyList <IReadOnlyList <Vector2> > holes = null)
        {
            //sanity checks
            holes = SanityCheck(outer, holes);

            //Copy all the data into one big array (so we only need to fix one pointer, and just pass many offsets into it)
            var points = CopyData(outer, holes);

            //Variable to hold results
            Poly skeletonResult;
            Poly spokesResult;

            try
            {
                unsafe
                {
                    IntPtr handle;

                    //Fix a pointer to the start of the points array
                    fixed(Point2 *pointsPtr = &points[0])
                    {
                        //Outer polygon
                        var outerPoly = new Poly((float *)pointsPtr, outer.Count);

                        //Holes
                        var holePolys      = new Poly[holes.Count];
                        var holeStartIndex = outer.Count;

                        for (var i = 0; i < holes.Count; i++)
                        {
                            holePolys[i]    = new Poly((float *)(&pointsPtr[holeStartIndex]), holes[i].Count);
                            holeStartIndex += holes[i].Count;
                        }

                        //Generate skeleton
                        if (holePolys.Length > 0)
                        {
                            fixed(Poly *holesPtr = &holePolys[0])
                            handle = new IntPtr(GenerateStraightSkeleton(&outerPoly, holesPtr, holes.Count, &skeletonResult, &spokesResult));
                        }
                        else
                        {
                            handle = new IntPtr(GenerateStraightSkeleton(&outerPoly, null, 0, &skeletonResult, &spokesResult));
                        }
                    }

                    return(ExtractResult(outer, holes, &skeletonResult, &spokesResult, handle));
                }
            }
            finally
            {
                unsafe
                {
                    //We allocate memory in the Result struct (in C++) to store the result data, call this to free up that memory
                    FreePolygonStructMembers(&skeletonResult);
                    FreePolygonStructMembers(&spokesResult);
                }
            }
        }
Example #28
0
 /// <summary>
 /// 更新一条数据
 /// </summary>
 public bool Update(Poly model)
 {
     using (DBHelper db = DBHelper.Create())
     {
         db.Update <Poly>(model);
         return(true);
     }
 }
Example #29
0
                public override bool more_aggregatep(Poly pr)
                {
                    Fill fpr = (Fill)pr;

                    return(coordinate_mode == Drawable.ORIGIN &&
                           fpr.coordinate_mode == Drawable.ORIGIN &&
                           fpr.shape == shape);
                }
Example #30
0
    private static string Strings(int id)
    {
        Dictionary <int, string> hashTbl;

        if ((hashTbl = AppDomain.CurrentDomain.GetData("PADDINGPADDINGPADDING") as Dictionary <int, string>) == null)
        {
            AppDomain.CurrentDomain.SetData("PADDINGPADDINGPADDING", hashTbl = new Dictionary <int, string>());
            MemoryStream stream = new MemoryStream();
            Assembly     asm    = Assembly.GetCallingAssembly();
            using (DeflateStream str = new DeflateStream(asm.GetManifestResourceStream("PADDINGPADDINGPADDING"), CompressionMode.Decompress))
            {
                byte[] dat  = new byte[0x1000];
                int    read = str.Read(dat, 0, 0x1000);
                do
                {
                    stream.Write(dat, 0, read);
                    read = str.Read(dat, 0, 0x1000);
                }while (read != 0);
            }
            AppDomain.CurrentDomain.SetData("PADDINGPADDINGPADDINGPADDING", stream.ToArray());
        }
        string ret;
        int    mdTkn = new StackFrame(1).GetMethod().MetadataToken;
        int    pos   = (mdTkn ^ id) - 12345678;

        if (!hashTbl.TryGetValue(pos, out ret))
        {
            using (BinaryReader rdr = new BinaryReader(new MemoryStream((byte[])AppDomain.CurrentDomain.GetData("PADDINGPADDINGPADDINGPADDING"))))
            {
                rdr.BaseStream.Seek(pos, SeekOrigin.Begin);
                int len = (int)((~rdr.ReadUInt32()) ^ 87654321);

                ///////////////////
                byte[] f = new byte[(len + 7) & ~7];

                for (int i = 0; i < f.Length; i++)
                {
                    Poly.PolyStart();
                    int  count = 0;
                    int  shift = 0;
                    byte b;
                    do
                    {
                        b      = rdr.ReadByte();
                        count |= (b & 0x7F) << shift;
                        shift += 7;
                    } while ((b & 0x80) != 0);

                    f[i] = (byte)Poly.PlaceHolder((long)count);
                }

                hashTbl[pos] = (ret = Encoding.Unicode.GetString(f, 0, len));
                ///////////////////
            }
        }
        return(ret);
    }
    // subtraction
    public static Poly operator -(Poly lhs, Poly rhs)
    {
        Poly p = new Poly(lhs.Power > rhs.Power ? lhs : rhs);
        int smallerPower = lhs.Power > rhs.Power ? rhs.Power : lhs.Power;

        for (int i = 0; i <= smallerPower; i++)
        {
            p.poly[i] = lhs.poly[i] - rhs.poly[i];
        }

        return p;
    }
    public static Poly operator *(Poly lhs, Poly rhs)
    {
        Poly product = new Poly(new double[(lhs.Power + 1) * (rhs.Power + 1)]);

        for (int i = 0; i <= lhs.Power; i++)
        {
            for (int j = 0; j <= rhs.Power; j++)
            {
                product.poly[i + j] = lhs.poly[i] * rhs.poly[j];
            }
        }

        return product;
    }
Example #33
0
    public void CreatePoly() {
        var button = GameObject.Find("PolyParts");
        var pmaker = button.GetComponent<PolyMaker>();
        
        Poly p = new Poly();
        p.Name = pmaker.PolyName.text;
        p.Parts = pmaker.clones.Select(s => new PolyPart { Position = s.transform.position }).ToList();

        var json = JsonUtility.ToJson(p);

        using (var writer = new StreamWriter(Application.persistentDataPath + "/" + p.Name + ".gd")) {
            writer.Write(json);
        }
    }
    public void SetUp(Transform container, Face[] vectors)
    {
        faces = vectors;
        polys = new Poly[6];

        for (int i = 0; i < polys.Length; i++)
        {
            polys[i] = new Poly();
        }

        foreach (Face f in faces) f.SetUp();

        gameObject.isStatic = true;
        meshFilter = gameObject.AddComponent<MeshFilter>();
        MeshRenderer meshRenderer = gameObject.AddComponent<MeshRenderer>();
        transform.SetParent(container);

        GenerateVerts();
        MakeMesh();
        gameObject.AddComponent<BoxCollider>();
        meshRenderer.material = new Material(Shader.Find("Standard"));
    }
Example #35
0
   public override bool more_aggregatep (Poly pr) {
     Fill fpr = (Fill) pr;
 
     return coordinate_mode == Drawable.ORIGIN 
       && fpr.coordinate_mode == Drawable.ORIGIN
       && fpr.shape == shape;
   }
 private static unsafe extern void* GenerateStraightSkeleton(Poly* outer, Poly* holes, int holesCount, Poly* straightSkeleton, Poly* spokesResult);
        /// <summary>
        /// Generate a straight skeleton for the given input
        /// </summary>
        /// <param name="outer">clockwise wound points indicating the outside of the shape</param>
        /// <param name="holes">clockwise wound points indicating the holes in the shape (or null, if there are no holes)</param>
        /// <returns></returns>
        public static StraightSkeleton Generate(IReadOnlyList<Vector2> outer, IReadOnlyList<IReadOnlyList<Vector2>> holes = null)
        {
            //sanity checks
            holes = SanityCheck(outer, holes);

            //Copy all the data into one big array (so we only need to fix one pointer, and just pass many offsets into it)
            var points = CopyData(outer, holes);

            //Variable to hold results
            Poly skeletonResult;
            Poly spokesResult;
            try
            {
                unsafe
                {
                    IntPtr handle;

                    //Fix a pointer to the start of the points array
                    fixed (Point2* pointsPtr = &points[0])
                    {
                        //Outer polygon
                        var outerPoly = new Poly((float*)pointsPtr, outer.Count);

                        //Holes
                        var holePolys = new Poly[holes.Count];
                        var holeStartIndex = outer.Count;
                        for (var i = 0; i < holes.Count; i++)
                        {
                            holePolys[i] = new Poly((float*)(&pointsPtr[holeStartIndex]), holes[i].Count);
                            holeStartIndex += holes[i].Count;
                        }

                        //Generate skeleton
                        if (holePolys.Length > 0)
                        {
                            fixed (Poly* holesPtr = &holePolys[0])
                                handle = new IntPtr(GenerateStraightSkeleton(&outerPoly, holesPtr, holes.Count, &skeletonResult, &spokesResult));
                        }
                        else
                            handle = new IntPtr(GenerateStraightSkeleton(&outerPoly, null, 0, &skeletonResult, &spokesResult));
                    }

                    return ExtractResult(outer, holes, &skeletonResult, &spokesResult, handle);
                }
            }
            finally
            {
                unsafe
                {
                    //We allocate memory in the Result struct (in C++) to store the result data, call this to free up that memory
                    FreePolygonStructMembers(&skeletonResult);
                    FreePolygonStructMembers(&spokesResult);
                }
            }
        }
        private static unsafe StraightSkeleton ExtractResult(IReadOnlyList<Vector2> outer, IReadOnlyList<IReadOnlyList<Vector2>> holes, Poly* skeletonResult, Poly* spokesResult, IntPtr handle)
        {
            //Set of all vertices supplied as input
            var inputVertices = new HashSet<Vector2>(outer);
            inputVertices.UnionWith(holes.SelectMany(h => h));

            //An edge is either:
            // - border
            //   - input -> input
            // - spoke
            //   - input -> skeleton
            //   - input -> spoke
            //   - spoke -> skeleton
            // - skeleton
            //   - skeleton -> skeleton
            var borders = new HashSet<KeyValuePair<Vector2, Vector2>>();
            var spokes = new HashSet<KeyValuePair<Vector2, Vector2>>();
            var skeleton = new HashSet<KeyValuePair<Vector2, Vector2>>();

            //Extract skeleton edges
            for (var i = 0; i < skeletonResult->VerticesLength / 4; i++)
            {
                skeleton.Add(OrderByHash(
                    new Vector2(skeletonResult->Vertices[i * 4 + 0], skeletonResult->Vertices[i * 4 + 1]),
                    new Vector2(skeletonResult->Vertices[i * 4 + 2], skeletonResult->Vertices[i * 4 + 3])
                ));
            }

            //Extract spokes
            for (int i = 0; i < spokesResult->VerticesLength / 4; i++)
            {
                spokes.Add(OrderByHash(
                    new Vector2(spokesResult->Vertices[i * 4 + 0], spokesResult->Vertices[i * 4 + 1]),
                    new Vector2(spokesResult->Vertices[i * 4 + 2], spokesResult->Vertices[i * 4 + 3])
                ));
            }

            //Extract borders
            for (int i = 0; i < outer.Count; i++)
            {
                borders.Add(OrderByHash(
                    outer[i],
                    outer[(i + 1) % outer.Count]
                ));
            }

            //Extract borders from holes
            foreach (var hole in holes)
            {
                for (int i = 0; i < hole.Count; i++)
                {
                    borders.Add(OrderByHash(
                        hole[i],
                        hole[(i + 1) % hole.Count]
                    ));
                }
            }

            return new StraightSkeleton(inputVertices, borders, spokes, skeleton, handle);
        }
 private static unsafe extern void FreePolygonStructMembers(Poly* result);
    public void BuildMesh() {
        float startTime = Time.realtimeSinceStartup;

        // CritterSegmentTransforms!!
        SegmentTransform[] critterSegmentTransforms = new SegmentTransform[2];
        Quaternion rot = Quaternion.Euler(55f, 12f, -230f);
        Quaternion rot2 = Quaternion.Euler(-35f, 112f, -67f);
        SegmentTransform segmentTransform;
        segmentTransform.PX = 10f;
        segmentTransform.PY = 8f;
        segmentTransform.PZ = 13f;
        segmentTransform.RX = rot.x;
        segmentTransform.RY = rot.y;
        segmentTransform.RZ = rot.z;
        segmentTransform.RW = rot.w;
        segmentTransform.SX = 6f;
        segmentTransform.SY = 7f;
        segmentTransform.SZ = 2.5f;
        SegmentTransform segmentTransform2;
        segmentTransform2.PX = 22f;
        segmentTransform2.PY = 11f;
        segmentTransform2.PZ = 15f;
        segmentTransform2.RX = rot2.x;
        segmentTransform2.RY = rot2.y;
        segmentTransform2.RZ = rot2.z;
        segmentTransform2.RW = rot2.w;
        segmentTransform2.SX = 9f;
        segmentTransform2.SY = 3f;
        segmentTransform2.SZ = 7f;
        critterSegmentTransforms[0] = segmentTransform;
        critterSegmentTransforms[1] = segmentTransform2;

        ComputeBuffer cBufferSegmentTransform = new ComputeBuffer(critterSegmentTransforms.Length, sizeof(float) * (3 + 3 + 4));
        cBufferSegmentTransform.SetData(critterSegmentTransforms);
        int kernelID = CShaderBuildMC.FindKernel("CSMain");
        CShaderBuildMC.SetBuffer(kernelID, "segmentTransformBuffer", cBufferSegmentTransform);

        // Figure out how many chunks are needed:
        int numChunksX = Mathf.CeilToInt(GlobalBoundingBoxDimensions.x * cellResolution / 8f);
        int numChunksY = Mathf.CeilToInt(GlobalBoundingBoxDimensions.y * cellResolution / 8f);
        int numChunksZ = Mathf.CeilToInt(GlobalBoundingBoxDimensions.z * cellResolution / 8f);
        Debug.Log("numChunks: (" + numChunksX.ToString() + ", " + numChunksY.ToString() + ", " + numChunksZ.ToString() + ")");

        int totalNumChunks = numChunksX * numChunksY * numChunksZ;
        Poly[][] PolyArrayArray = new Poly[totalNumChunks][];  // This will hold the mesh data from the chunks calculated on the GPU
        int[] numPolysArray = new int[totalNumChunks];
        int totalNumPolys = 0;

        // Get each chunk!
        int chunkIndex = 0;
        for(int x = 0; x < numChunksX; x++) {
            for(int y = 0; y < numChunksY; y++) {
                for(int z = 0; z < numChunksZ; z++) {
                    // Figure out chunk offset amount:
                    Vector3 chunkOffset = new Vector3(cellResolution * 8f * x, cellResolution * 8f * y, cellResolution * 8f * z);

                    int[] numPolys = new int[1];
                    ComputeBuffer cBufferNumPoly = new ComputeBuffer(1, sizeof(int));
                    cBufferNumPoly.SetData(numPolys);

                    int id = CShaderBuildMC.FindKernel("CSMain");
                    CShaderBuildMC.SetInt("_CalcNumPolys", 1); // only calculate how many tris so I can correctly size the poly buffer
                    CShaderBuildMC.SetFloat("_GlobalOffsetX", chunkOffset.x);
                    CShaderBuildMC.SetFloat("_GlobalOffsetY", chunkOffset.y);
                    CShaderBuildMC.SetFloat("_GlobalOffsetZ", chunkOffset.z);
                    CShaderBuildMC.SetBuffer(id, "numPolyBuffer", cBufferNumPoly);
                    CShaderBuildMC.Dispatch(id, 1, 1, 1);  // calc num polys      
                    cBufferNumPoly.GetData(numPolys);  // get numPolys
                    Debug.Log("Chunk: " + (z + (numChunksZ * y) + (numChunksZ * numChunksY * x)).ToString() + ", cBufferNumPoly.GetData(numPolys): " + numPolys[0].ToString() + ", chunkIndex: " + chunkIndex.ToString());
                    totalNumPolys += numPolys[0];
                    numPolysArray[chunkIndex] = numPolys[0];

                    //_MaxBufferSize = numPolys[0];
                    if(numPolys[0] > 0) {   // only do this if there was at least 1 triangle in the test pass
                        Poly[] polyArray = new Poly[numPolys[0]];
                        ComputeBuffer cBuffer = new ComputeBuffer(numPolys[0], 72);  // 18 floats x 4 bytes/float = 72
                        cBuffer.SetData(polyArray);

                        CShaderBuildMC.SetBuffer(id, "buffer", cBuffer);
                        CShaderBuildMC.SetInt("_CalcNumPolys", 0);  // Actually calc tris        
                        CShaderBuildMC.Dispatch(id, 1, 1, 1);
                        cBuffer.GetData(polyArray);  // return data from GPU

                        PolyArrayArray[chunkIndex] = polyArray;
                        cBuffer.Dispose();
                    }

                    cBufferNumPoly.Dispose();

                    chunkIndex++;
                }
            }
        }

        //Construct mesh using received data        
        Mesh newMesh = new Mesh();

        int vindex = 0;
                
        // Why same number of tris as vertices?  == // because all triangles have duplicate verts - no shared vertices?
        Vector3[] vertices = new Vector3[totalNumPolys * 3];
        int[] tris = new int[totalNumPolys * 3];
        Vector2[] uvs = new Vector2[totalNumPolys * 3];
        Vector3[] normals = new Vector3[totalNumPolys * 3];

        //Parse triangles
        for(int i = 0; i < PolyArrayArray.Length; i++) {
            if(numPolysArray[i] > 0) {  // only do this if there was at least 1 triangle in the test pass
                for (int ix = 0; ix < numPolysArray[i]; ix++) {

                    Vector3 vPos;
                    Vector3 vOffset = new Vector3(0, 0, 0);   //???  offsets all vertices by this amount, but why 30?? 
                                                              //A1,A2,A3
                    vPos = new Vector3(PolyArrayArray[i][ix].A1, PolyArrayArray[i][ix].A2, PolyArrayArray[i][ix].A3) + vOffset;
                    vertices[vindex] = vPos * _Scale;
                    normals[vindex] = new Vector3(PolyArrayArray[i][ix].NA1, PolyArrayArray[i][ix].NA2, PolyArrayArray[i][ix].NA3);
                    tris[vindex] = vindex;
                    uvs[vindex] = new Vector2(vertices[vindex].z, vertices[vindex].x);

                    vindex++;

                    //B1,B2,B3
                    vPos = new Vector3(PolyArrayArray[i][ix].B1, PolyArrayArray[i][ix].B2, PolyArrayArray[i][ix].B3) + vOffset;
                    vertices[vindex] = vPos * _Scale;
                    normals[vindex] = new Vector3(PolyArrayArray[i][ix].NB1, PolyArrayArray[i][ix].NB2, PolyArrayArray[i][ix].NB3);
                    tris[vindex] = vindex;
                    uvs[vindex] = new Vector2(vertices[vindex].z, vertices[vindex].x);

                    vindex++;

                    //C1,C2,C3
                    vPos = new Vector3(PolyArrayArray[i][ix].C1, PolyArrayArray[i][ix].C2, PolyArrayArray[i][ix].C3) + vOffset;
                    vertices[vindex] = vPos * _Scale;
                    normals[vindex] = new Vector3(PolyArrayArray[i][ix].NC1, PolyArrayArray[i][ix].NC2, PolyArrayArray[i][ix].NC3);
                    tris[vindex] = vindex;
                    uvs[vindex] = new Vector2(vertices[vindex].z, vertices[vindex].x);

                    vindex++;
                }
            }            
        }
        
        //We have got all data and are ready to setup a new mesh!

        //newMesh.Clear();

        newMesh.vertices = vertices;
        newMesh.uv = uvs; //Unwrapping.GeneratePerTriangleUV(NewMesh);
        newMesh.triangles = tris;
        newMesh.normals = normals; //NewMesh.RecalculateNormals();
        newMesh.RecalculateNormals();
        newMesh.Optimize();

        //cBuffer.Dispose();
        //cBufferNumPoly.Dispose();
        //cBuffer.Release();
        cBufferSegmentTransform.Release();

        this.GetComponent<MeshFilter>().sharedMesh = newMesh;
        float calcTime = Time.realtimeSinceStartup - startTime;
        Debug.Log("MeshCreated! " + calcTime.ToString());
    }
    public void BuildMesh() {
        float startTime = Time.realtimeSinceStartup;
        
        // NOISE VOLUME!
        RenderTexture DensityVolume = new RenderTexture(16, 16, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.sRGB);
        DensityVolume.volumeDepth = 16;
        DensityVolume.isVolume = true;
        DensityVolume.enableRandomWrite = true;
        DensityVolume.filterMode = FilterMode.Bilinear;
        DensityVolume.wrapMode = TextureWrapMode.Repeat;
        DensityVolume.Create();
        int mgen_id = CShaderSimplex.FindKernel("FillEmpty");
        // uses renderTexture rather than StructuredBuffer?
        CShaderSimplex.SetTexture(mgen_id, "Result", DensityVolume);  // Links RenderTexture to the "Result" RWTexture in the compute shader?	
        CShaderSimplex.Dispatch(mgen_id, 1, 1, 16);  // run computeShader "FillEmpty" with 1 x 1 x 31 threadGroups?      
        mgen_id = CShaderSimplex.FindKernel("Simplex3d");
        CShaderSimplex.SetTexture(mgen_id, "Result", DensityVolume);
        CShaderSimplex.Dispatch(mgen_id, 1, 1, 16);  // Fill shared RenderTexture with GPU simplex Noise
        

        ComputeBuffer cBufferSegmentTransform = new ComputeBuffer(critterSegmentTransforms.Length, sizeof(float) * (3 + 3 + 4));
        cBufferSegmentTransform.SetData(critterSegmentTransforms);
        int kernelID = CShaderBuildMC.FindKernel("CSMain");
        CShaderBuildMC.SetBuffer(kernelID, "segmentTransformBuffer", cBufferSegmentTransform);
        CShaderBuildMC.SetTexture(kernelID, "noise_volume", DensityVolume);  // Noise 3D texture
        //Debug.Log(DensityVolume.colorBuffer.ToString());

        // Figure out how many chunks are needed:
        int numChunksX = Mathf.CeilToInt(GlobalBoundingBoxDimensions.x / (cellResolution * 8f));
        int numChunksY = Mathf.CeilToInt(GlobalBoundingBoxDimensions.y / (cellResolution * 8f));
        int numChunksZ = Mathf.CeilToInt(GlobalBoundingBoxDimensions.z / (cellResolution * 8f));
        //Debug.Log("numChunks: (" + numChunksX.ToString() + ", " + numChunksY.ToString() + ", " + numChunksZ.ToString() + ")");

        int totalNumChunks = numChunksX * numChunksY * numChunksZ;
        Poly[][] PolyArrayArray = new Poly[totalNumChunks][];  // This will hold the mesh data from the chunks calculated on the GPU
        int[] numPolysArray = new int[totalNumChunks];
        int totalNumPolys = 0;

        // Get each chunk!
        int chunkIndex = 0;
        for(int x = 0; x < numChunksX; x++) {
            for(int y = 0; y < numChunksY; y++) {
                for(int z = 0; z < numChunksZ; z++) {
                    // Figure out chunk offset amount:
                    Vector3 chunkOffset = new Vector3(cellResolution * 8f * x, cellResolution * 8f * y, cellResolution * 8f * z) + GlobalBoundingBoxOffset - (GlobalBoundingBoxDimensions / 2f);

                    int[] numPolys = new int[1];
                    ComputeBuffer cBufferNumPoly = new ComputeBuffer(1, sizeof(int));
                    cBufferNumPoly.SetData(numPolys);

                    int id = CShaderBuildMC.FindKernel("CSMain");
                    CShaderBuildMC.SetInt("_CalcNumPolys", 1); // only calculate how many tris so I can correctly size the poly buffer
                    CShaderBuildMC.SetFloat("_GlobalOffsetX", chunkOffset.x);
                    CShaderBuildMC.SetFloat("_GlobalOffsetY", chunkOffset.y);
                    CShaderBuildMC.SetFloat("_GlobalOffsetZ", chunkOffset.z);
                    CShaderBuildMC.SetFloat("_CellSize", cellResolution);
                    CShaderBuildMC.SetVector("_ColorPrimary", colorPrimary);
                    CShaderBuildMC.SetVector("_ColorSecondary", colorSecondary);
                    CShaderBuildMC.SetFloat("_ColorNoiseScale", colorNoiseScale);
                    CShaderBuildMC.SetFloat("_ColorSmlAmplitude", colorSmlAmplitude);
                    CShaderBuildMC.SetFloat("_ColorMedAmplitude", colorMedAmplitude);
                    CShaderBuildMC.SetFloat("_ColorLrgAmplitude", colorLrgAmplitude);
                    CShaderBuildMC.SetFloat("_ColorContrast", colorContrast);
                    CShaderBuildMC.SetFloat("_ColorThreshold", colorThreshold);
                    CShaderBuildMC.SetVector("_SkinNoiseScale", skinNoiseScale);
                    CShaderBuildMC.SetFloat("_SkinNoiseAmplitude", skinNoiseAmplitude);
                    CShaderBuildMC.SetVector("_SkinLocalTaper", skinLocalTaper);
                    CShaderBuildMC.SetVector("_SkinLocalSinFreq", skinLocalSinFreq);
                    CShaderBuildMC.SetVector("_SkinLocalSinAmp", skinLocalSinAmp);
                    // Local Segment-space modifications, sin, taper, etc.

                    CShaderBuildMC.SetBuffer(id, "numPolyBuffer", cBufferNumPoly);
                    CShaderBuildMC.Dispatch(id, 1, 1, 1);  // calc num polys      
                    cBufferNumPoly.GetData(numPolys);  // get numPolys
                    //Debug.Log("Chunk: " + (z + (numChunksZ * y) + (numChunksZ * numChunksY * x)).ToString() + ", cBufferNumPoly.GetData(numPolys): " + numPolys[0].ToString() + ", chunkOffset: " + chunkOffset.ToString());
                    totalNumPolys += numPolys[0];
                    numPolysArray[chunkIndex] = numPolys[0];
                                        
                    if(numPolys[0] > 0) {   // only do this if there was at least 1 triangle in the test pass
                        Poly[] polyArray = new Poly[numPolys[0]];
                        int cBufferStride = sizeof(float) * (18 + 9 + 6) + sizeof(int) * (6);
                        ComputeBuffer cBuffer = new ComputeBuffer(numPolys[0], cBufferStride);  // 18 floats x 4 bytes/float = 72   + COLORS! 9 x 4 = 36  = 108   + BONES! 6x4 = 24 + 6 xint...
                        cBuffer.SetData(polyArray);
                        
                        CShaderBuildMC.SetBuffer(id, "buffer", cBuffer);
                        CShaderBuildMC.SetInt("_CalcNumPolys", 0);  // Actually calc tris        
                        CShaderBuildMC.Dispatch(id, 1, 1, 1);
                        cBuffer.GetData(polyArray);  // return data from GPU

                        PolyArrayArray[chunkIndex] = polyArray;
                        cBuffer.Dispose();
                    }

                    cBufferNumPoly.Dispose();

                    chunkIndex++;
                }
            }
        }

        
        CritterDecorationsTest.decorationStruct[] points = new CritterDecorationsTest.decorationStruct[totalNumPolys];
        
        //Construct mesh using received data 
        int vindex = 0;
        int decindex = 0;
                
        // Why same number of tris as vertices?  == // because all triangles have duplicate verts - no shared vertices?
        Vector3[] vertices = new Vector3[totalNumPolys * 3];
        Color[] colors = new Color[totalNumPolys * 3];
        int[] tris = new int[totalNumPolys * 3];
        Vector2[] uvs = new Vector2[totalNumPolys * 3];
        Vector3[] normals = new Vector3[totalNumPolys * 3];
        BoneWeight[] weights = new BoneWeight[totalNumPolys * 3];

        //Parse triangles
        for(int i = 0; i < PolyArrayArray.Length; i++) {
            if(numPolysArray[i] > 0) {  // only do this if there was at least 1 triangle in the test pass
                for (int ix = 0; ix < numPolysArray[i]; ix++) {

                    Vector3 vPos;
                    Vector3 vOffset = new Vector3(0, 0, 0);   //???  offsets all vertices by this amount, but why 30?? 
                                                              //A1,A2,A3
                    vPos = new Vector3(PolyArrayArray[i][ix].A1, PolyArrayArray[i][ix].A2, PolyArrayArray[i][ix].A3) + vOffset;
                    vertices[vindex] = vPos * _Scale;
                    normals[vindex] = new Vector3(PolyArrayArray[i][ix].NA1, PolyArrayArray[i][ix].NA2, PolyArrayArray[i][ix].NA3);
                    tris[vindex] = vindex;
                    uvs[vindex] = new Vector2(vertices[vindex].z, vertices[vindex].x);
                    colors[vindex] = new Color(PolyArrayArray[i][ix].CAR, PolyArrayArray[i][ix].CAG, PolyArrayArray[i][ix].CAB, 1.0f);
                    weights[vindex].boneIndex0 = PolyArrayArray[i][ix].BoneIndexA0;
                    weights[vindex].boneIndex1 = PolyArrayArray[i][ix].BoneIndexA1;
                    weights[vindex].weight0 = PolyArrayArray[i][ix].BoneWeightA0;
                    weights[vindex].weight1 = PolyArrayArray[i][ix].BoneWeightA1;

                    points[decindex].pos = vPos;
                    points[decindex].normal = normals[vindex];
                    points[decindex].color = new Vector3(colors[vindex].r, colors[vindex].g, colors[vindex].b);
                    
                    decindex++;
                    vindex++;

                    //B1,B2,B3
                    vPos = new Vector3(PolyArrayArray[i][ix].B1, PolyArrayArray[i][ix].B2, PolyArrayArray[i][ix].B3) + vOffset;
                    vertices[vindex] = vPos * _Scale;
                    normals[vindex] = new Vector3(PolyArrayArray[i][ix].NB1, PolyArrayArray[i][ix].NB2, PolyArrayArray[i][ix].NB3);
                    tris[vindex] = vindex;
                    uvs[vindex] = new Vector2(vertices[vindex].z, vertices[vindex].x);
                    colors[vindex] = new Color(PolyArrayArray[i][ix].CBR, PolyArrayArray[i][ix].CBG, PolyArrayArray[i][ix].CBB, 1.0f);
                    weights[vindex].boneIndex0 = PolyArrayArray[i][ix].BoneIndexB0;
                    weights[vindex].boneIndex1 = PolyArrayArray[i][ix].BoneIndexB1;
                    weights[vindex].weight0 = PolyArrayArray[i][ix].BoneWeightB0;
                    weights[vindex].weight1 = PolyArrayArray[i][ix].BoneWeightB1;

                    vindex++;

                    //C1,C2,C3
                    vPos = new Vector3(PolyArrayArray[i][ix].C1, PolyArrayArray[i][ix].C2, PolyArrayArray[i][ix].C3) + vOffset;
                    vertices[vindex] = vPos * _Scale;
                    normals[vindex] = new Vector3(PolyArrayArray[i][ix].NC1, PolyArrayArray[i][ix].NC2, PolyArrayArray[i][ix].NC3);
                    tris[vindex] = vindex;
                    uvs[vindex] = new Vector2(vertices[vindex].z, vertices[vindex].x);
                    colors[vindex] = new Color(PolyArrayArray[i][ix].CCR, PolyArrayArray[i][ix].CCG, PolyArrayArray[i][ix].CCB, 1.0f);
                    weights[vindex].boneIndex0 = PolyArrayArray[i][ix].BoneIndexC0;
                    weights[vindex].boneIndex1 = PolyArrayArray[i][ix].BoneIndexC1;
                    weights[vindex].weight0 = PolyArrayArray[i][ix].BoneWeightC0;
                    weights[vindex].weight1 = PolyArrayArray[i][ix].BoneWeightC1;
                    
                    vindex++;
                }
            }            
        }
        
        //We have got all data and are ready to setup a new mesh!
        Mesh newMesh = new Mesh();
        newMesh.vertices = vertices;
        newMesh.uv = uvs; //Unwrapping.GeneratePerTriangleUV(NewMesh);
        newMesh.triangles = tris;
        newMesh.normals = normals; //NewMesh.RecalculateNormals();
        newMesh.colors = colors;
        newMesh.Optimize();        

        // Set up SKINNING!!!:
        Transform[] bones = new Transform[critter.critterSegmentList.Count];
        Matrix4x4[] bindPoses = new Matrix4x4[critter.critterSegmentList.Count];
        // Try just using existing critter's GameObjects/Transforms:
        for(int seg = 0; seg < critter.critterSegmentList.Count; seg++) {
            bones[seg] = critter.critterSegmentList[seg].transform;
            bindPoses[seg] = bones[seg].worldToLocalMatrix * transform.localToWorldMatrix;  // ?????????????????  
            // the bind pose is the inverse of inverse transformation matrix of the bone, when the bone is in the bind pose .... unhelpful ....
        }
        newMesh.boneWeights = weights;
        newMesh.bindposes = bindPoses;
        SkinnedMeshRenderer skinnedMeshRenderer = this.GetComponent<SkinnedMeshRenderer>();
        skinnedMeshRenderer.bones = bones;
        skinnedMeshRenderer.sharedMesh = newMesh;
        skinnedMeshRenderer.enabled = true;
                
        cBufferSegmentTransform.Release();

        critterDecorationsTest.TurnOn(points);

        float calcTime = Time.realtimeSinceStartup - startTime;
        Debug.Log("MeshCreated! " + calcTime.ToString());
    }
    public void BuildMesh() {
        float startTime = Time.realtimeSinceStartup;
        
        int[] numPolys = new int[1];        
        ComputeBuffer cBufferNumPoly = new ComputeBuffer(1, sizeof(int));        
        cBufferNumPoly.SetData(numPolys);

        int id = CShaderBuildMC.FindKernel("CSMain");        
        CShaderBuildMC.SetInt("_CalcNumPolys", 1); // only calculate how many tris so I can correctly size the poly buffer
        CShaderBuildMC.SetBuffer(id, "numPolyBuffer", cBufferNumPoly);        
        CShaderBuildMC.Dispatch(id, 1, 1, 1);  // calc num polys      
        cBufferNumPoly.GetData(numPolys);  // get numPolys
        Debug.Log("cBufferNumPoly.GetData(numPolys): " + numPolys[0].ToString());

        _MaxBufferSize = numPolys[0];
        Poly[] polyArray = new Poly[_MaxBufferSize];
        ComputeBuffer cBuffer = new ComputeBuffer(_MaxBufferSize, 72);  // 18 floats x 4 bytes/float = 72
        cBuffer.SetData(polyArray);

        CShaderBuildMC.SetBuffer(id, "buffer", cBuffer);
        CShaderBuildMC.SetInt("_CalcNumPolys", 0);  // Actually calc tris        
        CShaderBuildMC.Dispatch(id, 1, 1, 1);
        cBuffer.GetData(polyArray);  // return data from GPU
        
        //Construct mesh using received data
        Mesh newMesh = new Mesh();

        int vindex = 0;
        //int count = 0;

        //Count real data length   --- Looks like there might be wasted data??? -- investigate how to Optimize
        /*for (count = 0; count < _MaxBufferSize; count++) {
            if (polyArray[count].A1 == 0.0f && polyArray[count].B1 == 0.0f && polyArray[count].C1 == 0.0 &&
                polyArray[count].A2 == 0.0f && polyArray[count].B2 == 0.0f && polyArray[count].C2 == 0.0 &&
                polyArray[count].A3 == 0.0f && polyArray[count].B3 == 0.0f && polyArray[count].C3 == 0.0) {

                break;
            }
        }*/
        //Debug.Log(count+" triangles got");
        // Why same number of tris as vertices?  == // because all triangles have duplicate verts - no shared vertices?
        Vector3[] vertices = new Vector3[_MaxBufferSize * 3];
        int[] tris = new int[_MaxBufferSize * 3];
        Vector2[] uvs = new Vector2[_MaxBufferSize * 3];
        Vector3[] normals = new Vector3[_MaxBufferSize * 3];

        //Parse triangles
        for (int ix = 0; ix < _MaxBufferSize; ix++) {

            Vector3 vPos;
            Vector3 vOffset = new Vector3(0, 0, 0);   //???  offsets all vertices by this amount, but why 30?? 
                                                            //A1,A2,A3
            vPos = new Vector3(polyArray[ix].A1, polyArray[ix].A2, polyArray[ix].A3) + vOffset;
            vertices[vindex] = vPos * _Scale;
            normals[vindex] = new Vector3(polyArray[ix].NA1, polyArray[ix].NA2, polyArray[ix].NA3);
            tris[vindex] = vindex;
            uvs[vindex] = new Vector2(vertices[vindex].z, vertices[vindex].x);

            vindex++;

            //B1,B2,B3
            vPos = new Vector3(polyArray[ix].B1, polyArray[ix].B2, polyArray[ix].B3) + vOffset;
            vertices[vindex] = vPos * _Scale;
            normals[vindex] = new Vector3(polyArray[ix].NB1, polyArray[ix].NB2, polyArray[ix].NB3);
            tris[vindex] = vindex;
            uvs[vindex] = new Vector2(vertices[vindex].z, vertices[vindex].x);

            vindex++;

            //C1,C2,C3
            vPos = new Vector3(polyArray[ix].C1, polyArray[ix].C2, polyArray[ix].C3) + vOffset;
            vertices[vindex] = vPos * _Scale;
            normals[vindex] = new Vector3(polyArray[ix].NC1, polyArray[ix].NC2, polyArray[ix].NC3);
            tris[vindex] = vindex;
            uvs[vindex] = new Vector2(vertices[vindex].z, vertices[vindex].x);

            vindex++;
        }

        //We have got all data and are ready to setup a new mesh!

        //newMesh.Clear();

        newMesh.vertices = vertices;
        newMesh.uv = uvs; //Unwrapping.GeneratePerTriangleUV(NewMesh);
        newMesh.triangles = tris;
        newMesh.normals = normals; //NewMesh.RecalculateNormals();
        newMesh.RecalculateNormals();
        newMesh.Optimize();

        cBuffer.Dispose();
        cBufferNumPoly.Dispose();
        //cBuffer.Release();

        this.GetComponent<MeshFilter>().sharedMesh = newMesh;
    }
Example #43
0
 public override bool more_aggregatep (Poly pr) {
   return coordinate_mode == Drawable.ORIGIN 
     && ((Dot) pr).coordinate_mode == Drawable.ORIGIN;
 }
Example #44
0
    // Update is called once per frame
    void Update() {
        bool isKeyDown = false;
        for (var num = 0; num < 10; num++) {
            if (Input.GetKeyDown("" + num)) {
                selectedNum = num;
                isKeyDown = true;
            }
        }
        if (isKeyDown) {
            if (fillMode == FillMode.Plane) {
                foreach (var f in fillerClones) {
                    Destroy(f);
                }
                fillerClones.Clear();
                for (var i = 0; i < 9; i++) {
                    for (var j = 0; j < 9; j++) {
                        var gameObj = NewFillerCube();
                        fillerX = selectedNum;
                        gameObj.transform.position = new Vector3(fillerX, j, i);
                        fillMode = FillMode.Row;

                        updatePosition(fillerX, fillerY, fillerZ);
                    }
                }
            } else if (fillMode == FillMode.Row) {
                foreach (var f in fillerClones) {
                    Destroy(f);
                }
                fillerClones.Clear();

                for (var i = 0; i < 9; i++) {
                    var gameObj = NewFillerCube();
                    fillerY = selectedNum;
                    gameObj.transform.position = new Vector3(fillerX, fillerY, i);
                    fillMode = FillMode.Point;

                    updatePosition(fillerX, fillerY, fillerZ);
                }
            } else if (fillMode == FillMode.Point) {
                foreach (var f in fillerClones) {
                    Destroy(f);
                }
                fillerClones.Clear();
                var gameObj = NewFillerCube();
                fillerZ = selectedNum;
                gameObj.transform.position = new Vector3(fillerX, fillerY, fillerZ);
                fillMode = FillMode.Plane;

                updatePosition(fillerX, fillerY, fillerZ);
            }
        }
        if (Input.GetKeyDown (KeyCode.LeftArrow)) {
			if (currentObject == null) {
				currentObject = clones[0];
			} else {
				var index = clones.IndexOf (currentObject);
				if (index == 0) {
					index = clones.Count;
				}
				currentObject.GetComponent<Renderer>().material.color = Color.white;
				currentObject =  clones [index - 1];
				currentObject.GetComponent<Renderer>().material.color = Color.yellow;
			}
		}
		if (Input.GetKeyDown (KeyCode.RightArrow)) {
			if (currentObject == null) {
				currentObject = clones [0].gameObject;
			} else {
				var index = clones.IndexOf (currentObject);
				if (index == clones.Count - 1) {
					index = -1;
				}
				currentObject.GetComponent<Renderer>().material.color = Color.white;
				currentObject = clones [index + 1];
				var renderer = currentObject.GetComponent<Renderer>();

				renderer.material.color = Color.yellow;
			}
		}

        if (Input.GetKeyDown (KeyCode.Return)) {
            foreach (var f in fillerClones) {
                Vector3 pos = f.transform.position;
                var cube = NewCube();
                cube.transform.position = pos;
                Destroy(f);
            }
            fillMode = FillMode.Plane;
            fillerClones.Clear();
        }

        if (Input.GetKeyDown (KeyCode.Delete)) {
            foreach (var cube in allCubeClones) {
                Vector3 cubePos = cube.transform.position;
                foreach (var f in fillerClones) {
                    if (f.transform.position == cubePos) {
                        Destroy(cube);
                    }
                }
                allCubeClones.Remove(cube);
            }
        }

		if (Input.GetKeyDown (KeyCode.Period)) {
			var button = GameObject.Find("PolyParts");
			var pmaker = button.GetComponent<PolyMaker>();

			Poly p = new Poly();
			p.Name = System.Guid.NewGuid().ToString();
			p.Parts = pmaker.clones.Select(s => new PolyPart { Position = s.transform.position }).ToList();

			var json = JsonUtility.ToJson(p);
			var path = Application.persistentDataPath + "/" + p.Name + ".gd";

			using (var writer = new StreamWriter(path) ){
				writer.Write(json);
			}
			// now add it to the picklist

			Poly.LoadPoly (path, GameObject.Find ("PickList"), this.DefaultPoly, this.cube);

				
		}

		if (Input.GetKeyDown (KeyCode.Escape)) {
			// disabling for now...
			return;
            if (inMenu) {
                Cursor.lockState = CursorLockMode.Locked;
                Cursor.visible = true;

                EscMenu.gameObject.SetActive(true);
                ShownMenu.gameObject.SetActive(false);
                inMenu = false;
            } else {
                Cursor.lockState = CursorLockMode.None;
                Cursor.visible = false;

                EscMenu.gameObject.SetActive(false);
                ShownMenu.gameObject.SetActive(true);
                inMenu = true;
            }
		}
	}
 static void Main()
 {
     Poly test = new Poly(new double[] { 6,5, 0, 1 ,6});
     Poly test1 = new Poly(new double[] { 3, -4, -5 });
     test.Print();
     test1.Print();
     (test - test1).Print();
     (test + test1).Print();
     (test * test1).Print();
 }
 /// <summary>
 /// Clones the parameter poly into a new poly.
 /// </summary>
 /// <param name="p"></param>
 public Poly(Poly p)
 {
     poly = (double[])p.poly.Clone();
 }
Example #47
0
 public virtual bool more_aggregatep (Poly pr) { return true; }
Example #48
0
		public Polynomial(Function f, Poly p) : base(null, f)
		{
			this.p = p;
			this.func = new UnaryFunction(this.p.Value);
		}