Exemplo n.º 1
0
        private SchemaType MakeType(SDF sdf)
        {
            var n = sdf as Node;

            if (n == null)
            {
                throw new InvalidDataException("Schema type description must be a node.");
            }

            var conditions = MakeConditionsForNode(n);

            switch (n.Name)
            {
            case "node-type":
                SchemaElement children = null;
                if (n.Attributes.ContainsKey("children"))
                {
                    children = MakeElement(n.Attributes["children"]);
                }

                var attributes = MakeAttributes(n.Children);
                return(new SchemaNodeType(n, children, conditions, attributes));

            case "literal-type":
                return(new SchemaLiteralType(n, _builtinTypes, conditions));

            default:
                throw new InvalidDataException("Invalid schema type description.");
            }
        }
Exemplo n.º 2
0
    public FP Get(Vector2Int pt, int layerMask = -1)
    {
        FP val = SDF.Get(pt);

        if (layerMask == 1)
        {
            TSVector2 pos = new TSVector2(pt.x * SDF.Grain, pt.y * SDF.Grain);
            foreach (var shape in Obstacles)
            {
                if ((shape.LayerMask & layerMask) == 0)
                {
                    continue;
                }
                if (!shape.Bound.Contains(pt))
                {
                    continue;
                }
                FP sd = shape.SDValue(pos);
                if (sd < val)
                {
                    val = sd;
                }
            }
        }

        return(val);
    }
Exemplo n.º 3
0
    void Update()
    {
        Ray ray = new Ray(transform.position, transform.forward);

        if (Physics.Raycast(ray, out RaycastHit hit, maxDistance, chunkLayerMask.value))
        {
            Debug.DrawLine(ray.origin, hit.point, Color.white);

            if (!hit.collider.TryGetComponent(out TestChunk chunk))
            {
                return;
            }

            if (Input.GetMouseButton(0))
            {
                var sdfParams = new SDFParams(hit.point, chunk.chunkSize, power, Time.deltaTime);
                SDF.SphereSDF(sdfParams, radius, ref chunk).Complete();
                chunk.BuildMesh();
            }
            else if (Input.GetMouseButton(2))
            {
                var sdfParams = new SDFParams(hit.point, chunk.chunkSize, -power, Time.deltaTime);
                SDF.SphereSDF(sdfParams, radius, ref chunk).Complete();
                chunk.BuildMesh();
            }
        }
    }
Exemplo n.º 4
0
        internal override bool MeetsCondition(SDF value)
        {
            var aNumber = value as NumberLiteral;

            if (aNumber == null)
            {
                return(false);
            }

            var a = aNumber.Double;
            var b = _value.Double;

            switch (_operatorName)
            {
            case "<": return(a < b);

            case ">": return(a > b);

            case "<=": return(a <= b || _value.Integer == aNumber.Integer && _value.Fraction == aNumber.Fraction);                    // just in case

            case ">=": return(a >= b || _value.Integer == aNumber.Integer && _value.Fraction == aNumber.Fraction);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 5
0
 private static void PrintLiteral(SDF literal, int offset)
 {
     PrintOffset(offset);
     if (literal is StringLiteral)
     {
         Console.Write("\"" + (literal as StringLiteral).Value + "\"");                 // TODO: escape characters
     }
     else if (literal is NumberLiteral)
     {
         var number = literal as NumberLiteral;
         Console.Write(number.Integer);
         if (number.Fraction > 0)
         {
             Console.Write(".");
             Console.Write(number.Fraction);
         }
     }
     else if (literal is BooleanLiteral)
     {
         Console.Write((literal as BooleanLiteral).Value ? "true" : "false");
     }
     else
     {
         Console.Write("null");
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// Triangulates the given object and parses the result to the builder.
        /// </summary>
        /// <param name="autoOptimize">Determine weather or not to use grid refinement, lazy cube evaluation and another sized grid - based on the given SDF.</param>
        /// <returns></returns>
        public virtual IPolygon Run(SDF obj, IPolygonBuilder builder, bool autoOptimize)
        {
            /// Setup!
            if (autoOptimize)
            {
                Optimize(obj);
            }

            _obj     = obj;
            _builder = builder;

            if (builder is GridLog)
            {
                _log        = builder as GridLog;
                _useLogging = true;
            }

            if (useRefinement)
            {
                GridRefinement();
            }
            else
            {
                _halfStep = new Vec3(_step / 2, _step / 2, _step / 2);
                _lazy     = _halfStep.Magnitude() * 1.001f;
                Initialize();
                GridLoop();
            }

            return(_builder.Build());
        }
Exemplo n.º 7
0
        internal override bool MeetsCondition(SDF value)
        {
            var a = value as StringLiteral;

            if (a == null)
            {
                return(false);
            }

            switch (_operatorName)
            {
            case "~=":
            case "^=":
            case "$=":
                return(MeetsOperator(a.Value, _operatorName));

            case "!~=":
            case "!^=":
            case "!$=":
                return(!MeetsOperator(a.Value, _operatorName.Substring(1)));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 8
0
        internal static void AssertAreDeeplyEqualNodes(SDF expected, SDF actual)
        {
            var n1 = expected as Node;
            var n2 = actual as Node;

            if (n1 == null || n2 == null)
            {
                Assert.Fail("Both expected and actual must be nodes, but at least one of them is not:\n\t" + expected + "\n\t" + actual);
            }

            Assert.AreEqual(n1.Name, n2.Name);
            Assert.AreEqual(n1.Attributes.Count, n2.Attributes.Count);
            Assert.AreEqual(n1.Children.Count, n2.Children.Count);

            // compare attributes
            foreach (var attribute in n1.Attributes)
            {
                Assert.IsTrue(n2.Attributes.ContainsKey(attribute.Key));
                AssertAreDeeplyEqual(attribute.Value, n2.Attributes[attribute.Key]);
            }

            // now compare children
            for (var i = 0; i < n1.Children.Count; ++i)
            {
                AssertAreDeeplyEqual(n1.Children[i], n2.Children[i]);
            }
        }
Exemplo n.º 9
0
Arquivo: Match.cs Projeto: Tkachov/sdf
        internal static Match MakeMatch(SDF v, Match parent, int index, bool moreThanOneChild)
        {
            // make children's path
            string path;

            if (parent == null)
            {
                path = "/";
            }
            else
            {
                path = parent.Path + "/";
            }

            if (v is Node)
            {
                path += (v as Node).Name;
            }

            if (moreThanOneChild || !(v is Node))
            {
                path += "#" + index;
            }

            return(MakeMatch(v, path, parent));
        }
Exemplo n.º 10
0
        public bool Run()
        {
            Program.PrintTitle("SETUP - DEFAULT LAUNCHER");

            // Debug?
            var debugView = AskUser("Enable step visualizer triangulation?");

            // # of triangulations?
            Console.WriteLine("\nNumber of simultaneous triangulations?");
            Console.Write("> ");
            var n = 0;

            while (!int.TryParse(Console.ReadLine(), out n))
            {
                Console.WriteLine("Invalid input! Please enter a number");
                Console.Write("\n> ");
            }

            // Setup...
            var triangulator = new ITriangulator[n];
            var sdf          = new SDF[n];

            for (int i = 0; i < n; i++)
            {
                Program.PrintTitle($"PERFORM SETUP {i + 1} of {n}");
                triangulator[i] = Program.UserInstantiation <ITriangulator>("triangulation method");
                sdf[i]          = Program.UserInstantiation <IRuntimeSDF>("signed distance function").Instance();
            }


            // Triangulate!
            Tuple <Log, IPolygon, string, long>[] result;
            if (debugView)
            {
                result = TriangulateWithLog(triangulator, sdf);
            }
            else
            {
                result = Triangulate(triangulator, sdf);
            }

            // Show result!
            if (debugView)
            {
                if (!LaunchLogView(result))
                {
                    Export(result);
                }
            }
            else
            {
                if (!LaunchView(result))
                {
                    Export(result);
                }
            }

            return(!AskUser("Restart the application?"));
        }
Exemplo n.º 11
0
        /// <summary>
        ///     Partially validate given SDF representation with current schema.
        ///     Returns whether given SDF could match schema (for example, a node lacks a required attribute, but otherwise it's
        ///     completely correct).
        ///     If SDF does not match schema (no possible addition will fix it), ErrorMessage would be set to notify of a reason.
        ///     Only the first error is returned.
        /// </summary>
        /// <param name="input">SDF to validate.</param>
        /// <returns>Whether given SDF could match schema.</returns>
        public bool ValidatePartial(SDF input)
        {
            ErrorMessage = null;

            var e = _topElement;

            return(ValidateMatchesPartial(e, Match.MakeRootMatch(input)));
        }
Exemplo n.º 12
0
 public bool Setup(float[] f, SDF[] s)
 {
     if (s.Length != 1 && f.Length != 1)
     {
         return(false);
     }
     obj = new PolygonTriangulation.ImplicitObjects.Scaling(s[0], f[0]);
     return(true);
 }
Exemplo n.º 13
0
 public bool Setup(params float[] f)
 {
     if (f.Length <= 2)
     {
         return(false);
     }
     obj = new PolygonTriangulation.ImplicitObjects.Box(f[1], f[0], f[2]);
     return(true);
 }
Exemplo n.º 14
0
Arquivo: Match.cs Projeto: Tkachov/sdf
        private static Match MakeMatch(SDF v, [NotNull] string path, Match parent)
        {
            if (v is Node)
            {
                return(new MatchNode(v, path, parent));
            }

            return(new Match(v, path, parent));
        }
Exemplo n.º 15
0
 public bool Setup(float[] f, SDF[] s)
 {
     if (s.Length != 2)
     {
         return(false);
     }
     obj = new PolygonTriangulation.ImplicitObjects.Subtraction(s[0], s[1]);
     return(true);
 }
        public bool Setup(params float[] f)
        {
            if (f.Length != 4)
            {
                return(false);
            }

            obj = new PolygonTriangulation.ImplicitObjects.Primitives.GoursatsSurface(f[0], f[1], f[2], f[3]);
            return(true);
        }
Exemplo n.º 17
0
        bool IRuntimeSDF.Setup(params float[] f)
        {
            if (f.Length <= 1)
            {
                return(false);
            }

            obj = new PolygonTriangulation.ImplicitObjects.Torus(f[0], f[1]);
            return(true);
        }
Exemplo n.º 18
0
        public bool Setup(params float[] f)
        {
            if (f.Length != 1)
            {
                return(false);
            }

            obj = new PolygonTriangulation.ImplicitObjects.InfinitePlane(f[0]);
            return(true);
        }
        public bool Setup(float[] f, SDF[] s)
        {
            if (s.Length != 1 && f.Length != 3)
            {
                return(false);
            }

            obj = new PolygonTriangulation.ImplicitObjects.Transformation(s[0], new PolygonTriangulation.Model.Vec3(f[0], f[1], f[2]));
            return(true);
        }
Exemplo n.º 20
0
        public bool Setup(params float[] f)
        {
            if (f.Length != 1)
            {
                return(false);
            }

            obj = new PolygonTriangulation.ImplicitObjects.Complex.AtomCube(f[0]);
            return(true);
        }
Exemplo n.º 21
0
    private void OnWizardCreate()
    {
        SDF.MaxIter = MaxIter;
        var rt = SDF.Bake(_texture);

        var path    = AssetDatabase.GetAssetPath(_texture);
        var sdfPath = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path)) + "-SDF.png";

        SaveRTToFile(rt, sdfPath);

        RenderTexture.ReleaseTemporary(rt);
    }
Exemplo n.º 22
0
        internal static Mesh NewSDFMesh(SDF sdf, Box box, double step)
        {
            var             min       = box.Min;
            var             size      = box.Size();
            var             nx        = (int)Math.Ceiling(size.X / step);
            var             ny        = (int)Math.Ceiling(size.Y / step);
            var             nz        = (int)Math.Ceiling(size.Z / step);
            var             sx        = size.X / nx;
            var             sy        = size.Y / ny;
            var             sz        = size.Z / nz;
            List <Triangle> triangles = new List <Triangle>();

            for (int x = 0; x < nx - 1; x++)
            {
                for (int y = 0; y < ny - 1; y++)
                {
                    for (int z = 0; z < nz - 1; z++)
                    {
                        (var x0, var y0, var z0) = ((double)x * sx + min.X, (double)y * sy + min.Y, (double)z * sz + min.Z);
                        (var x1, var y1, var z1) = (x0 + sx, y0 + sy, z0 + sz);

                        var p = new Vector[8] {
                            new Vector(x0, y0, z0),
                            new Vector(x1, y0, z0),
                            new Vector(x1, y1, z0),
                            new Vector(x0, y1, z0),
                            new Vector(x0, y0, z1),
                            new Vector(x1, y0, z1),
                            new Vector(x1, y1, z1),
                            new Vector(x0, y1, z1)
                        };

                        double[] v = new double[8];

                        for (int i = 0; i < 8; i++)
                        {
                            v[i] = sdf.Evaluate(p[i]);
                        }

                        if (mcPolygonize(p, v, 0) == null)
                        {
                            continue;
                        }
                        else
                        {
                            triangles.AddRange(mcPolygonize(p, v, 0));
                        }
                    }
                }
            }
            return(Mesh.NewMesh(triangles.ToArray()));
        }
Exemplo n.º 23
0
        internal static void AssertAreDeeplyEqual(SDF expected, SDF actual)
        {
            var n = expected as Node;

            if (n == null)
            {
                AssertAreDeeplyEqualLiterals(expected, actual);
            }
            else
            {
                AssertAreDeeplyEqualNodes(expected, actual);
            }
        }
Exemplo n.º 24
0
        public bool Setup(float[] f, SDF[] s)
        {
            if (s.Length != 1 && f.Length != 3)
            {
                return(false);
            }
            var x = (float)(f[0] % 360 * Math.PI) / 180;
            var y = (float)(f[1] % 360 * Math.PI) / 180;
            var z = (float)(f[2] % 360 * Math.PI) / 180;

            obj = new PolygonTriangulation.ImplicitObjects.Rotation(s[0], x, y, z);
            return(true);
        }
Exemplo n.º 25
0
        private static bool PrintOnSameLineIfLiteral(SDF s, int offset, bool newLineIfLiteral)
        {
            if (s is Node)
            {
                Console.WriteLine();
                Print(s, offset);
                return(false);
            }

            Console.Write(" ");
            Print(s, 0, newLineIfLiteral);
            return(true);
        }
Exemplo n.º 26
0
        SDF userSDF()
        {
            if (!AskUser("Choose an SDF operator?"))
            {
                return(Program.UserInstantiation <IRuntimeSDF>("signed distance function").Instance());
            }

            var obj = Program.UserInstantiation <ISDFOperator>("operator");

            // Set all float values
            var parems = obj.FloatParameters();
            var f      = new float[parems.Length];

            for (int i = 0; i < parems.Length; i++)
            {
                Console.WriteLine($"\n[{obj.GetType().Name.Beautify()}] Please specify { parems[i] }:");
                Console.Write("> ");
                var input = Console.ReadLine();
                if (!float.TryParse(input, out f[i]))
                {
                    i--;                     // Retry if it failed
                }
            }

            // Set all sdf values
            var SDFparems = obj.SDFParameters();
            var s         = new SDF[SDFparems.Length];

            for (int i = 0; i < SDFparems.Length; i++)
            {
                Console.WriteLine($"\n[{obj.GetType().Name.Beautify()}] Please specify { SDFparems[i] }:");
                Console.Write("> ");
                s[i] = userSDF();
            }
            obj.Setup(f, s);
            Console.WriteLine($"Done with {obj.ToString()}");

            SDF result = null;

            if (obj is IRuntimeSDF)
            {
                result = (obj as IRuntimeSDF).Instance();
            }

            if (obj is ISDFOperator)
            {
                result = (obj as ISDFOperator).Instance();
            }

            return(result);
        }
Exemplo n.º 27
0
Arquivo: Match.cs Projeto: Tkachov/sdf
        internal MatchNode(SDF value, string path, Match parent) : base(value, path, parent)
        {
            var n = value as Node;

            if (n == null)
            {
                throw new InvalidDataException("Cannot create MatchNode from something but a Node.");
            }

            var index = 0;

            Children   = n.Children.Select(c => MakeMatch(c, this, index++, n.Children.Count > 1)).ToList();
            Attributes = n.Attributes.ToDictionary(a => a.Key, a => MakeMatch(a.Value, this, a.Key));
        }
Exemplo n.º 28
0
        internal override bool MeetsCondition(SDF value)
        {
            switch (_operatorName)
            {
            case "=":
                return(MeetsOperator(value, "="));

            case "!=":
                return(!MeetsOperator(value, "=") && SameType(value));                        // so !=3 wouldn't produce nodes, strings, etc

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 29
0
        private SchemaElement MakeElement(SDF sdf)
        {
            var n = sdf as Node;

            if (n == null)
            {
                throw new InvalidDataException("Schema element description must be a node.");
            }

            switch (n.Name)
            {
            case "node-element":
                return(new SchemaNodeElement(n));

            case "literal-element":
                return(new SchemaLiteralElement(n, _builtinTypes));

            case "sequence":
            case "one-of":
                var elements = new List <SchemaElement>();
                foreach (var child in n.Children)
                {
                    elements.Add(MakeElement(child));
                }

                if (n.Name == "sequence")
                {
                    return(new SchemaSequenceElement(elements));
                }

                return(new SchemaOneOfElement(elements));

            case "list":
                var children = n.Children;
                if (children.Count != 1)
                {
                    throw new InvalidDataException("Schema list description must have exactly one element description.");
                }

                return(new SchemaListElement(n, MakeElement(children[0])));

            default:
                throw new InvalidDataException("Invalid schema element description.");
            }
        }
Exemplo n.º 30
0
Arquivo: Match.cs Projeto: Tkachov/sdf
        internal static Match MakeMatch(SDF v, Match parent, string attributeName)
        {
            // make attribute's path
            string path;

            if (parent == null)
            {
                path = "/";
            }
            else
            {
                path = parent.Path + "/";
            }

            path += "@" + attributeName;

            return(MakeMatch(v, path, parent));
        }