Inheritance: SmallXmlParser.IContentHandler
        public SVGGradientElement(SVGParser xmlImp, Node node)
        {
            _attrList = node.attributes;
            _xmlImp = xmlImp;
            _stopList = new List<SVGStopElement>();
            _id = _attrList.GetValue("id");
            _gradientUnits = SVGGradientUnit.ObjectBoundingBox;
            if (_attrList.GetValue("gradiantUnits") == "userSpaceOnUse")
            {
                _gradientUnits = SVGGradientUnit.UserSpaceOnUse;
            }

            _gradientTransform = new SVGTransformList(_attrList.GetValue("gradientTransform"));

            //------
            // TODO: It's probably a bug that the value is not innoculated for CaSe
            // VaRiAtIoN in GetValue, below:
            _spreadMethod = SVGSpreadMethod.Pad;
            if (_attrList.GetValue("spreadMethod") == "reflect")
            {
                _spreadMethod = SVGSpreadMethod.Reflect;
            } else if (_attrList.GetValue("spreadMethod") == "repeat")
            {
                _spreadMethod = SVGSpreadMethod.Repeat;
            }

            if(node is BlockOpenNode)
            {
                GetElementList();
            }
        }
Beispiel #2
0
    protected SVGGradientElement(SVGParser xmlImp, Dictionary<string, string> attrList)
    {
        _attrList = attrList;
        _xmlImp = xmlImp;
        _stopList = new List<SVGStopElement>();
        _id = _attrList.GetValue("id");
        _gradientUnits = SVGGradientUnit.ObjectBoundingBox;
        if (_attrList.GetValue("gradiantUnits") == "userSpaceOnUse")
        {
            _gradientUnits = SVGGradientUnit.UserSpaceOnUse;
        }

        //------
        // TODO: It's probably a bug that the value is not innoculated for CaSe
        // VaRiAtIoN in GetValue, below:
        _spreadMethod = SVGSpreadMethod.Pad;
        if (_attrList.GetValue("spreadMethod") == "reflect")
        {
            _spreadMethod = SVGSpreadMethod.Reflect;
        }
        else if (_attrList.GetValue("spreadMethod") == "repeat")
        {
            _spreadMethod = SVGSpreadMethod.Repeat;
        }

        GetElementList();
    }
 public SVGClipPathElement(SVGParser xmlImp, Node node)
 {
     _attrList = node.attributes;
     _xmlImp = xmlImp;
     _id = _attrList.GetValue("id");
     GetElementList();
 }
Beispiel #4
0
    public SVGGElement(SVGParser xmlImp,
		SVGTransformList inheritTransformList,
		SVGPaintable inheritPaintable,
		SVGGraphics render)
        : base(inheritTransformList)
    {
        _render = render;
        Dictionary<string, string> attrList = xmlImp.Node.Attributes;
        _paintable = new SVGPaintable(inheritPaintable, attrList);
        currentTransformList = new SVGTransformList(attrList.GetValue("transform"));
        xmlImp.GetElementList(_elementList, _paintable, _render, summaryTransformList);
    }
 /***********************************************************************************/
 public SVGSVGElement(  SVGParser xmlImp,
           SVGTransformList inheritTransformList,
           SVGPaintable inheritPaintable,
           SVGGraphics r)
     : base(inheritTransformList)
 {
     _render = r;
     _xmlImp = xmlImp;
     _attrList = _xmlImp.Node.Attributes;
     _paintable = new SVGPaintable(inheritPaintable, _attrList);
     _width = new SVGLength(_attrList.GetValue("width"));
     _height = new SVGLength(_attrList.GetValue("height"));
     Initial();
 }
Beispiel #6
0
 /***********************************************************************************/
 public SVGGElement(SVGParser xmlImp,
                   SVGTransformList inheritTransformList,
                   SVGPaintable inheritPaintable,
                   SVGGraphics render)
     : base(inheritTransformList)
 {
     _render = render;
     _xmlImp = xmlImp;
     _attrList = _xmlImp.Node.Attributes;
     _paintable = new SVGPaintable(inheritPaintable, _attrList);
     _elementList = new List<object>();
     currentTransformList = new SVGTransformList(_attrList.GetValue("transform"));
     GetElementList();
 }
        public SVGLinearGradientElement(SVGParser xmlImp, Node node) : base(xmlImp, node)
        {
            string temp;
            temp = _attrList.GetValue("x1");
            _x1 = new SVGLength((temp == "") ? "0%" : temp);

            temp = this._attrList.GetValue("y1");
            _y1 = new SVGLength((temp == "") ? "0%" : temp);

            temp = this._attrList.GetValue("x2");
            _x2 = new SVGLength((temp == "") ? "100%" : temp);

            temp = this._attrList.GetValue("y2");
            _y2 = new SVGLength((temp == "") ? "0%" : temp);
        }
    public SVGRadialGradientElement(SVGParser xmlImp, Dictionary<string, string> attrList)
        : base(xmlImp, attrList)
    {
        string temp = attrList.GetValue("cx");
        _cx = new SVGLength((temp == "") ? "50%" : temp);

        temp = attrList.GetValue("cy");
        _cy = new SVGLength((temp == "") ? "50%" : temp);

        temp = attrList.GetValue("r");
        _r = new SVGLength((temp == "") ? "50%" : temp);

        temp = attrList.GetValue("fx");
        _fx = new SVGLength((temp == "") ? "50%" : temp);

        temp = attrList.GetValue("fy");
        _fy = new SVGLength((temp == "") ? "50%" : temp);
    }
        public SVGRadialGradientElement(SVGParser xmlImp, Node node) : base(xmlImp, node)
        {
            string temp;
            temp = _attrList.GetValue("cx");
            _cx = new SVGLength((temp == "") ? "50%" : temp);

            temp = _attrList.GetValue("cy");
            _cy = new SVGLength((temp == "") ? "50%" : temp);

            temp = _attrList.GetValue("r");
            _r = new SVGLength((temp == "") ? "50%" : temp);

            temp = _attrList.GetValue("fx");
            _fx = new SVGLength((temp == "") ? "50%" : temp);

            temp = _attrList.GetValue("fy");
            _fy = new SVGLength((temp == "") ? "50%" : temp);
        }
    public SVGRadialGradientElement(SVGParser xmlImp, Dictionary<string, string> attrList)
        : base(xmlImp, attrList)
    {
        // TODO: Override GetValue to return `null` and use `||`.
        string temp = attrList.GetValue("cx");
        _cx = new SVGLength((temp == "") ? "50%" : temp);

        temp = attrList.GetValue("cy");
        _cy = new SVGLength((temp == "") ? "50%" : temp);

        temp = attrList.GetValue("r");
        _r = new SVGLength((temp == "") ? "50%" : temp);

        temp = attrList.GetValue("fx");
        _fx = new SVGLength((temp == "") ? "50%" : temp);

        temp = attrList.GetValue("fy");
        _fy = new SVGLength((temp == "") ? "50%" : temp);
    }
Beispiel #11
0
    public SVGSVGElement(SVGParser xmlImp,
                       SVGTransformList inheritTransformList,
                       SVGPaintable inheritPaintable,
                       SVGGraphics r)
        : base(inheritTransformList)
    {
        _render = r;
        _attrList = xmlImp.Node.Attributes;
        var paintable = new SVGPaintable(inheritPaintable, _attrList);
        _width = new SVGLength(_attrList.GetValue("width"));
        _height = new SVGLength(_attrList.GetValue("height"));

        SetViewBox();

        ViewBoxTransform();

        SVGTransform temp = new SVGTransform(_cachedViewBoxTransform);
        SVGTransformList t_currentTransformList = new SVGTransformList();
        t_currentTransformList.AppendItem(temp);
        currentTransformList = t_currentTransformList; // use setter only once, since it also updates other lists

        xmlImp.GetElementList(_elementList, paintable, _render, summaryTransformList);
    }
Beispiel #12
0
    void SetCrisps()
    {
        string crisp =
            @"<svg xmlns=""http://www.w3.org/2000/svg"" viewBox=""0 0 11.44 13.95"">
                <g><path id=""Packet"" d=""M13.13,13.9H3.39a5.9,5.9,0,0,1-.81-3.15c0-1.51.75-2.34.63-4.08a16.67,16.67,0,0,0-.39-1.79A5.66,5.66,0,0,1,3.21,1L12.6,1a15.62,15.62,0,0,1,.33,5c-.19,1.94-.78,2.25-.56,3.63.2,1.21.79,2.12.53,3.63a4.26,4.26,0,0,1-.27.93"" transform=""translate(-2.07 -0.47)"" fill=""none"" stroke=""#000"" stroke-miterlimit=""10""/></g>
                <g><text transform=""translate(2.33 5.11) rotate(-7.27)"" font-size=""2.5"">B</text></g>
                <g><text transform=""translate(3.66 5) rotate(-2.06)"" font-size=""2.5"" font-family=""ArialNarrow-Italic, Arial"">I</text></g>
                <g><text transform=""translate(4.23 5.03) rotate(0.56)"" font-size=""2.5"" font-family=""ArialNarrow-Italic, Arial"">T</text></g>
                <g><text transform=""translate(5.45 5.07) rotate(2.51)"" font-size=""2.5"" font-family=""ArialNarrow-Italic, Arial"">E</text></g>
                <g><text transform=""translate(6.66 5.17) rotate(3.93)"" font-size=""2.5"" font-family=""ArialNarrow-Italic, Arial"">R</text></g>
                <g><text transform=""translate(8.07 5.27) rotate(0.35)"" font-size=""2.5"" font-family=""ArialNarrow-Italic, Arial"">S</text></g>
                <g><ellipse id=""Crisp1"" cx=""8.34"" cy=""9.75"" rx=""2.04"" ry=""1.5"" transform=""translate(-5.83 5) rotate(-30)"" fill=""#ffdc7f"" stroke=""#000"" stroke-miterlimit=""10"" stroke-width=""0.15""/></g>
                <g><ellipse id=""Crisp0"" cx=""6.77"" cy=""8.95"" rx=""2.04"" ry=""1.5"" transform=""translate(-6.44 9.86) rotate(-60)"" fill=""#ffdc7f"" stroke=""#000"" stroke-miterlimit=""10"" stroke-width=""0.15""/></g>
            </svg>";

        var sceneInfo = SVGParser.ImportSVG(new StringReader(crisp));
        var shape     = sceneInfo.NodeIDs["Packet"].Shapes[0];

        shape.Fill = new SolidFill()
        {
            Color = Color.red
        };

        var tessOptions = new VectorUtils.TessellationOptions()
        {
            StepDistance         = 100f,
            MaxCordDeviation     = 0.5f,
            MaxTanAngleDeviation = 0.1f,
            SamplingStepSize     = 0.01f
        };

        var geoms  = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions);
        var sprite = VectorUtils.BuildSprite(geoms, 26, VectorUtils.Alignment.Center, Vector2.zero, 128, true);

        GetComponent <SpriteRenderer>().sprite = sprite;
    }
Beispiel #13
0
    public void ImportSVG_UseCanReferenceImageDefinedLater()
    {
        string svg =
            @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""no""?>
            <!DOCTYPE svg PUBLIC ""-//W3C//DTD SVG 1.1//EN"" ""http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"">
            <svg width=""100%"" height=""100%"" viewBox=""0 0 256 256"" version=""1.1"" xmlns=""http://www.w3.org/2000/svg"" xmlns:xlink=""http://www.w3.org/1999/xlink"" xml:space=""preserve"" xmlns:serif=""http://www.serif.com/"" style=""fill-rule:evenodd;clip-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:1.5;"">
                <g transform=""matrix(0.975989,0,0,0.975989,3.07335,3.07335)"">
                    <path d=""M256,64C256,28.677 227.323,0 192,0L64,0C28.677,0 0,28.677 0,64L0,192C0,227.323 28.677,256 64,256L192,256C227.323,256 256,227.323 256,192L256,64Z"" style=""fill:url(#_Linear1);stroke:black;stroke-width:6.15px;""/>
                </g>
                <g id=""palette--5-"" serif:id=""palette (5)"" transform=""matrix(0.135645,0,0,-0.135645,19.4839,209.387)"">
                    <use id=""Use"" xlink:href=""#_Image2"" x=""0"" y=""0"" width=""1600px"" height=""1200px"" transform=""matrix(7.37327,0,0,7.36196,0,0)""/>
                </g>
                <defs>
                    <linearGradient id=""_Linear1"" x1=""0"" y1=""0"" x2=""1"" y2=""0"" gradientUnits=""userSpaceOnUse"" gradientTransform=""matrix(256,0,0,256,0,128)""><stop offset=""0"" style=""stop-color:rgb(216,255,0);stop-opacity:1""/><stop offset=""1"" style=""stop-color:rgb(255,0,244);stop-opacity:1""/></linearGradient>
                    <image id=""_Image2"" width=""217px"" height=""163px"" xlink:href=""data:image/png;base64,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""/>
                </defs>
            </svg>";

        var sceneInfo   = SVGParser.ImportSVG(new StringReader(svg));
        var shape       = sceneInfo.NodeIDs["Use"].Shapes[0];
        var textureFill = shape.Fill as TextureFill;

        Assert.IsNotNull(textureFill);
    }
Beispiel #14
0
    public void ImportSVG_SupportsLinearGradientFills()
    {
        string svg =
            @"<svg xmlns=""http://www.w3.org/2000/svg"" width=""100"" height=""20"">
                <defs>
                    <linearGradient id=""grad"">
                        <stop offset=""0%"" stop-color=""blue"" />
                        <stop offset=""100%"" stop-color=""red"" />
                    </linearGradient>
                </defs>
                <rect x=""5"" y=""10"" width=""100"" height=""20"" fill=""url(#grad)"" />
            </svg>";

        var sceneInfo = SVGParser.ImportSVG(new StringReader(svg));
        var shape     = sceneInfo.Scene.Root.Children[0].Shapes[0];
        var fill      = shape.Fill as GradientFill;

        Assert.AreEqual(GradientFillType.Linear, fill.Type);
        Assert.AreEqual(2, fill.Stops.Length);
        Assert.AreEqual(0.0f, fill.Stops[0].StopPercentage);
        Assert.AreEqual(Color.blue, fill.Stops[0].Color);
        Assert.AreEqual(1.0f, fill.Stops[1].StopPercentage);
        Assert.AreEqual(Color.red, fill.Stops[1].Color);
    }
Beispiel #15
0
        public Bitmap GetPin(float ratio, int number, int width, int height, float alpha = 1)
        {
            int    key = number + ((int)(ratio * 10000)) << 6;
            Bitmap bmp;

            if (pinCache.TryGetValue(key, out bmp))
            {
                return(bmp);
            }

            var svg = SVGParser.ParseSVGFromResource(context.Resources,
                                                     Resource.Raw.pin,
                                                     SvgColorMapperFactory.FromFunc(c => ColorReplacer(c, ratio, alpha)));

            bmp = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888);
            using (var c = new Canvas(bmp)) {
                var dst = new RectF(0, 0, width, height);
                c.DrawPicture(svg.Picture, dst);
                c.DrawText(number.ToString(), width / 2 - 1, 16.ToPixels (), textPaint);
            }

            pinCache [key] = bmp;
            return(bmp);
        }
        public Rect CalcSize(XdObjectJson xdObject)
        {
            var position      = Vector2.zero;
            var size          = new Vector2(xdObject.Shape.Width, xdObject.Shape.Height);
            var scaleBehavior = xdObject.Style?.Fill?.Pattern?.Meta?.Ux?.ScaleBehavior ?? "fill";
            var spriteUid     = xdObject.Style?.Fill?.Pattern?.Meta?.Ux?.Uid;

            var shapeType = xdObject.Shape?.Type;

            if (!string.IsNullOrWhiteSpace(spriteUid))
            {
                // nothing
            }
            else if (SvgUtil.Types.Contains(shapeType))
            {
                var svg = SvgUtil.CreateSvg(xdObject);
                using (var reader = new StringReader(svg))
                {
                    var sceneInfo   = SVGParser.ImportSVG(reader, ViewportOptions.DontPreserve);
                    var tessOptions = SvgToPng.TessellationOptions;
                    var geometry    = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions, sceneInfo.NodeOpacity);
                    var vertices    = geometry.SelectMany(geom => geom.Vertices.Select(x => (geom.WorldTransform * x))).ToArray();
                    var bounds      = VectorUtils.Bounds(vertices);
                    if (bounds.width > 0.0001f && bounds.height > 0.0001f)
                    {
                        size     = new Vector2(bounds.width, bounds.height);
                        position = new Vector2(bounds.x, bounds.y);
                    }
                }
            }

            if (scaleBehavior == "cover" && size.x > 0.0001f && size.y > 0.0001f)
            {
                var imageWidth     = xdObject.Style?.Fill?.Pattern?.Width ?? 0f;
                var imageHeight    = xdObject.Style?.Fill?.Pattern?.Height ?? 0f;
                var imageSize      = new Vector2(imageWidth, imageHeight);
                var imageAspect    = imageSize.x / imageSize.y;
                var instanceAspect = size.x / size.y;
                var offsetX        = xdObject.Style?.Fill?.Pattern?.Meta?.Ux?.OffsetX ?? 0f;
                var offsetY        = xdObject.Style?.Fill?.Pattern?.Meta?.Ux?.OffsetY ?? 0f;
                var scale          = xdObject.Style?.Fill?.Pattern?.Meta?.Ux?.Scale ?? 1.0f;

                if (imageAspect > instanceAspect)
                {
                    var prev = size.x;
                    size.x      = size.y * (imageSize.x / imageSize.y);
                    position.x -= (size.x - prev) / 2f;

                    position.x += offsetX * xdObject.Shape.Width * imageAspect / instanceAspect;
                    position.y += offsetY * xdObject.Shape.Height;
                }
                else
                {
                    var prev = size.y;
                    size.y      = size.x * (imageSize.y / imageSize.x);
                    position.y -= (size.y - prev) / 2f;

                    position.x += offsetX * xdObject.Shape.Width;
                    position.y += offsetY * xdObject.Shape.Height * imageAspect / instanceAspect;
                }

                {
                    var prev = size;
                    size     *= scale;
                    position -= (size - prev) / 2f;
                }
            }

            return(new Rect(position, size));
        }
Beispiel #17
0
 public SVGDocument(string originalDocument, SVGGraphics r)
 {
     parser = new SVGParser(originalDocument);
     render = r;
 }
Beispiel #18
0
        public void StartProcess(SVGAsset asset)
        {
            if (UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
            {
                return;
            }

            if (errors == null)
            {
                errors = new List <SVGError>();
            }
            else
            {
                errors.Clear();
            }
            _importingSVG = true;

            UnityEditor.SerializedObject   svgAsset      = new UnityEditor.SerializedObject(asset);
            UnityEditor.SerializedProperty sharedMesh    = svgAsset.FindProperty("_sharedMesh");
            UnityEditor.SerializedProperty sharedShaders = svgAsset.FindProperty("_sharedShaders");

            Clear();
            SVGParser.Init();
            SVGGraphics.Init();
            atlasData = new SVGAtlasData();
            SVGElement _rootSVGElement = null;

#if IGNORE_EXCEPTIONS
            try {
#else
            Debug.LogWarning("Exceptions are turned on!");
#endif
                // Create new Asset
                CreateEmptySVGDocument();
                _rootSVGElement = this._svgDocument.rootElement;
#if IGNORE_EXCEPTIONS
            } catch (System.Exception exception) {
                _rootSVGElement = null;
                errors.Add(SVGError.Syntax);
                Debug.LogError("SVG Document Exception: " + exception.Message, asset);
            }
#endif

                if (_rootSVGElement == null)
                {
                    Debug.LogError("SVG Document is corrupted! " + UnityEditor.AssetDatabase.GetAssetPath(asset), asset);
                    _importingSVG = false;
                    return;
                }

                SVGGraphics.depthTree = new SVGDepthTree(_rootSVGElement.paintable.viewport);

#if IGNORE_EXCEPTIONS
                try {
#endif
                _rootSVGElement.Render();

                // Handle gradients
                bool hasGradients = (useGradients == SVGUseGradients.Always);

                // Create actual Mesh
                Shader[] outputShaders;
                SVGLayer[] outputLayers;
                Mesh mesh = SVGMesh.CombineMeshes(SVGGraphics.meshes, out outputLayers, out outputShaders, useGradients, format, compressDepth);
                if (mesh == null)
                {
                    return;
                }

                if (outputShaders != null)
                {
                    for (int i = 0; i < outputShaders.Length; i++)
                    {
                        if (outputShaders[i] == null)
                        {
                            continue;
                        }
                        if (outputShaders[i].name == SVGShader.GradientColorOpaque.name ||
                            outputShaders[i].name == SVGShader.GradientColorAlphaBlended.name)
                        {
                            hasGradients = true;
                            break;
                        }
                    }
                }

                Vector3[] vertices = mesh.vertices;
                Vector2 offset;
                Bounds bounds = mesh.bounds;
                Rect viewport = _rootSVGElement.paintable.viewport;
                viewport.x    *= SVGAssetImport.meshScale;
                viewport.y    *= SVGAssetImport.meshScale;
                viewport.size *= SVGAssetImport.meshScale;

                if (asset.ignoreSVGCanvas)
                {
                    offset = new Vector2(bounds.min.x + bounds.size.x * asset.pivotPoint.x,
                                         bounds.min.y + bounds.size.y * asset.pivotPoint.y);
                }
                else
                {
                    offset = new Vector2(viewport.min.x + viewport.size.x * asset.pivotPoint.x,
                                         viewport.min.y + viewport.size.y * asset.pivotPoint.y);
                }

                // Apply pivot point and Flip Y Axis
                for (int i = 0; i < vertices.Length; i++)
                {
                    vertices[i].x = vertices[i].x - offset.x;
                    vertices[i].y = (vertices[i].y - offset.y) * -1f;
                }

                mesh.vertices = vertices;
                mesh.RecalculateBounds();
                sharedMesh.objectReferenceValue = AddObjectToAsset <Mesh>(mesh, asset, HideFlags.HideInHierarchy);

//                Material sharedMaterial;
                if (outputShaders != null && outputShaders.Length > 0)
                {
                    sharedShaders.arraySize = outputShaders.Length;
                    if (hasGradients)
                    {
                        for (int i = 0; i < outputShaders.Length; i++)
                        {
                            sharedShaders.GetArrayElementAtIndex(i).stringValue = outputShaders[i].name;
                        }
                    }
                    else
                    {
                        for (int i = 0; i < outputShaders.Length; i++)
                        {
                            if (outputShaders[i].name == SVGShader.GradientColorAlphaBlended.name)
                            {
                                outputShaders[i] = SVGShader.SolidColorAlphaBlended;
                            }
                            else if (outputShaders[i].name == SVGShader.GradientColorOpaque.name)
                            {
                                outputShaders[i] = SVGShader.SolidColorOpaque;
                            }
                            sharedShaders.GetArrayElementAtIndex(i).stringValue = outputShaders[i].name;
                        }
                    }
                }

                // Serialize the Asset
                svgAsset.ApplyModifiedProperties();

                // Handle Canvas Rectangle
                System.Reflection.MethodInfo _editor_SetCanvasRectangle = typeof(SVGAsset).GetMethod("_editor_SetCanvasRectangle", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                _editor_SetCanvasRectangle.Invoke(asset, new object[] { new Rect(viewport.x, viewport.y, viewport.size.x, viewport.size.y) });

                if (asset.generateCollider)
                {
                    // Create polygon contour
                    if (SVGGraphics.paths != null && SVGGraphics.paths.Count > 0)
                    {
                        List <List <Vector2> > polygons = new List <List <Vector2> >();
                        for (int i = 0; i < SVGGraphics.paths.Count; i++)
                        {
                            Vector2[] points = SVGGraphics.paths[i].points;
                            for (int j = 0; j < points.Length; j++)
                            {
                                points[j].x = points[j].x * SVGAssetImport.meshScale - offset.x;
                                points[j].y = (points[j].y * SVGAssetImport.meshScale - offset.y) * -1f;
                            }

                            polygons.Add(new List <Vector2>(points));
                        }

                        polygons = SVGGeom.MergePolygon(polygons);

                        SVGPath[] paths = new SVGPath[polygons.Count];
                        for (int i = 0; i < polygons.Count; i++)
                        {
                            paths[i] = new SVGPath(polygons[i].ToArray());
                        }

                        System.Reflection.MethodInfo _editor_SetColliderShape = typeof(SVGAsset).GetMethod("_editor_SetColliderShape", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                        if (paths != null && paths.Length > 0)
                        {
                            _editor_SetColliderShape.Invoke(asset, new object[] { paths });
                        }
                        else
                        {
                            _editor_SetColliderShape.Invoke(asset, new object[] { null });
                        }
                    }
                }
                else
                {
                    System.Reflection.MethodInfo _editor_SetColliderShape = typeof(SVGAsset).GetMethod("_editor_SetColliderShape", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                    _editor_SetColliderShape.Invoke(asset, new object[] { null });
                }

                if (hasGradients)
                {
                    System.Reflection.MethodInfo _editor_SetGradients = typeof(SVGAsset).GetMethod("_editor_SetGradients", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                    if (atlasData.gradients != null && atlasData.gradients.Count > 0)
                    {
                        _editor_SetGradients.Invoke(asset, new object[] { atlasData.gradients.ToArray() });
                    }
                    else
                    {
                        _editor_SetGradients.Invoke(asset, new object[] { null });
                    }
                }
#if IGNORE_EXCEPTIONS
            } catch (System.Exception exception) {
                Debug.LogWarning("Asset: " + UnityEditor.AssetDatabase.GetAssetPath(asset) + " Failed to import\n" + exception.Message, asset);
                errors.Add(SVGError.CorruptedFile);
            }
#endif
                if (_svgDocument != null)
                {
                    _svgDocument.Clear();
                    _svgDocument = null;
                }
                Clear();

                UnityEditor.EditorUtility.SetDirty(asset);
                _importingSVG = false;
            }
Beispiel #19
0
    void SetHair(ref string svg, ref SVGParser.SceneInfo sceneInfo)
    {
        if (citizen.age >= 55)
        {
            hairColour = Color.grey;
        }
        else
        {
            hairColour = worldController.hairColours[Random.Range(0, worldController.hairColours.Length)];
        }
        hairColour = ChangeColorBrightness(hairColour);

        //string hairSvg =
        //    @"<svg xmlns=""http://www.w3.org/2000/svg"" viewBox=""0 0 30.21 14.6"">";

        int style = 0;

        if (!citizen.gender)
        {
            RandomHairStyle(ref svg, out style);
        }
        svg      += @"<g><path id=""Hair1"" d=""M30.82,16.71c.29,7.6-6.42,14-14.57,14.1-8.33.12-15.34-6.33-15-14.1"" transform=""translate(-1 -2.6)"" fill=""#fff"" stroke=""#040000"" stroke-linecap=""round"" stroke-miterlimit=""10"" stroke-width=""0.5""/></g>
                        <g><path id=""Hair2"" d=""M1.12,16.71a29.34,29.34,0,0,0,14.88,4,29.25,29.25,0,0,0,14.75-4"" transform=""translate(-1 -2.6)"" fill=""#fff"" stroke=""#000"" stroke-linecap=""round"" stroke-miterlimit=""10"" stroke-width=""0.5""/></g>
                        </svg>";
        sceneInfo = SVGParser.ImportSVG(new StringReader(svg));
        var hairShape = sceneInfo.NodeIDs["Hair1"].Shapes[0];

        hairShape.Fill = new SolidFill()
        {
            Color = hairColour
        };
        hairShape      = sceneInfo.NodeIDs["Hair2"].Shapes[0];
        hairShape.Fill = new SolidFill()
        {
            Color = skinTone
        };
        if (!citizen.gender)
        {
            switch (style)
            {
            case 0:
                hairShape      = sceneInfo.NodeIDs["PonyTail"].Shapes[0];
                hairShape.Fill = new SolidFill()
                {
                    Color = hairColour
                };
                hairShape      = sceneInfo.NodeIDs["PonyTail2"].Shapes[0];
                hairShape.Fill = new SolidFill()
                {
                    Color = hairColour
                };
                break;

            case 1:
                hairShape      = sceneInfo.NodeIDs["PonyTail"].Shapes[0];
                hairShape.Fill = new SolidFill()
                {
                    Color = hairColour
                };
                break;
            }
        }

        //var tessOptions = new VectorUtils.TessellationOptions()
        //{
        //    StepDistance = 100f,
        //    MaxCordDeviation = 0.5f,
        //    MaxTanAngleDeviation = 0.1f,
        //    SamplingStepSize = 0.01f
        //};

        //var geoms = VectorUtils.TessellateScene(hairSceneInfo.Scene, tessOptions);
        //var sprite = VectorUtils.BuildSprite(geoms, 26, VectorUtils.Alignment.Center, Vector2.zero, 128, true);
        //GameObject go = new GameObject("Hair");
        //go.transform.SetParent(transform);
        //transform.GetChild(0).gameObject.SetActive(true);
        //go.AddComponent<SpriteRenderer>();
        //go.transform.localPosition = new Vector3(0, citizen.gender ? -.25f : -.355f, 0);
        //SpriteRenderer sr = go.GetComponent<SpriteRenderer>();
        //sr.sprite = sprite;
        //sr.sortingLayerID = GetComponent<SpriteRenderer>().sortingLayerID;
        //sr.sortingOrder = GetComponent<SpriteRenderer>().sortingOrder;
    }
    void Start()
    {
        // Prepare the vector path, add it to the vector scene.
        m_Path = new Shape()
        {
            Contours = new BezierContour[] {
                new BezierContour()
                {
                    Segments = new BezierPathSegment[2]
                },
                new BezierContour()
                {
                    Segments = new BezierPathSegment[2]
                }
            },
            PathProps = new PathProperties()
            {
                Stroke = new Stroke()
                {
                    Color         = Color.white,
                    HalfThickness = 0.1f
                }
            }
        };

        m_Scene = new Scene()
        {
            Root = new SceneNode()
            {
                Shapes = new List <Shape> {
                    //m_Path
                }
            }
        };

        m_Options = new VectorUtils.TessellationOptions()
        {
            StepDistance         = 1000.0f,
            MaxCordDeviation     = 0.05f,
            MaxTanAngleDeviation = 0.05f,
            SamplingStepSize     = 0.01f
        };

        // Instantiate a new mesh, it will be filled with data in Update()
        m_Mesh = new Mesh();
        GetComponent <MeshFilter>().mesh = m_Mesh;


        // =======================================================================
        string path = string.Format(@"D:\WriteByHand\svgs\{0}.svg", 20986);
        string svg  = SVGHelper.readSVG(path);

        SVGParser.SceneInfo scene_info = SVGParser.ImportSVG(new StringReader(svg));
        Scene     scene = scene_info.Scene;
        SceneNode word  = scene.Root.Children[1];

        // 前半為背景(無 Clipper),後半為寫字筆劃(有 Clipper)
        List <SceneNode> bg_and_stroke = word.Children;
        int double_stroke_number       = bg_and_stroke.Count;
        int stroke_number = double_stroke_number / 2;

        // 筆劃第一筆
        SceneNode    test_node         = bg_and_stroke[stroke_number];
        List <Shape> test_shapes       = test_node.Shapes;
        SceneNode    test_clipper_node = (test_node.Clipper == null) ? null : test_node.Clipper;
        List <Shape> test_clippers     = new List <Shape>();

        if (test_clipper_node != null)
        {
            test_clippers = test_clipper_node.Children[0].Shapes;
            if (test_clippers != null)
            {
                print("test_clippers len:" + test_clippers.Count);
                Shape test_clipper_shape = test_clippers[0];
            }
            else
            {
                print("test_clippers is null");
            }
        }
        else
        {
            print("test_clipper_node is null");
        }

        Shape test_stroke = test_shapes[0];

        BezierContour[]     bezierContours     = test_stroke.Contours;
        BezierPathSegment[] bezierPathSegments = bezierContours[0].Segments;
        BezierPathSegment   point1             = bezierPathSegments[0];
        BezierPathSegment   point2             = bezierPathSegments[bezierPathSegments.Length - 1];

        #region Word scene
        // 遮罩嘗試
        display_scene = new Scene()
        {
            Root = new SceneNode()
            {
                Children = new List <SceneNode>()
                {
                    #region One stroke
                    new SceneNode()
                    {
                        Shapes = new List <Shape>()
                        {
                            #region Piece of stroke
                            new Shape()
                            {
                                Contours = new BezierContour[] {
                                    new BezierContour()
                                    {
                                        Segments = new BezierPathSegment[]
                                        {
                                            point1,
                                            point2
                                        }
                                    },
                                    //new BezierContour() {
                                    //    Segments = new BezierPathSegment[2]
                                    //}
                                },
                                PathProps = new PathProperties()
                                {
                                    Stroke = new Stroke()
                                    {
                                        Color         = Color.white,
                                        HalfThickness = 10f
                                    }
                                }
                            }
                            #endregion Piece of stroke end
                        },
                        Clipper = new SceneNode()
                        {
                            Shapes = new List <Shape>()
                            {
                                #region Piece of clipper
                                test_clippers[0]
                                #endregion Piece of clipper end
                            }
                        }
                    }
                    #endregion One stroke end
                }
            }
        };
        #endregion Word scene end

        StartCoroutine(nextStroke(bg_and_stroke));
    }
Beispiel #21
0
    void Start()
    {
        //string svg =
        //    @"<svg width=""283.9"" height=""283.9"" xmlns=""http://www.w3.org/2000/svg"">
        //        <line x1=""170.3"" y1=""226.99"" x2=""177.38"" y2=""198.64"" fill=""none"" stroke=""#888"" stroke-width=""1""/>
        //        <line x1=""205.73"" y1=""198.64"" x2=""212.81"" y2=""226.99"" fill=""none"" stroke=""#888"" stroke-width=""1""/>
        //        <line x1=""212.81"" y1=""226.99"" x2=""219.9"" y2=""255.33"" fill=""none"" stroke=""#888"" stroke-width=""1""/>
        //        <line x1=""248.25"" y1=""255.33"" x2=""255.33"" y2=""226.99"" fill=""none"" stroke=""#888"" stroke-width=""1""/>
        //        <path d=""M170.08,226.77c7.09-28.34,35.43-28.34,42.52,0s35.43,28.35,42.52,0"" transform=""translate(0.22 0.22)"" fill=""none"" stroke=""red"" stroke-width=""1.2""/>
        //        <circle cx=""170.3"" cy=""226.99"" r=""1.2"" fill=""blue"" stroke-width=""0.6""/>
        //        <circle cx=""212.81"" cy=""226.99"" r=""1.2"" fill=""blue"" stroke-width=""0.6""/>
        //        <circle cx=""255.33"" cy=""226.99"" r=""1.2"" fill=""blue"" stroke-width=""0.6""/>
        //        <circle cx=""177.38"" cy=""198.64"" r=""1"" fill=""black"" />
        //        <circle cx=""205.73"" cy=""198.64"" r=""1"" fill=""black"" />
        //        <circle cx=""248.25"" cy=""255.33"" r=""1"" fill=""black"" />
        //        <circle cx=""219.9"" cy=""255.33"" r=""1"" fill=""black"" />
        //    </svg>";



        var tessOptions = new VectorUtils.TessellationOptions()
        {
            StepDistance         = 100.0f,
            MaxCordDeviation     = 0.5f,
            MaxTanAngleDeviation = 0.1f,
            SamplingStepSize     = 0.01f
        };

        //Pfad zur Datei
        string svgFilePath = Application.dataPath + "/Resources/testObject_layerTest-10-10.svg";

        StreamReader sr      = new StreamReader(svgFilePath);
        string       svgText = sr.ReadToEnd();

        print(svgText);
        sr.Close();
        sr.Dispose();

        var sceneInfo = SVGParser.ImportSVG(new StringReader(svgText));

        int NrOfLayers = sceneInfo.Scene.Root.Children.Count;

        m_Sprites = new Sprite[NrOfLayers];
        SVGParser.SceneInfo[]         m_SIArray = new SVGParser.SceneInfo[NrOfLayers];
        List <VectorUtils.Geometry>[] m_Geoms   = new List <VectorUtils.Geometry> [NrOfLayers];

        for (int i = 0; i < NrOfLayers; i++)
        {
            m_SIArray[i] = SVGParser.ImportSVG(new StringReader(svgText));
            int removed = 0;
            for (int c = 0; c < NrOfLayers; c++)
            {
                if (c != i)
                {
                    //print("at " + i + " removing index " + c);
                    m_SIArray[i].Scene.Root.Children.Remove(m_SIArray[i].Scene.Root.Children[c - removed]);
                    removed++;
                }
            }

            var fullBounds  = VectorUtils.SceneNodeBounds(sceneInfo.Scene.Root);
            var localBounds = VectorUtils.SceneNodeBounds(sceneInfo.Scene.Root.Children[i]);
            var pivot       = localBounds.position - fullBounds.position;

            var localSceneBounds = VectorUtils.SceneNodeBounds(m_SIArray[i].Scene.Root);

            Vector2 position = new Vector2(fullBounds.position.x, fullBounds.position.y);
            // position = new Vector2(fullBounds.center.x / fullBounds.width - (localBounds.position.x) / fullBounds.width, fullBounds.center.y / fullBounds.height - localBounds.position.y / fullBounds.height);
            //position = new Vector2((fullBounds.center.x - localBounds.position.x )/ fullBounds.width, 0);
            //position = new Vector2((fullBounds.position.x-localBounds.position.x-pivot.x) / fullBounds.width , 0);
            position = new Vector2(0, 0);

            print("FullBounds: " + fullBounds + " localBounds:" + localBounds);// + " localSceneBounds:"+ localSceneBounds);
            //print(i + ": " + position+" / pivot: "+pivot);

            //print(position.x * fullBounds.width + " , " + position.y * fullBounds.height);

            m_Geoms[i]   = VectorUtils.TessellateScene(m_SIArray[i].Scene, tessOptions);
            m_Sprites[i] = VectorUtils.BuildSprite(m_Geoms[i], 1000.0f, VectorUtils.Alignment.TopLeft, position, 128, true);

            GameObject     go = new GameObject();
            SpriteRenderer s  = go.AddComponent <SpriteRenderer>();
            go.transform.parent = transform;
            // go.transform.position = new Vector3((localSceneBounds.x - fullBounds.width/2f)/1000f, (fullBounds.y + fullBounds.height/2f - localSceneBounds.y) /1000f , 0);
            go.transform.position = new Vector3((localBounds.x) / 1000f, (fullBounds.y - localBounds.y) / 1000f, 0);
            s.sprite = m_Sprites[i];

            //var test = typeof(VectorUtils.TessellateScene);
            //var methods = test.GetMethods();

            //// test code: generate better shape
            //bool m_BetterGeneratePhysicsShape = true;
            //if (m_BetterGeneratePhysicsShape)
            //{
            //    var test = typeof(VectorUtils);
            //    var methods = test.GetMethods();
            //    foreach (MethodInfo mf in methods)
            //    {
            //        Debug.Log(mf.Name);
            //    }

            //    var physicsShapes = VectorUtils.TraceNodeHierarchyShapes(sceneInfo.Scene.Root, tessOptions);

            //    var rect = sceneInfo.SceneViewport;

            //    foreach (var vertices in physicsShapes)
            //    {
            //        if (rect == Rect.zero)
            //        {
            //            rect = VectorUtils.Bounds(vertices);
            //            VectorUtils.RealignVerticesInBounds(vertices, rect, flip: true);
            //        }
            //        else
            //        {
            //            VectorUtils.FlipVerticesInBounds(vertices, rect);
            //            VectorUtils.ClampVerticesInBounds(vertices, rect);
            //        }
            //    }

            //    m_Sprites[i].OverridePhysicsShape(physicsShapes);
            //}
            //// test code end

            go.AddComponent <PolygonCollider2D>();

            //PrefabUtility.SaveAsPrefabAsset(go, svgFilePath.Replace(".svg", "_2" + i.ToString() + ".prefab"));
        }



        //AssetImportContext ctx;

        //ctx.AddObjectToAsset();

        //var geoms = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions);

        //// Build a sprite with the tessellated geometry.
        //var sprite = VectorUtils.BuildSprite(geoms, 1000.0f, VectorUtils.Alignment.TopLeft, Vector2.zero, 128, true);
        //GetComponent<SpriteRenderer>().sprite = sprite;

        //GenerateSpriteAsset(ctx, sprite, name);
    }
 // Start is called before the first frame update
 void Start()
 {
     SVGParser.ImportSVG(svg, 0, 1, 100, 100, false);
 }
Beispiel #23
0
        /// <summary>
        /// Imports a vector texture
        /// </summary>
        /// <param name="file">The file to import from</param>
        /// <param name="size">The size of the texture</param>
        /// <param name="type"></param>
        /// <returns>The vector texture imported as a Sprite</returns>
        public static Sprite ImportVector(FileInfo file, int size, SpriteImportType type)
        {
            StreamReader reader = null;
            StringReader sr     = null;

            try
            {
                reader = new StreamReader(file.OpenRead());
                sr     = new StringReader(reader.ReadToEnd());
                SVGParser.SceneInfo scene = SVGParser.ImportSVG(sr);

                VectorUtils.TessellationOptions tessOptions = new VectorUtils.TessellationOptions()
                {
                    StepDistance         = 100.0f,
                    MaxCordDeviation     = 0.5f,
                    MaxTanAngleDeviation = 0.1f,
                    SamplingStepSize     = 0.01f
                };

                List <VectorUtils.Geometry> geoms = VectorUtils.TessellateScene(scene.Scene, tessOptions);
                Sprite tempSprite = VectorUtils.BuildSprite(geoms, size, VectorUtils.Alignment.Center, Vector2.zero, 64, false);

                Shader shader = null;
                switch (type)
                {
                case SpriteImportType.svggradient:
                    shader = Shader.Find("Unlit/VectorGradient");
                    break;

                case SpriteImportType.svg:
                default:
                    shader = Shader.Find("Unlit/Vector");
                    break;
                }

                Texture2D tex = VectorUtils.RenderSpriteToTexture2D(tempSprite, size, size, new Material(shader));
                //tex.alphaIsTransparency = true;
                Sprite sprite = Sprite.Create(tex, new Rect(Vector2.zero, new Vector2(tex.width, tex.height)), new Vector2(0.5f, 0.5f), size * 2);

                return(sprite);
            }

            catch (Exception e)
            {
                MonoBehaviour.print(e.Message + "\nFile: " + file.Name + "\n" + e.StackTrace);
            }

            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (sr != null)
                {
                    sr.Close();
                }
            }

            return(null);
        }
Beispiel #24
0
 public SVGGroupElement(SVGParser xmlImp,
                        SVGTransformList inheritTransformList,
                        SVGPaintable inheritPaintable) : base(xmlImp, inheritTransformList, inheritPaintable)
 {
     _name = attributeList.GetValue("id");
 }
Beispiel #25
0
    //public static Sprite[] m_Sprites;

    public static void ImportAsMesh(string svg, ref GameObject go)
    {
        // UnityEngine.XR.XRSettings.enabled = false;

        /*string svg =
         *  @"<svg width=""283.9"" height=""283.9"" xmlns=""http://www.w3.org/2000/svg"">
         *      <line x1=""170.3"" y1=""226.99"" x2=""177.38"" y2=""198.64"" fill=""none"" stroke=""#888"" stroke-width=""1""/>
         *      <line x1=""205.73"" y1=""198.64"" x2=""212.81"" y2=""226.99"" fill=""none"" stroke=""#888"" stroke-width=""1""/>
         *      <line x1=""212.81"" y1=""226.99"" x2=""219.9"" y2=""255.33"" fill=""none"" stroke=""#888"" stroke-width=""1""/>
         *      <line x1=""248.25"" y1=""255.33"" x2=""255.33"" y2=""226.99"" fill=""none"" stroke=""#888"" stroke-width=""1""/>
         *      <path d=""M170.08,226.77c7.09-28.34,35.43-28.34,42.52,0s35.43,28.35,42.52,0"" transform=""translate(0.22 0.22)"" fill=""none"" stroke=""red"" stroke-width=""1.2""/>
         *      <circle cx=""170.3"" cy=""226.99"" r=""1.2"" fill=""blue"" stroke-width=""0.6""/>
         *      <circle cx=""212.81"" cy=""226.99"" r=""1.2"" fill=""blue"" stroke-width=""0.6""/>
         *      <circle cx=""255.33"" cy=""226.99"" r=""1.2"" fill=""blue"" stroke-width=""0.6""/>
         *      <circle cx=""177.38"" cy=""198.64"" r=""1"" fill=""black"" />
         *      <circle cx=""205.73"" cy=""198.64"" r=""1"" fill=""black"" />
         *      <circle cx=""248.25"" cy=""255.33"" r=""1"" fill=""black"" />
         *      <circle cx=""219.9"" cy=""255.33"" r=""1"" fill=""black"" />
         *  </svg>";
         *
         */

        var tessOptions = new VectorUtils.TessellationOptions()
        {
            StepDistance         = 100.0f,
            MaxCordDeviation     = 0.5f,
            MaxTanAngleDeviation = 0.1f,
            SamplingStepSize     = 0.01f
        };

        //Pfad zur Datei
        //string svgFilePath = Application.dataPath+"/equation.svg";

        //StreamReader sr = new StreamReader(svgFilePath);
        //string svgText = sr.ReadToEnd();
        // print(svgText);
        // sr.Close();
        // sr.Dispose();

        // Dynamically import the SVG data, and tessellate the resulting vector scene.
        var sceneInfo = SVGParser.ImportSVG(new StringReader(svg));
        //var sceneInfo = SVGParser.ImportSVG(new StringReader(svgText));

        var geometryList = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions);

        var svgMesh = new Mesh();

        VectorUtils.FillMesh(svgMesh, geometryList, 100f, false);
        go.GetComponent <MeshFilter>().mesh = svgMesh;
        // go.GetComponent<MeshRenderer>().material = new Material(Shader.Find("Unlit/Vector"));


        /*
         * int NrOfLayers = sceneInfo.Scene.Root.Children.Count;
         *
         * m_Sprites = new Sprite[NrOfLayers];
         * SVGParser.SceneInfo[] m_SIArray = new SVGParser.SceneInfo[NrOfLayers];
         * List<VectorUtils.Geometry>[] m_Geoms = new List<VectorUtils.Geometry>[NrOfLayers];
         *
         * for (int i = 0; i < NrOfLayers; i++)
         * {
         *  m_SIArray[i] = SVGParser.ImportSVG(new StringReader(svgText));
         *  int removed = 0;
         *  for (int c = 0; c < NrOfLayers; c++)
         *  {
         *      if (c != i)
         *      {
         *          //print("at " + i + " removing index " + c);
         *          m_SIArray[i].Scene.Root.Children.Remove(m_SIArray[i].Scene.Root.Children[c - removed]);
         *          removed++;
         *      }
         *  }
         *
         *  var fullBounds = VectorUtils.SceneNodeBounds(sceneInfo.Scene.Root);
         *  var localBounds = VectorUtils.SceneNodeBounds(sceneInfo.Scene.Root.Children[i]);
         *  var pivot = localBounds.position - fullBounds.position;
         *
         *  var localSceneBounds = VectorUtils.SceneNodeBounds(m_SIArray[i].Scene.Root);
         *
         *
         *
         *  Vector2 position = new Vector2(fullBounds.position.x, fullBounds.position.y);
         *  // position = new Vector2(fullBounds.center.x / fullBounds.width - (localBounds.position.x) / fullBounds.width, fullBounds.center.y / fullBounds.height - localBounds.position.y / fullBounds.height);
         *  //position = new Vector2((fullBounds.center.x - localBounds.position.x )/ fullBounds.width, 0);
         *  //position = new Vector2((fullBounds.position.x-localBounds.position.x-pivot.x) / fullBounds.width , 0);
         *  position = new Vector2(0, 0);
         *
         *  print("FullBounds: " + fullBounds + " localBounds:" + localBounds);// + " localSceneBounds:"+ localSceneBounds);
         *  //print(i + ": " + position+" / pivot: "+pivot);
         *
         *  //print(position.x * fullBounds.width + " , " + position.y * fullBounds.height);
         *
         *  m_Geoms[i] = VectorUtils.TessellateScene(m_SIArray[i].Scene, tessOptions);
         *  m_Sprites[i] = VectorUtils.BuildSprite(m_Geoms[i], 1000.0f, VectorUtils.Alignment.TopLeft, position, 128, true);
         *
         *  GameObject go = new GameObject();
         *  SpriteRenderer s = go.AddComponent<SpriteRenderer>();
         *  go.transform.parent = transform;
         *  // go.transform.position = new Vector3((localSceneBounds.x - fullBounds.width/2f)/1000f, (fullBounds.y + fullBounds.height/2f - localSceneBounds.y) /1000f , 0);
         *  go.transform.position = new Vector3((localBounds.x) / 1000f, (fullBounds.y - localBounds.y) / 1000f, 0);
         *  s.sprite = m_Sprites[i];
         * }
         */


        /*
         *
         * for (int i = 0; i < sceneInfo.Scene.Root.Children.Count; i++)
         * {
         *  print("ChildList: " + i + " " + sceneInfo.Scene.Root.Children[i]);
         *
         *  SceneNode activeNode = sceneInfo.Scene.Root.Children[i];
         *  while (activeNode.Drawables==null)
         *  {
         *      activeNode = activeNode.Children[0];
         *  }
         *
         *
         *  for (int d = 0; d < activeNode.Drawables.Count; d++)
         *  {
         *      IDrawable element = activeNode.Drawables[d];
         *      //print(element.GetType());
         *      if (element.GetType()== typeof(Unity.VectorGraphics.Path))
         *      {
         *          Unity.VectorGraphics.Path p = (Unity.VectorGraphics.Path) element;
         *          print(p.PathProps.Stroke.Color);
         *      }
         *      if (element.GetType() == typeof(Unity.VectorGraphics.Shape))
         *      {
         *          Unity.VectorGraphics.Shape s = (Unity.VectorGraphics.Shape)element;
         *
         *          SolidFill sf = (SolidFill)s.Fill;
         *          print(sf.Color);
         *      }
         *
         *      print("ChildList: " + i + " " + activeNode.Drawables[d]);
         *  }
         *
         *
         * }*/

        /*
         * var geoms = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions);
         *
         * // Build a sprite with the tessellated geometry.
         * var sprite = VectorUtils.BuildSprite(geoms, 1000.0f, VectorUtils.Alignment.TopLeft, Vector2.zero, 128, true);
         * GetComponent<SpriteRenderer>().sprite = sprite;
         */
    }
Beispiel #26
0
    static void SvgLayerImporter(string assetPath)
    {
        var originalSvgPathFull = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf("/") + 1) + assetPath;

        var sceneInfo = SVGParser.ImportSVG(File.OpenText(originalSvgPathFull));

        if (null == sceneInfo.Scene)
        {
            Debug.LogError("Could not parse SVG at " + originalSvgPathFull + "!");
        }
        else
        {
            Debug.Log("Custom import: " + originalSvgPathFull);

            // this could probably stand to be specified elsewhere
            var tessOptions = new VectorUtils.TessellationOptions()
            {
                StepDistance         = 100.0f,
                MaxCordDeviation     = 0.5f,
                MaxTanAngleDeviation = 0.1f,
                SamplingStepSize     = 0.01f
            };

            // duplicate the original SVG prefab and create a GameObject that will serve as a pretend "instance" of that prefab
            var newPrefabLocation = assetPath.Replace(".svg", "_Split.prefab");
            //var ob = new GameObject("111");
            //PrefabUtility.SaveAsPrefabAsset(ob, newPrefabLocation);

            var newSceneInfo = SVGParser.ImportSVG(File.OpenText(originalSvgPathFull));
            var geom         = VectorUtils.TessellateScene(newSceneInfo.Scene, tessOptions);
            var newSprite    = VectorUtils.BuildSprite(geom, 10.0f, VectorUtils.Alignment.SVGOrigin, Vector2.zero, 128, true);

            var            ob             = new GameObject("111");
            SpriteRenderer spriteRenderer = ob.AddComponent <SpriteRenderer>();
            spriteRenderer.sprite = newSprite;

            //PrefabUtility.CreatePrefab(newPrefabLocation, ob);
            //PrefabUtility.SaveAsPrefabAsset(ob, newPrefabLocation);
            //AssetDatabase.ImportAsset(newPrefabLocation);
            //AssetDatabase.
            //Debug.Log(newSprite.bounds);
            //AssetDatabase.AddObjectToAsset(newSprite, newPrefabLocation);
            //AssetDatabase.SaveAssets();

            //AssetDatabase.CreateAsset(newSprite, assetPath.Replace(".svg", "_test.prefab"));
            //AssetDatabase.SaveAssets();

            //PrefabUtility.CreatePrefab(assetPath.Replace(".svg", "_test.prefab"), ob);
            ////AssetDatabase.CreateAsset(ob, assetPath.Replace(".svg", "_test.prefab"));
            //AssetDatabase.AddObjectToAsset(newSprite, assetPath.Replace(".svg", "_test.prefab"));
            //AssetDatabase.SaveAssets();
            //Sprite t = (Sprite)AssetDatabase.LoadAssetAtPath(assetPath.Replace(".svg", "_test.prefab"), typeof(Sprite));
            //Debug.Log(t.bounds);

            //AssetDatabase.AddObjectToAsset(newSprite, ob);
            //PrefabUtility.SaveAsPrefabAsset(ob, newPrefabLocation);

            //PrefabUtility.CreateEmptyPrefab(newPrefabLocation);
            //var newPrefab = AssetDatabase.LoadAssetAtPath<GameObject>(newPrefabLocation);
            //Debug.Log(newPrefab);
            //var instPrefab = new GameObject();

            /*
             * // go through each layer of the SVG, and in each layer, remove SVG info nodes that are *not* in that layer
             * int numOriginalLayers = sceneInfo.Scene.Root.Children.Count;
             * for (int i = 0; i < numOriginalLayers; ++i)
             * {
             *  var newSceneInfo = SVGParser.ImportSVG(File.OpenText(originalSvgPathFull));
             *  int removed = 0;
             *  var layerName = "";
             *  for (int c = 0; c < numOriginalLayers; ++c)
             *  {
             *      if (c == i)
             *      {
             *          layerName = "Layer " + c;
             *      }
             *      else
             *      {
             *          newSceneInfo.Scene.Root.Children.Remove(newSceneInfo.Scene.Root.Children[c - removed]);
             ++removed;
             *      }
             *  }
             *
             *  // instantiate the current layer as a new sprite in the scene, and attach it to our new prefab which will soon be saved to disk
             *  var geom = VectorUtils.TessellateScene(newSceneInfo.Scene, tessOptions);
             *  var newSprite = VectorUtils.BuildSprite(geom, 10.0f, VectorUtils.Alignment.SVGOrigin, Vector2.zero, 128, true);
             *  newSprite.name = layerName;
             *
             *  // each SVG layer will have a corresponding GameObject that's part of the new prefab
             *  GameObject go = new GameObject(layerName);
             *  SpriteRenderer s = go.AddComponent<SpriteRenderer>();
             *  s.sprite = newSprite;
             *  go.transform.SetParent(instPrefab.transform);
             *
             *  // bundle the new sprite (for this layer) in with the new SVG prefab
             *  AssetDatabase.AddObjectToAsset(newSprite, newPrefab);
             * }
             *
             * // now apply the changes from the instantiated prefab to the saved prefab on disk, and destroy the instance
             * PrefabUtility.ReplacePrefab(instPrefab, newPrefab, ReplacePrefabOptions.ReplaceNameBased);
             * Object.DestroyImmediate(instPrefab);
             */
        }

        return;
    }
Beispiel #27
0
 public SVGDocument(string originalDocument, SVGGraphics r)
 {
     parser  = new SVGParser(originalDocument);
     _render = r;
 }
        public void TestCombo()
        {
            var map = BasicMap();

            var timer = new System.Diagnostics.Stopwatch();

            timer.Start();

            var heightmap = new SimplifiedHeightmap(512, map);

            heightmap.BuildSecondDerivative();
            heightmap.GenerateFullTree();
            heightmap.GenerateMesh();

            timer.Stop();
            Console.WriteLine("!!! Heightmap took " + timer.ElapsedMilliseconds + "ms.");
            timer.Restart();

            var svg   = new SVGParser(File.ReadAllText(@"C:\Users\Rhys\Documents\roads.svg"));
            var paths = svg.ToLinePaths();

            var geom = new RoadGeometry(paths, TS1RoadTemplates.OLD_TOWN_DEFAULT_TEMPLATES);

            geom.GenerateIntersections();
            geom.GenerateRoadGeometry();

            timer.Stop();
            Console.WriteLine("!!! Road took " + timer.ElapsedMilliseconds + "ms.");
            timer.Restart();

            List <MeshProjector> projectors = new List <MeshProjector>();

            foreach (var pair in geom.Meshes)
            {
                var mesh = pair.Value;

                var baseTris = new List <BaseMeshTriangle>();
                for (int i = 0; i < heightmap.Indices.Count; i += 3)
                {
                    baseTris.Add(new BaseMeshTriangle()
                    {
                        Vertices = new Vector3[] {
                            heightmap.Vertices[heightmap.Indices[i]],
                            heightmap.Vertices[heightmap.Indices[i + 1]],
                            heightmap.Vertices[heightmap.Indices[i + 2]],
                        }
                    });
                }

                var projTris = new List <MeshTriangle>();
                for (int i = 0; i < mesh.Indices.Count; i += 3)
                {
                    projTris.Add(new MeshTriangle()
                    {
                        Vertices = new Vector3[] {
                            mesh.Vertices[mesh.Indices[i]].Position,
                            mesh.Vertices[mesh.Indices[i + 1]].Position,
                            mesh.Vertices[mesh.Indices[i + 2]].Position,
                        },
                        TexCoords = new float[][]
                        {
                            mesh.Vertices[mesh.Indices[i]].TexCoords,
                            mesh.Vertices[mesh.Indices[i + 1]].TexCoords,
                            mesh.Vertices[mesh.Indices[i + 2]].TexCoords,
                        }
                    });
                }

                var proj = new MeshProjector(baseTris, projTris);
                proj.Project();
                projectors.Add(proj);
            }

            timer.Stop();
            Console.WriteLine("!!! Projection took " + timer.ElapsedMilliseconds + "ms.");

            //write result
            using (var file = File.Open(@"C:\Users\Rhys\Documents\combined.obj", FileMode.Create))
            {
                SaveResults(projectors, file);
            }
        }
Beispiel #29
0
    static void SvgLayerImporterModified(string assetPath)
    {
        var originalSvgPathFull = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf("/") + 1) + assetPath;

        var sceneInfo = SVGParser.ImportSVG(File.OpenText(originalSvgPathFull));

        if (null == sceneInfo.Scene)
        {
            Debug.LogError("Could not parse SVG at " + originalSvgPathFull + "!");
        }
        else
        {
            Debug.Log("Custom import: " + originalSvgPathFull);

            var tessOptions = new VectorUtils.TessellationOptions()
            {
                StepDistance         = 100.0f,
                MaxCordDeviation     = 0.5f,
                MaxTanAngleDeviation = 0.1f,
                SamplingStepSize     = 0.01f
            };

            var newPrefabLocation = assetPath.Replace(".svg", "_Split.prefab");
            var parentObj         = new GameObject("testObject");

            int numOriginalLayers = sceneInfo.Scene.Root.Children.Count;

            var objs    = new GameObject[numOriginalLayers];
            var sprites = new Sprite[numOriginalLayers];

            //for (int i = 0; i < numOriginalLayers; i++)
            //{
            //    objs[i] = new GameObject(numOriginalLayers.ToString());

            //}

            for (int i = 0; i < numOriginalLayers; i++)
            {
                var newSceneInfo = sceneInfo;
                int removed      = 0;
                var layerName    = "";

                for (int c = 0; c < numOriginalLayers; c++)
                {
                    if (c == i)
                    {
                        layerName = "Layer " + c;
                    }
                    else
                    {
                        if (c - removed >= 0 && c - removed < newSceneInfo.Scene.Root.Children.Count)
                        {
                            newSceneInfo.Scene.Root.Children.Remove(newSceneInfo.Scene.Root.Children[c - removed]);
                        }

                        ++removed;
                    }
                }

                // instantiate the current layer as a new sprite in the scene, and attach it to our new prefab which will soon be saved to disk
                var geom = VectorUtils.TessellateScene(newSceneInfo.Scene, tessOptions);
                sprites[i]      = VectorUtils.BuildSprite(geom, 10.0f, VectorUtils.Alignment.SVGOrigin, Vector2.zero, 128, true);
                sprites[i].name = layerName;

                // each SVG layer will have a corresponding GameObject that's part of the new prefab
                //GameObject go = new GameObject(layerName);
                objs[i] = new GameObject(layerName);
                SpriteRenderer s = objs[i].AddComponent <SpriteRenderer>();
                s.sprite = sprites[i];
                objs[i].transform.SetParent(parentObj.transform);
                Debug.Log(objs[i].GetComponent <SpriteRenderer>().sprite.bounds);
                Debug.Log(sprites[i].name + sprites[i].bounds);

                //AssetDatabase.AddObjectToAsset(sprites[i].texture, objs[i]);
                var tempPath = assetPath.Replace(".svg", "_" + i.ToString() + ".prefab");
                PrefabUtility.SaveAsPrefabAsset(objs[i], tempPath);

                AssetDatabase.ImportAsset(tempPath);
                AssetDatabase.AddObjectToAsset(sprites[i], objs[i]);
                AssetDatabase.SaveAssets();
            }

            // now apply the changes from the instantiated prefab to the saved prefab on disk, and destroy the instance
            Debug.Log(parentObj.transform.childCount);


            PrefabUtility.SaveAsPrefabAsset(parentObj, newPrefabLocation);
            //PrefabUtility.SaveAsPrefabAsset(instPrefab, newPrefabLocation);

            for (int i = 0; i < objs.Length; i++)
            {
                Debug.Log(objs[i].name);
                Debug.Log(objs[i].GetComponent <SpriteRenderer>().sprite.bounds);
            }

            Object.DestroyImmediate(parentObj);
        }

        return;
    }
Beispiel #30
0
    /// <summary>
    /// Create a Texture2D icon of a SVG image (editor only version).
    /// </summary>
    /// <param name="svg">String containing svg content.</param>
    /// <param name="renderUtil">PreviewRenderUtility to use for drawing</param>
    /// <remarks>
    /// Standard header and footer will be included if not found in svgContent
    /// </remarks>
    public static Texture2D GetIcon(string svgContent, PreviewRenderUtility renderUtil)
    {
        string svg;

        if (svgContent.StartsWith("<?xml version = \"1.0\" encoding=\"UTF - 8\"?>"))
        {
            svg = svgContent;
        }
        else
        {
            svg = svgIconHeader + svgContent;
        }

        if (!svg.EndsWith(svgIconFooter))
        {
            svg = svg + svgIconFooter;
        }

        // Parse the SVG
        SVGParser.SceneInfo sceneInfo = SVGParser.ImportSVG(new System.IO.StringReader(svg));
        int width  = Mathf.CeilToInt(sceneInfo.SceneViewport.width);
        int height = Mathf.CeilToInt(sceneInfo.SceneViewport.height);

        if ((width > 64) || (height > 64))
        {
            Debug.LogWarning("SVG icon of unusual size!");
        }

        // Save the render state and get a temporary render texture
        RenderTexture activeTexture = RenderTexture.active;

        renderUtil.camera.targetTexture   = RenderTexture.GetTemporary(width * 2, height * 2, 8, RenderTextureFormat.ARGB32);
        renderUtil.camera.backgroundColor = Color.clear;

        // Generate the mesh
        Mesh iconMesh = new Mesh();
        List <VectorUtils.Geometry> iconGeometry = VectorUtils.TessellateScene(sceneInfo.Scene, tessellationOptions);

        VectorUtils.FillMesh(iconMesh, iconGeometry, 1f);

        // Activate the render texture and draw the mesh into it
        RenderTexture.active = renderUtil.camera.targetTexture;
        float   cameraSize     = renderUtil.camera.orthographicSize;
        Vector3 cameraPosition = renderUtil.camera.transform.position;

        renderUtil.camera.orthographicSize   = sceneInfo.SceneViewport.height / 2;
        renderUtil.camera.transform.position = new Vector3(sceneInfo.SceneViewport.center.x, sceneInfo.SceneViewport.center.y, -1);
        // HACK until FillMesh() flpYAxis is fixed
        renderUtil.camera.transform.Rotate(0, 0, 180f);
        renderUtil.DrawMesh(iconMesh, Matrix4x4.identity, renderMaterial, 0);
        renderUtil.camera.Render();
        renderUtil.camera.transform.Rotate(0, 0, 180f);
        renderUtil.camera.orthographicSize   = cameraSize;
        renderUtil.camera.transform.position = cameraPosition;
        Texture2D iconTexture = new Texture2D(width * 2, height * 2);

        iconTexture.ReadPixels(new Rect(0, 0, width * 2, height * 2), 0, 0);
        iconTexture.Apply();

        // Restore the render state and release the temporary objects
        RenderTexture.active = activeTexture;
        RenderTexture.ReleaseTemporary(renderUtil.camera.targetTexture);
        UnityEngine.Object.DestroyImmediate(iconMesh);

        return(iconTexture);
    }
Beispiel #31
0
        public void StartProcess(SVGAsset asset)
        {
            if (UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
            {
                return;
            }

            if (errors == null)
            {
                errors = new List <SVGError>();
            }
            else
            {
                errors.Clear();
            }
            _importingSVG = true;

            System.Reflection.FieldInfo _editor_runtimeMaterials = typeof(SVGAsset).GetField("_runtimeMaterials", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            _editor_runtimeMaterials.SetValue(asset, null);

            System.Reflection.FieldInfo _editor_runtimeMesh = typeof(SVGAsset).GetField("_runtimeMesh", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            _editor_runtimeMesh.SetValue(asset, null);

            UnityEditor.SerializedObject   svgAsset      = new UnityEditor.SerializedObject(asset);
            UnityEditor.SerializedProperty sharedMesh    = svgAsset.FindProperty("_sharedMesh");
            UnityEditor.SerializedProperty sharedShaders = svgAsset.FindProperty("_sharedShaders");

            Clear();
            SVGParser.Init();
            SVGGraphics.Init();
            atlasData = new SVGAtlasData();
            atlasData.Init(SVGAtlas.defaultAtlasTextureWidth * SVGAtlas.defaultAtlasTextureHeight);
            atlasData.AddGradient(SVGAtlasData.GetDefaultGradient());
            SVGElement _rootSVGElement = null;

#if IGNORE_EXCEPTIONS
            try {
#else
            Debug.LogWarning("Exceptions are turned on!");
#endif
                // Create new Asset
                CreateEmptySVGDocument();
                _rootSVGElement = this._svgDocument.rootElement;
#if IGNORE_EXCEPTIONS
            } catch (System.Exception exception) {
                _rootSVGElement = null;
                errors.Add(SVGError.Syntax);
                Debug.LogError("SVG Document Exception: " + exception.Message, asset);
            }
#endif

                if (_rootSVGElement == null)
                {
                    Debug.LogError("SVG Document is corrupted! " + UnityEditor.AssetDatabase.GetAssetPath(asset), asset);
                    _importingSVG = false;
                    return;
                }

#if IGNORE_EXCEPTIONS
                try {
#endif
                _rootSVGElement.Render();

                Rect viewport = _rootSVGElement.paintable.viewport;
                viewport.x    *= SVGAssetImport.meshScale;
                viewport.y    *= SVGAssetImport.meshScale;
                viewport.size *= SVGAssetImport.meshScale;

                Vector2 offset;
                SVGGraphics.CorrectSVGLayers(SVGGraphics.layers, viewport, asset, out offset);

                // Handle gradients
                bool hasGradients = false;

                // Create actual Mesh
                Shader[] outputShaders;
                Mesh mesh = new Mesh();
                SVGMesh.CombineMeshes(SVGGraphics.layers.ToArray(), mesh, out outputShaders, useGradients, format, compressDepth, asset.antialiasing);
                if (mesh == null)
                {
                    return;
                }

                if (useGradients == SVGUseGradients.Always)
                {
                    if (outputShaders != null)
                    {
                        for (int i = 0; i < outputShaders.Length; i++)
                        {
                            if (outputShaders[i] == null)
                            {
                                continue;
                            }
                            if (outputShaders[i].name == SVGShader.SolidColorOpaque.name)
                            {
                                outputShaders[i] = SVGShader.GradientColorOpaque;
                            }
                            else if (outputShaders[i].name == SVGShader.SolidColorAlphaBlended.name)
                            {
                                outputShaders[i] = SVGShader.GradientColorAlphaBlended;
                            }
                            else if (outputShaders[i].name == SVGShader.SolidColorAlphaBlendedAntialiased.name)
                            {
                                outputShaders[i] = SVGShader.GradientColorAlphaBlendedAntialiased;
                            }
                        }
                    }
                    hasGradients = true;
                }
                else
                {
                    if (outputShaders != null)
                    {
                        for (int i = 0; i < outputShaders.Length; i++)
                        {
                            if (outputShaders[i] == null)
                            {
                                continue;
                            }
                            if (outputShaders[i].name == SVGShader.GradientColorOpaque.name ||
                                outputShaders[i].name == SVGShader.GradientColorAlphaBlended.name ||
                                outputShaders[i].name == SVGShader.GradientColorAlphaBlendedAntialiased.name ||
                                outputShaders[i].name == SVGShader.GradientColorAlphaBlendedAntialiasedCompressed.name)
                            {
                                hasGradients = true;
                                break;
                            }
                        }
                    }
                }

                if (!asset.useLayers)
                {
                    sharedMesh.objectReferenceValue = AddObjectToAsset <Mesh>(mesh, asset, HideFlags.HideInHierarchy);
                }

//                Material sharedMaterial;
                if (outputShaders != null && outputShaders.Length > 0)
                {
                    sharedShaders.arraySize = outputShaders.Length;
                    if (hasGradients)
                    {
                        for (int i = 0; i < outputShaders.Length; i++)
                        {
                            sharedShaders.GetArrayElementAtIndex(i).stringValue = outputShaders[i].name;
                        }
                    }
                    else
                    {
                        for (int i = 0; i < outputShaders.Length; i++)
                        {
                            if (outputShaders[i].name == SVGShader.GradientColorAlphaBlended.name)
                            {
                                outputShaders[i] = SVGShader.SolidColorAlphaBlended;
                            }
                            else if (outputShaders[i].name == SVGShader.GradientColorOpaque.name)
                            {
                                outputShaders[i] = SVGShader.SolidColorOpaque;
                            }
                            sharedShaders.GetArrayElementAtIndex(i).stringValue = outputShaders[i].name;
                        }
                    }
                }

                // Serialize the Asset
                svgAsset.ApplyModifiedProperties();

                // Handle Canvas Rectangle
                System.Reflection.MethodInfo _editor_SetCanvasRectangle = typeof(SVGAsset).GetMethod("_editor_SetCanvasRectangle", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                _editor_SetCanvasRectangle.Invoke(asset, new object[] { new Rect(viewport.x, viewport.y, viewport.size.x, viewport.size.y) });

                if (asset.generateCollider)
                {
                    // Create polygon contour
                    if (SVGGraphics.paths != null && SVGGraphics.paths.Count > 0)
                    {
                        List <List <Vector2> > polygons = new List <List <Vector2> >();
                        for (int i = 0; i < SVGGraphics.paths.Count; i++)
                        {
                            Vector2[] points = SVGGraphics.paths[i].points;
                            for (int j = 0; j < points.Length; j++)
                            {
                                points[j].x = points[j].x * SVGAssetImport.meshScale - offset.x;
                                points[j].y = (points[j].y * SVGAssetImport.meshScale + offset.y) * -1f;
                            }

                            polygons.Add(new List <Vector2>(points));
                        }

                        polygons = SVGGeom.MergePolygon(polygons);

                        SVGPath[] paths = new SVGPath[polygons.Count];
                        for (int i = 0; i < polygons.Count; i++)
                        {
                            paths[i] = new SVGPath(polygons[i].ToArray());
                        }

                        System.Reflection.MethodInfo _editor_SetColliderShape = typeof(SVGAsset).GetMethod("_editor_SetColliderShape", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                        if (paths != null && paths.Length > 0)
                        {
                            _editor_SetColliderShape.Invoke(asset, new object[] { paths });
                        }
                        else
                        {
                            _editor_SetColliderShape.Invoke(asset, new object[] { null });
                        }
                    }
                }
                else
                {
                    System.Reflection.MethodInfo _editor_SetColliderShape = typeof(SVGAsset).GetMethod("_editor_SetColliderShape", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                    _editor_SetColliderShape.Invoke(asset, new object[] { null });
                }

                System.Reflection.MethodInfo _editor_SetGradients = typeof(SVGAsset).GetMethod("_editor_SetGradients", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                _editor_SetGradients.Invoke(asset, new object[] { null });
                if (hasGradients)
                {
                    if (atlasData.gradientCache != null && atlasData.gradientCache.Count > 0)
                    {
                        int          gradientsCount = SVGAssetImport.atlasData.gradientCache.Count;
                        CCGradient[] gradients      = new CCGradient[gradientsCount];
                        int          i = 0;
                        foreach (KeyValuePair <string, CCGradient> entry in SVGAssetImport.atlasData.gradientCache)
                        {
                            gradients[i++] = entry.Value;
                        }
                        _editor_SetGradients.Invoke(asset, new object[] { gradients });
                    }
                }

                System.Reflection.MethodInfo _editor_SetLayers = typeof(SVGAsset).GetMethod("_editor_SetLayers", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                _editor_SetLayers.Invoke(asset, new object[] { null });
                if (asset.useLayers)
                {
                    if (SVGGraphics.layers != null && SVGGraphics.layers.Count > 0)
                    {
                        _editor_SetLayers.Invoke(asset, new object[] { SVGGraphics.layers.ToArray() });
                    }
                }

#if IGNORE_EXCEPTIONS
            } catch (System.Exception exception) {
                Debug.LogWarning("Asset: " + UnityEditor.AssetDatabase.GetAssetPath(asset) + " Failed to import\n" + exception.Message, asset);
                errors.Add(SVGError.CorruptedFile);
            }
#endif
                if (_svgDocument != null)
                {
                    _svgDocument.Clear();
                    _svgDocument = null;
                }
                Clear();

                UnityEditor.EditorUtility.SetDirty(asset);
                _importingSVG = false;
            }
    public override void OnImportAsset(AssetImportContext ctx)
    {
        // We're using a hardcoded window size of 100x100. This way, using a pixels per point value of 100
        // results in a sprite of size 1 when the SVG file has a viewbox specified.
        SVGParser.SceneInfo sceneInfo;
        using (StreamReader stream = new StreamReader(ctx.assetPath))
        {
            sceneInfo = SVGParser.ImportSVG(stream, 0, 1, 100, 100, PreserveViewport);
        }

        if (sceneInfo.Scene == null || sceneInfo.Scene.Root == null)
        {
            throw new Exception("Wowzers!");
        }

        float stepDist         = StepDistance;
        float samplingStepDist = SamplingStepDistance;
        float maxCord          = MaxCordDeviationEnabled ? MaxCordDeviation : float.MaxValue;
        float maxTangent       = MaxTangentAngleEnabled ? MaxTangentAngle : Mathf.PI * 0.5f;

        if (!AdvancedMode)
        {
            // Automatically compute sensible tessellation options from the
            // vector scene's bouding box and target resolution
            ComputeTessellationOptions(sceneInfo, TargetResolution, ResolutionMultiplier, out stepDist, out maxCord, out maxTangent);
        }

        var tessOptions = new ShapeUtils.TessellationOptions();

        tessOptions.MaxCordDeviation     = maxCord;
        tessOptions.MaxTanAngleDeviation = maxTangent;
        tessOptions.SamplingStepSize     = 1.0f / (float)samplingStepDist;
        tessOptions.StepDistance         = stepDist;

        var rect = Rect.zero;

        if (PreserveViewport)
        {
            rect = sceneInfo.SceneViewport;
        }

        var geometry = ShapeUtils.TessellateScene(sceneInfo.Scene, tessOptions, sceneInfo.NodeOpacity);

        string name = System.IO.Path.GetFileNameWithoutExtension(ctx.assetPath);

        var gameObject = new GameObject("Shape" + name, typeof(MeshFilter), typeof(MeshRenderer));

        var mesh = new Mesh();

        mesh.name = "Mesh" + name;
        CalculateSideExtrusion(mesh, geometry);

        mesh.RecalculateBounds();
        mesh.RecalculateNormals();

        var mat = new Material(Shader.Find("Standard"));

        mat.name = "Material" + name;

        gameObject.GetComponent <MeshFilter>().mesh       = mesh;
        gameObject.GetComponent <MeshRenderer>().material = mat;

        ctx.AddObjectToAsset("shape", gameObject);
        ctx.AddObjectToAsset("mesh", mesh);
        ctx.AddObjectToAsset("material", mat);
        ctx.SetMainObject(gameObject);
    }
Beispiel #33
0
        /// <summary>Imports an SVG asset</summary>
        /// <param name="ctx">The asset import context of the scripted importer</param>
        public override void OnImportAsset(AssetImportContext ctx)
        {
            UpdateProperties();

            // We're using a hardcoded window size of 100x100. This way, using a pixels per point value of 100
            // results in a sprite of size 1 when the SVG file has a viewbox specified.
            SVGParser.SceneInfo sceneInfo;
            using (var stream = new StreamReader(ctx.assetPath))
                sceneInfo = SVGParser.ImportSVG(stream, ViewportOptions, 0, 1, 100, 100);

            if (sceneInfo.Scene == null || sceneInfo.Scene.Root == null)
            {
                throw new Exception("Wowzers!");
            }

            float stepDist         = StepDistance;
            float samplingStepDist = SamplingStepDistance;
            float maxCord          = MaxCordDeviationEnabled ? MaxCordDeviation : float.MaxValue;
            float maxTangent       = MaxTangentAngleEnabled ? MaxTangentAngle : Mathf.PI * 0.5f;

            if (!AdvancedMode)
            {
                // Automatically compute sensible tessellation options from the
                // vector scene's bouding box and target resolution
                ComputeTessellationOptions(sceneInfo, TargetResolution, ResolutionMultiplier, out stepDist, out maxCord, out maxTangent);
            }

            var tessOptions = new VectorUtils.TessellationOptions();

            tessOptions.MaxCordDeviation     = maxCord;
            tessOptions.MaxTanAngleDeviation = maxTangent;
            tessOptions.SamplingStepSize     = 1.0f / (float)samplingStepDist;
            tessOptions.StepDistance         = stepDist;

            var rect = Rect.zero;

            if (ViewportOptions == ViewportOptions.PreserveViewport)
            {
                rect = sceneInfo.SceneViewport;
            }

            var    geometry = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions, sceneInfo.NodeOpacity);
            var    name     = System.IO.Path.GetFileNameWithoutExtension(ctx.assetPath);
            Sprite sprite   = null;

            switch (SvgType)
            {
            case SVGType.VectorSprite:
                sprite = BuildSpriteFromGeometry(geometry, rect);
                GenerateSpriteAsset(ctx, sprite, name);
                break;

            case SVGType.UISVGImage:
                sprite = BuildSpriteFromGeometry(geometry, rect);
                GenerateUGUISpriteAsset(ctx, sprite, name);
                break;

            case SVGType.TexturedSprite:
                sprite = BuildSpriteFromGeometry(geometry, rect);
                GenerateTexturedSpriteAsset(ctx, sprite, name);
                break;

            case SVGType.Texture2D:
                sprite = BuildSpriteFromGeometry(geometry, rect);
                GenerateTexture2DAsset(ctx, sprite, name);
                break;

#if UNITY_2019_3_OR_NEWER
            case SVGType.UIToolkit:
                GenerateVectorImageAsset(ctx, geometry, name);
                break;
#endif
            default:
                break;
            }
        }
Beispiel #34
0
    // Start is called before the first frame update
    void Start()
    {
        string path = string.Format(@"D:\WriteByHand\svgs\{0}.svg", 20986);
        string svg  = SVGHelper.readSVG(path);

        SVGParser.SceneInfo scene_info = SVGParser.ImportSVG(new StringReader(svg));
        scene = scene_info.Scene;

        // svg 本體
        SceneNode        node   = scene.Root;
        List <SceneNode> layer1 = node.Children;

        // node0:背景米字;node1:字的筆劃
        SceneNode node0 = layer1[0], node1 = layer1[1];

        // 背景米字
        //List<SceneNode> layer2 = node0.Children;
        //print("layer2:" + layer2.Count);

        // 字的筆劃
        List <SceneNode> layer3 = node1.Children;

        //print("layer3:" + layer3.Count);
        //int n = 0;
        //foreach (SceneNode scene_node in layer3)
        //{
        //    print(string.Format("=== Node {0} ===", ++n));
        //    List<Shape> shapes = scene_node.Shapes; // length = 1
        //    Shape shape = shapes[0]; // length = 1
        //    BezierContour[] contours = shape.Contours; // length = 1
        //    BezierPathSegment[] segments = contours[0].Segments; // 每一筆劃的區段數量不同
        //    int num = 0;
        //    foreach(BezierPathSegment bezierPathSegment in segments)
        //    {
        //        print(string.Format("= segment {0} =", ++num));
        //        print(bezierPathSegment.P0);
        //        print(bezierPathSegment.P1);
        //        print(bezierPathSegment.P2);
        //        break;
        //    }

        //    SceneNode clipper = (scene_node.Clipper == null) ? null : scene_node.Clipper;
        //    if(clipper != null)
        //    {
        //        List<SceneNode> clippers = clipper.Children; // length = 1
        //        SceneNode mask = clippers[0];
        //        List<Shape> m_shapes = mask.Shapes; // length = 1
        //        Shape m_shape = m_shapes[0];
        //        BezierContour[] m_contours = m_shape.Contours; // length = 1
        //        //print("m_contours len:" + m_contours.Length);
        //        BezierPathSegment[] m_segments = m_contours[0].Segments; // 每一筆劃的區段數量不同
        //        //print("m_segments len:" + m_segments.Length);
        //        int number = 0;
        //        foreach (BezierPathSegment m_bezierPathSegment in m_segments)
        //        {
        //            print(string.Format("= clipper segment {0} =", ++number));
        //            print(m_bezierPathSegment.P0);
        //            print(m_bezierPathSegment.P1);
        //            print(m_bezierPathSegment.P2);
        //            break;
        //        }
        //    }
        //    else
        //    {
        //        print("clipper is null");
        //    }
        //}

        n_scene = new Scene()
        {
            Root = new SceneNode()
            {
                // node.Children  正常的字
                // node1.Children  上下相反的字
                //Children = node.Children
                Children = new List <SceneNode>()
                {
                    new SceneNode()
                    {
                        Children = node1.Children
                    }
                }
            }
        };


        //foreach (SceneNode sceneNode in layer3)
        //{
        //    n_scene.Root.Children.Add(sceneNode);
        //}

        sceneDisplay(n_scene, render);

        //StartCoroutine(nextStroke(layer3));
    }