Ejemplo n.º 1
0
        public void Pack(ref int targetWidth, int targetHeight, int padding, bool correctPow2)
        {
            if ((padding % 2) != 0)
            {
                Debug.LogWarning("Padding not an even number");
                padding++;
            }
            int num = targetHeight;

            for (int i = 0; i < this.nodes.Count; i++)
            {
                TextureNode node = this.nodes[i];
                node.packedRect.x      = 0f;
                node.packedRect.y      = 0f;
                node.packedRect.width  = Mathf.Round(node.sourceRect.width * node.scale.x);
                node.packedRect.height = Mathf.Min((float)num, Mathf.Round(node.sourceRect.height * node.scale.y));
                if (node.tileV)
                {
                    node.packedRect.height = num;
                }
                if (correctPow2)
                {
                    node.packedRect.width  = Mathf.ClosestPowerOfTwo((int)node.packedRect.width);
                    node.packedRect.height = Mathf.ClosestPowerOfTwo((int)node.packedRect.height);
                }
            }
            if (< > f__am$cache0 == null)
            {
Ejemplo n.º 2
0
        public void AddTexture(string name, Texture2D diffuse, Color diffuseColor, Texture2D normal, Texture2D gloss, Texture2D transtex, Texture2D shadowOffsetTex, float shininess, Vector2 scale, bool tileV, Vector2 uvTiling)
        {
            TextureNode node = new TextureNode();

            node.name                = name;
            node.diffuseTexture      = diffuse;
            node.diffuseColor        = diffuseColor;
            node.normalTexture       = normal;
            node.glossTexture        = gloss;
            node.translucencyTexture = transtex;
            node.shadowOffsetTexture = shadowOffsetTex;
            node.shininess           = shininess;
            node.scale               = scale;
            node.tileV               = tileV;
            node.uvTiling            = uvTiling;

            if (diffuse)
            {
                node.sourceRect.width  = diffuse.width;
                node.sourceRect.height = diffuse.height;
            }
            else
            {
                node.sourceRect.width  = 64;
                node.sourceRect.height = 64;
                node.scale             = new Vector2(1.0f, 1.0f);
            }

            nodes.Add(node);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Inserts an user-created OrbitTexture into the cache for future reference
        /// </summary>
        /// <param name="texture">The instance of the OrbitTexture to insert in the cache</param>
        /// <param name="id">The proposed Id of the OrbitTexture</param>
        /// <returns>True if successfully inserted. False otherwise</returns>
        public static bool InsertInCache(OrbitTexture texture, string id)
        {
            if (IsInCache(id))
            {
                return(false);
            }

            _Mutex.WaitOne();
            // create the new node
            TextureNode node = new TextureNode(texture, id.ToLower());

            node.Disposed += new EventHandler(Texture_Disposed);
            // expand the list
            TextureNode[] newList = new TextureNode[_Textures.Length + 1];
            for (int i = 0; i < _Textures.Length; i++)
            {
                newList[i] = _Textures[i];
            }
            newList[newList.Length - 1] = node;
            // finally replace the list
            _Textures = newList;

            _Mutex.ReleaseMutex();
            //System.Diagnostics.Debug.WriteLine("InsertInCache(): Inserted " + id + " in cache");
            return(true);
        }
Ejemplo n.º 4
0
 public void AddTexture(string name, Texture2D diffuse, Color diffuseColor, Texture2D normal, Texture2D gloss, Texture2D transtex, Texture2D shadowOffsetTex, float shininess, Vector2 scale, bool tileV, Vector2 uvTiling)
 {
     TextureNode item = new TextureNode {
         name = name,
         diffuseTexture = diffuse,
         diffuseColor = diffuseColor,
         normalTexture = normal,
         glossTexture = gloss,
         translucencyTexture = transtex,
         shadowOffsetTexture = shadowOffsetTex,
         shininess = shininess,
         scale = scale,
         tileV = tileV,
         uvTiling = uvTiling
     };
     if (diffuse != null)
     {
         item.sourceRect.width = diffuse.width;
         item.sourceRect.height = diffuse.height;
     }
     else
     {
         item.sourceRect.width = 64f;
         item.sourceRect.height = 64f;
         item.scale = new Vector2(1f, 1f);
     }
     this.nodes.Add(item);
 }
Ejemplo n.º 5
0
    public override void OnBodyGUI()
    {
        base.OnBodyGUI();
        TextureNode node = target as TextureNode;

        switch (node.landLayer)
        {
        case NodeVariables.Texture.LandLayerEnum.Ground:
            node.groundEnum = (TerrainSplat.Enum)EditorGUILayout.EnumPopup("Texture", node.groundEnum);
            break;

        case NodeVariables.Texture.LandLayerEnum.Biome:
            node.biomeEnum = (TerrainBiome.Enum)EditorGUILayout.EnumPopup("Texture", node.biomeEnum);
            break;

        case NodeVariables.Texture.LandLayerEnum.Alpha:
            node.alphaEnum = (NodeVariables.Texture.AlphaEnum)EditorGUILayout.EnumPopup("Texture", node.alphaEnum);
            break;

        case NodeVariables.Texture.LandLayerEnum.Topology:
            node.topologyLayer = (TerrainTopology.Enum)EditorGUILayout.EnumPopup("Topology", node.topologyLayer);
            node.topologyEnum  = (NodeVariables.Texture.TopologyEnum)EditorGUILayout.EnumPopup("Texture", node.topologyEnum);
            break;
        }
        node.Texture.LandLayer       = (int)node.landLayer;
        node.Texture.TopologyLayer   = TerrainTopology.TypeToIndex((int)node.topologyLayer);
        node.Texture.GroundTexture   = (int)node.groundEnum;
        node.Texture.BiomeTexture    = (int)node.biomeEnum;
        node.Texture.AlphaTexture    = (int)node.alphaEnum;
        node.Texture.TopologyTexture = (int)node.topologyEnum;
    }
Ejemplo n.º 6
0
        public void AddTexture(string name, Texture2D diffuse, Color diffuseColor, Texture2D normal, Texture2D gloss, Texture2D transtex, Texture2D shadowOffsetTex, float shininess, Vector2 scale, bool tileV, Vector2 uvTiling)
        {
            TextureNode item = new TextureNode {
                name                = name,
                diffuseTexture      = diffuse,
                diffuseColor        = diffuseColor,
                normalTexture       = normal,
                glossTexture        = gloss,
                translucencyTexture = transtex,
                shadowOffsetTexture = shadowOffsetTex,
                shininess           = shininess,
                scale               = scale,
                tileV               = tileV,
                uvTiling            = uvTiling
            };

            if (diffuse != null)
            {
                item.sourceRect.width  = diffuse.width;
                item.sourceRect.height = diffuse.height;
            }
            else
            {
                item.sourceRect.width  = 64f;
                item.sourceRect.height = 64f;
                item.scale             = new Vector2(1f, 1f);
            }
            this.nodes.Add(item);
        }
    public static void Init(TextureNode _src)
    {
        PreviewTextureWindow window = null;

        foreach (var x in m_List)
        {
            if (x != null && !x.m_Locked)
            {
                window = x;
                break;
            }
        }
        if (window == null)
        {
            window = CreateInstance <PreviewTextureWindow>();
            m_List.Add(window);
        }
        else
        {
            if (window.m_Source != null)
            {
                window.m_Source.RemoveRefreshWindow(window);
            }
        }
        //GetWindow<PreviewTextureWindow>();//ScriptableObject.CreateInstance<PreviewTextureWindow>();
        _src.AddRefreshWindow(window);
        window.m_Source = _src;


//            window.m_Preview = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32);
        //window.position = new Rect(_inst.canvasWindowRect.x+ _inst.canvasWindowRect.width*0.5f, _inst.canvasWindowRect.y + _inst.canvasWindowRect.height * 0.5f, 350, 250);
        window.titleContent = new GUIContent("Preview");
        window.Show();
        window.Repaint();
    }
Ejemplo n.º 8
0
        private static SceneNode CreateAnnotation(float2 pos, float borderScaleFactor, string text, Texture iconTex, Texture frameTex)
        {
            TextureNode icon = new TextureNode(
                "icon",
                VsTex,
                PsTex,
                iconTex,
                new MinMaxRect
            {
                Min = new float2(0, 0),
                Max = new float2(1, 1)
            },
                UIElementPosition.CalcOffsets(AnchorPos.StretchAll, new float2(0.07f, 0.07f), AnnotationDim.y, AnnotationDim.x, new float2(0.35f, 0.35f)),
                float2.One
                );

            TextNode annotationText = new TextNode(
                text,
                "annotation text",
                VsTex,
                PsText,
                new MinMaxRect
            {
                Min = new float2(0, 0),
                Max = new float2(1, 1)
            },
                UIElementPosition.CalcOffsets(AnchorPos.StretchAll, new float2(0.5f, 0.07f), AnnotationDim.y, AnnotationDim.x, new float2(2.5f, 0.35f)),
                RalewayFontMap,
                (float4)ColorUint.Black,
                HorizontalTextAlignment.Center,
                VerticalTextAlignment.Center);

            TextureNode annotation = new TextureNode(
                "Annotation",
                VsNineSlice,
                PsNineSlice,
                frameTex,
                new MinMaxRect
            {
                Min = new float2(0, 0),
                Max = new float2(0, 0)
            },
                UIElementPosition.CalcOffsets(AnchorPos.DownDownLeft, pos, CanvasHeightInit, CanvasWidthInit,
                                              AnnotationDim),
                new float2(1, 1),
                new float4(0.09f, 0.09f, 0.09f, 0.09f),
                AnnotationBorderThickness.x, AnnotationBorderThickness.y, AnnotationBorderThickness.z,
                AnnotationBorderThickness.w,
                borderScaleFactor

                );

            annotation.Children.Add(annotationText);
            annotation.Children.Add(icon);

            return(annotation);
        }
Ejemplo n.º 9
0
        /// <summary>Gets this node as a loonim node. Potentially pulls a cached node.</summary>
        public TextureNode GetLoonim(SurfaceTexture tex)
        {
            if (LoonimNode_ == null)
            {
                LoonimNode_ = ToLoonimNode(tex);
            }

            return(LoonimNode_);
        }
Ejemplo n.º 10
0
    void OnGUI()
    {
        GUILayout.BeginHorizontal();
        m_Locked    = GUILayout.Toggle(m_Locked, "Locked");
        m_Histogram = GUILayout.Toggle(m_Histogram, "Histogram");
        m_Scale     = EditorGUILayout.FloatField(m_Scale);
        GUILayout.EndHorizontal();
        //            GUILayout.Label("Base Settings", EditorStyles.boldLabel);

        if (m_Source == null || m_Source.m_Param == null || m_Source.m_Cached == null)
        {
            return;
        }
        int wantWidth  = m_Source.m_Cached.width;
        int wantHeight = m_Source.m_Cached.height;

        if (m_Histogram)
        {
            wantWidth  = 512;
            wantHeight = 512;
        }

        if (m_tex == null || m_tex.width != wantWidth || m_tex.height != wantHeight)
        {
            AllocTex(wantWidth, wantHeight);
        }

        RenderTexture preview = RenderTexture.GetTemporary(wantWidth, wantHeight, 0, RenderTextureFormat.ARGB32);

        Material m = TextureNode.GetMaterial("TextureOps");

        m.SetVector("_Multiply", new Vector4(1.0f, 0, 0, 0));
        if (m_Histogram)
        {
            CreatePreviewHistogram(preview);
        }
        else
        {
            Graphics.Blit(m_Source.m_Cached, preview, m, m_Source.m_TexMode == TextureNode.TexMode.Greyscale
                    ? (int)ShaderOp.CopyGrey: (int)ShaderOp.CopyColor);
        }
        m_tex.ReadPixels(new Rect(0, 0, wantWidth, wantHeight), 0, 0);
        m_tex.Apply();
        RenderTexture.active = null;

        //            EditorGUILayout.LabelField("\n Warning: Erases Current Canvas", EditorStyles.wordWrappedLabel);
        //            EditorGUILayout.Separator();
        Rect texRect = new Rect(2, 20, position.width - 4, position.height - 24);

        GUILayout.BeginArea(texRect, GUI.skin.box);
        GUI.DrawTexture(texRect, m_tex, ScaleMode.StretchToFill);//ScaleMode.StretchToFill);
        //GUI.DrawTexture(texRect, m_Preview, ScaleMode.ScaleToFit);//ScaleMode.StretchToFill);
        GUILayout.EndArea();
        RenderTexture.ReleaseTemporary(preview);
    }
Ejemplo n.º 11
0
        private void CreateTexture(TextureNode textureNode)
        {
            if (textureNode.Name == null)
            {
                textureNode.Name = string.Format(CultureInfo.InvariantCulture, "Tex{0}", textureNode.UniqueId);
            }

            Texture texture = new Texture();

            texture.Name = textureNode.Name;

            if (textureNode.Width == 0 || textureNode.Height == 0)
            {
                Texture id = this.Textures.Values
                             .FirstOrDefault(t => t.Id == textureNode.UniqueId);

                if (id == null && this.Textures.Count != 0)
                {
                    id = this.Textures.ElementAt(this.Textures.Count - 1).Value;
                }

                if (id == null)
                {
                    throw new InvalidDataException("invalid 0x0 texture");
                }

                texture.Id        = id.Id;
                texture.Width     = id.Width;
                texture.Height    = id.Height;
                texture.Palette   = id.Palette;
                texture.ImageData = id.ImageData;
                texture.AlphaData = id.AlphaData;
            }
            else
            {
                texture.Id        = textureNode.UniqueId;
                texture.Width     = textureNode.Width;
                texture.Height    = textureNode.Height;
                texture.Palette   = textureNode.Palettes;
                texture.ImageData = textureNode.Bytes;

                TextureAlphaNode alphaNode = (TextureAlphaNode)textureNode.Nodes
                                             .FirstOrDefault(t => t.NodeType == NodeType.TextureAlpha);

                if (alphaNode != null)
                {
                    texture.AlphaData = alphaNode.Bytes;
                }
            }

            this.Textures.Add(texture.Name, texture);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Removes an user-created OrbitTexture from the cache
        /// </summary>
        /// <param name="id">The id</param>
        /// <returns>True if successfully removed. False otherwise</returns>
        public static bool RemoveFromCache(string id)
        {
            _Mutex.WaitOne();
            TextureNode toRemove = null;

            id = id.ToLower();
            for (int i = 0; i < _Textures.Length; i++)
            {
                if (_Textures[i].Id == id)
                {
                    toRemove = _Textures[i];
                }
            }

            if (toRemove != null)
            {
                // reduce the list
                TextureNode[] newList = new TextureNode[_Textures.Length - 1];
                bool          found   = false;
                for (int i = 0; i < _Textures.Length; i++)
                {
                    if (_Textures[i] != toRemove)
                    {
                        if (found)
                        {
                            newList[i - 1] = _Textures[i];
                        }
                        else
                        {
                            newList[i] = _Textures[i];
                        }
                    }
                    else
                    {
                        found = true;
                    }
                }
                // finally replace the list
                _Textures = newList;

                _Mutex.ReleaseMutex();
                //System.Diagnostics.Debug.WriteLine("RemoveFromCache(): Removed " + id + " from cache");
                return(true);
            }
            else
            {
                _Mutex.ReleaseMutex();
                //System.Diagnostics.Debug.WriteLine("RemoveFromCache(): " + id + " not found in cache");
                return(false);
            }
        }
Ejemplo n.º 13
0
 public static bool Overlap(TextureNode a, TextureNode b)
 {
     if (a.tileV || b.tileV)
     {
         return(!((a.packedRect.x > (b.packedRect.x + b.packedRect.width)) ||
                  ((a.packedRect.x + a.packedRect.width) < b.packedRect.x)));
     }
     else
     {
         return(!((a.packedRect.x > (b.packedRect.x + b.packedRect.width)) ||
                  ((a.packedRect.x + a.packedRect.width) < b.packedRect.x) ||
                  (a.packedRect.y > (b.packedRect.y + b.packedRect.height)) ||
                  ((a.packedRect.y + a.packedRect.height) < b.packedRect.y)));
     }
 }
Ejemplo n.º 14
0
 public int CompareTo(TextureNode b)
 {
     if (tileV && b.tileV)
     {
         return(-packedRect.width.CompareTo(b.packedRect.width));
     }
     if (tileV)
     {
         return(-1);
     }
     if (b.tileV)
     {
         return(1);
     }
     return(-packedRect.height.CompareTo(b.packedRect.height));
 }
Ejemplo n.º 15
0
        public Dictionary <string, CTexture> ParseTexture()  //텍스처 파싱후 Map으로 반환
        {
            xml = new XmlDocument();
            xml.Load("../../../Script/TextureList.xml");
            Dictionary <string, CTexture> mapTexture = new Dictionary <string, CTexture>();
            XmlNodeList TextureList = xml.SelectNodes("/TextureList/Texture");

            foreach (XmlNode TextureNode in TextureList)   //Texture 수만큼 루프
            {
                string  strName    = TextureNode["Name"].InnerText;
                XmlNode BackGround = TextureNode["BackgroundRGB"];
                if (BackGround != null && BackGround.HasChildNodes)
                {
                    int R = Int32.Parse(TextureNode["BackgroundRGB"].SelectSingleNode("R").InnerText);
                    int G = Int32.Parse(TextureNode["BackgroundRGB"].SelectSingleNode("G").InnerText);
                    int B = Int32.Parse(TextureNode["BackgroundRGB"].SelectSingleNode("B").InnerText);
                }
                string   strPath = TextureNode["Path"].InnerText;
                CTexture Texture = new CTexture();
                Texture.SetName(strName);
                Texture.SetRoute("../../" + strPath);
                XmlNodeList SpriteList = TextureNode.SelectNodes("Sprite");
                foreach (XmlNode SpriteNode in SpriteList)   //Sprite 수만큼 루프
                {
                    if (SpriteNode.HasChildNodes)
                    {
                        string     SpriteName = SpriteNode["Name"].InnerText;
                        spriteInfo SpriteInfo;
                        SpriteInfo.iXBegin     = Int32.Parse(SpriteNode["XBegin"].InnerText);
                        SpriteInfo.iYBegin     = Int32.Parse(SpriteNode["YBegin"].InnerText);
                        SpriteInfo.iIsLine     = Int32.Parse(SpriteNode["isLine"].InnerText);
                        SpriteInfo.iFrameCount = Int32.Parse(SpriteNode["FrameCount"].InnerText);
                        SpriteInfo.iXFrame     = Int32.Parse(SpriteNode["XFrame"].InnerText);
                        SpriteInfo.iYFrame     = Int32.Parse(SpriteNode["YFrame"].InnerText);
                        SpriteInfo.iXSize      = Int32.Parse(SpriteNode["XSize"].InnerText);
                        SpriteInfo.iYSize      = Int32.Parse(SpriteNode["YSize"].InnerText);
                        CSprite Sprite = new CSprite(SpriteInfo);
                        Texture.AddSprite(SpriteName, Sprite);
                    }
                }
                mapTexture.Add(strName, Texture);
            }
            return(mapTexture);
        }
Ejemplo n.º 16
0
        protected override void AddNodeClick(object sender, EventArgs e)
        {
            if (this.Tree.SelectedNode != null && this.Tree.SelectedNode is TextureNode)
            {
                TextureNode selected = this.Tree.SelectedNode as TextureNode;

                string newNodeName = selected.Text;
                if (newNodeName.Equals("Root"))
                {
                    newNodeName = "Node";
                }
                newNodeName += "." + (selected.CumulatedChildCount + 1);

                TextureNode newNode = new TextureNode(newNodeName);
                newNode.Checked = true;
                selected.AddNode(newNode);
                selected.Expand();
                newNode.Update(false);
                base.AddNodeClick(sender, e);
            }
        }
Ejemplo n.º 17
0
    void CreatePreviewHistogram(RenderTexture preview)
    {
        if (m_ComputeShader2 == null)
        {
            m_ComputeShader2 = (ComputeShader)Resources.Load("EyeHistogram");
        }
        var cs = m_ComputeShader2;

        if (m_Buffer == null)
        {
            m_Buffer = new ComputeBuffer(512 * 1, sizeof(uint) << 2);
        }
        int kernel = cs.FindKernel("KHistogramClear");

        cs.SetBuffer(kernel, "_Histogram", m_Buffer);
        cs.Dispatch(kernel, 1, 1, 1);

        kernel = cs.FindKernel("KHistogramGather");
        cs.SetBuffer(kernel, "_Histogram", m_Buffer);
        Texture source = m_Source.m_Cached;

        cs.SetTexture(kernel, "_Source", source);
        cs.SetInt("_IsLinear", GraphicsUtils.isLinearColorSpace ? 1 : 0);
        cs.SetVector("_Res", new Vector4(source.width, source.height, 0f, 0f));
        cs.SetVector("_Channels", new Vector4(1f, 1f, 1f, 0f));

        cs.Dispatch(kernel, Mathf.CeilToInt(source.width / 16f), Mathf.CeilToInt(source.height / 16f), 1);

        kernel = cs.FindKernel("KHistogramScale");
        cs.SetBuffer(kernel, "_Histogram", m_Buffer);
        cs.SetVector("_Res", new Vector4(512, 512, m_Scale, 0f));
        cs.Dispatch(kernel, 1, 1, 1);
        Material m = TextureNode.GetMaterial("TextureOps");

        m.SetVector("_Multiply", new Vector4(preview.width, preview.height, 0, 0));
        m.SetBuffer("_Histogram", m_Buffer);
        Graphics.Blit(m_Source.m_Cached, preview, m, (int)ShaderOp.Histogram);
    }
Ejemplo n.º 18
0
 private void colorClick(object sender, System.EventArgs e)
 {
     if (this.selectedNode != null)
     {
         ColorDialog colorDialog = new ColorDialog();
         colorDialog.Color          = this.colorButton.BackColor;
         colorDialog.FullOpen       = true;
         colorDialog.SolidColorOnly = false;
         colorDialog.AllowFullOpen  = true;
         colorDialog.AnyColor       = true;
         if (colorDialog.ShowDialog() == DialogResult.OK)
         {
             this.colorButton.BackColor = colorDialog.Color;
             if (this.selectedNode != null)
             {
                 TextureNode   node      = this.selectedNode;
                 SharpDX.Color color     = node.Color;
                 SharpDX.Color nodeColor =
                     new SharpDX.Color(colorDialog.Color.R, colorDialog.Color.G, colorDialog.Color.B, color.A);
                 node.Color = nodeColor;
             }
         }
     }
 }
Ejemplo n.º 19
0
        private SceneContainer CreateGui()
        {
            var vsTex = AssetStorage.Get <string>("texture.vert");
            var psTex = AssetStorage.Get <string>("texture.frag");

            var btnFuseeLogo = new GUIButton
            {
                Name = "Canvas_Button"
            };

            btnFuseeLogo.OnMouseEnter += BtnLogoEnter;
            btnFuseeLogo.OnMouseExit  += BtnLogoExit;
            btnFuseeLogo.OnMouseDown  += BtnLogoDown;

            var guiFuseeLogo = new Texture(AssetStorage.Get <ImageData>("FuseeText.png"));
            var fuseeLogo    = new TextureNode(
                "fuseeLogo",
                vsTex,
                psTex,
                //Set the diffuse texture you want to use.
                guiFuseeLogo,
                //Define anchor points. They are given in percent, seen from the lower left corner, respectively to the width/height of the parent.
                //In this setup the element will stretch horizontally but stay the same vertically if the parent element is scaled.
                UIElementPosition.GetAnchors(AnchorPos.TopTopLeft),
                //Define Offset and therefor the size of the element.
                UIElementPosition.CalcOffsets(AnchorPos.TopTopLeft, new float2(0, _initCanvasHeight - 0.5f), _initCanvasHeight, _initCanvasWidth, new float2(1.75f, 0.5f))
                );

            fuseeLogo.AddComponent(btnFuseeLogo);

            // Initialize the information text line.
            var textToDisplay = "FUSEE 3D Scene";

            if (_scene.Header.CreatedBy != null || _scene.Header.CreationDate != null)
            {
                textToDisplay += " created";
                if (_scene.Header.CreatedBy != null)
                {
                    textToDisplay += " by " + _scene.Header.CreatedBy;
                }

                if (_scene.Header.CreationDate != null)
                {
                    textToDisplay += " on " + _scene.Header.CreationDate;
                }
            }

            var fontLato     = AssetStorage.Get <Font>("Lato-Black.ttf");
            var guiLatoBlack = new FontMap(fontLato, 24);

            var text = new TextNode(
                textToDisplay,
                "SceneDescriptionText",
                vsTex,
                psTex,
                UIElementPosition.GetAnchors(AnchorPos.StretchHorizontal),
                UIElementPosition.CalcOffsets(AnchorPos.StretchHorizontal, new float2(_initCanvasWidth / 2 - 4, 0), _initCanvasHeight, _initCanvasWidth, new float2(8, 1)),
                guiLatoBlack,
                ColorUint.Tofloat4(ColorUint.Greenery),
                HorizontalTextAlignment.Center,
                VerticalTextAlignment.Center);


            var canvas = new CanvasNode(
                "Canvas",
                _canvasRenderMode,
                new MinMaxRect
            {
                Min = new float2(-_canvasWidth / 2, -_canvasHeight / 2f),
                Max = new float2(_canvasWidth / 2, _canvasHeight / 2f)
            });

            canvas.Children.Add(fuseeLogo);
            canvas.Children.Add(text);

            return(new SceneContainer
            {
                Children = new List <SceneNode>
                {
                    //Add canvas.
                    canvas
                }
            });
        }
Ejemplo n.º 20
0
        private SceneContainer CreateGui()
        {
            var vsTex = AssetStorage.Get <string>("texture.vert");
            var psTex = AssetStorage.Get <string>("texture.frag");

            var canvasWidth  = Width / 100f;
            var canvasHeight = Height / 100f;

            var btnFuseeLogo = new GUIButton
            {
                Name = "Canvas_Button"
            };

            btnFuseeLogo.OnMouseEnter += BtnLogoEnter;
            btnFuseeLogo.OnMouseExit  += BtnLogoExit;
            btnFuseeLogo.OnMouseDown  += BtnLogoDown;

            var guiFuseeLogo = new Texture(AssetStorage.Get <ImageData>("FuseeText.png"));
            var fuseeLogo    = new TextureNode(
                "fuseeLogo",
                vsTex,
                psTex,
                //Set the albedo texture you want to use.
                guiFuseeLogo,
                //Define anchor points. They are given in percent, seen from the lower left corner, respectively to the width/height of the parent.
                //In this setup the element will stretch horizontally but stay the same vertically if the parent element is scaled.
                UIElementPosition.GetAnchors(AnchorPos.TopTopLeft),
                //Define Offset and therefor the size of the element.
                UIElementPosition.CalcOffsets(AnchorPos.TopTopLeft, new float2(0, canvasHeight - 0.5f), canvasHeight, canvasWidth, new float2(1.75f, 0.5f))
                );

            fuseeLogo.AddComponent(btnFuseeLogo);

            var fontLato     = AssetStorage.Get <Font>("Lato-Black.ttf");
            var guiLatoBlack = new FontMap(fontLato, 24);

            var text = new TextNode(
                "FUSEE Simple Example",
                "ButtonText",
                vsTex,
                psTex,
                UIElementPosition.GetAnchors(AnchorPos.StretchHorizontal),
                UIElementPosition.CalcOffsets(AnchorPos.StretchHorizontal, new float2(canvasWidth / 2 - 4, 0), canvasHeight, canvasWidth, new float2(8, 1)),
                guiLatoBlack,
                ColorUint.Tofloat4(ColorUint.Greenery),
                HorizontalTextAlignment.Center,
                VerticalTextAlignment.Center);

            var canvas = new CanvasNode(
                "Canvas",
                _canvasRenderMode,
                new MinMaxRect
            {
                Min = new float2(-canvasWidth / 2, -canvasHeight / 2f),
                Max = new float2(canvasWidth / 2, canvasHeight / 2f)
            })
            {
                Children = new ChildList()
                {
                    //Simple Texture Node, contains the fusee logo.
                    fuseeLogo,
                    text
                }
            };

            return(new SceneContainer
            {
                Children = new List <SceneNode>
                {
                    //Add canvas.
                    canvas
                }
            });
        }
Ejemplo n.º 21
0
        //Build a scene graph consisting out of a canvas and other UI elements.
        private SceneContainer CreateNineSliceScene()
        {
            var vsTex       = AssetStorage.Get <string>("texture.vert");
            var psTex       = AssetStorage.Get <string>("texture.frag");
            var vsNineSlice = AssetStorage.Get <string>("nineSlice.vert");
            var psNineSlice = AssetStorage.Get <string>("nineSliceTile.frag");

            var canvasScaleFactor = _initWindowWidth / _canvasWidth;

            float borderScaleFactor = 1;

            if (_canvasRenderMode == CanvasRenderMode.Screen)
            {
                borderScaleFactor = canvasScaleFactor;
            }

            var fps = new TextNode(
                "FPS: 0.00",
                "FPSText",
                vsTex,
                psTex,
                UIElementPosition.GetAnchors(AnchorPos.DownDownRight),
                new MinMaxRect
            {
                Min = new float2(-2, 0),
                Max = new float2(0, 1)
            },
                _fontMap,
                ColorUint.Tofloat4(ColorUint.White),
                HorizontalTextAlignment.Center,
                VerticalTextAlignment.Center
                );

            _fpsText = fps.GetComponentsInChildren <GUIText>().FirstOrDefault();

            var text = new TextNode(
                "The five\n" +
                "boxing wizards\n" +
                "jump\n" +
                "quickly.",
                "ButtonText",
                vsTex,
                psTex,
                UIElementPosition.GetAnchors(AnchorPos.StretchAll),
                new MinMaxRect
            {
                Min = new float2(1f, 0.5f),
                Max = new float2(-1f, -0.5f)
            },
                _fontMap,
                ColorUint.Tofloat4(ColorUint.Greenery),
                HorizontalTextAlignment.Center,
                VerticalTextAlignment.Center);

            var catTextureNode = new TextureNode(
                "Cat",
                AssetStorage.Get <string>("nineSlice.vert"),
                AssetStorage.Get <string>("nineSliceTile.frag"),
                //Set the albedo texture you want to use.
                new Texture(AssetStorage.Get <ImageData>("Kitti.jpg")),

                //Define anchor points. They are given in percent, seen from the lower left corner, respectively to the width/height of the parent.
                //In this setup the element will stretch horizontally but stay the same vertically if the parent element is scaled.
                UIElementPosition.GetAnchors(AnchorPos.StretchHorizontal),//Anchor is in the lower left corner of the parent. Anchor is in the lower right corner of the parent.

                //Define Offset and therefor the size of the element.
                //Min: distance to this elements Min anchor.
                //Max: distance to this elements Max anchor.
                UIElementPosition.CalcOffsets(AnchorPos.StretchHorizontal, new float2(_initCanvasWidth / 2 - 2.5f, 0), _initCanvasHeight, _initCanvasWidth, new float2(5, 4)),
                //Choose in how many tiles you want to split the inner part of the texture. Use float2.one if you want it stretched.
                new float2(5, 5),
                //Tell how many percent of the texture, seen from the edges, belongs to the border. Order: left, right, top, bottom.
                new float4(0.11f, 0.11f, 0.06f, 0.17f),
                4, 4, 4, 4,
                borderScaleFactor

                )
            {
                Children = new ChildList()
                {
                    text
                }
            };

            catTextureNode.Components.Add(_btnCat);

            var bltTextureNode = new TextureNode(
                "Blt",
                vsTex,
                psTex,
                //Set the albedo texture you want to use.
                _bltDestinationTex,
                //_fontMap.Image,
                //Define anchor points. They are given in percent, seen from the lower left corner, respectively to the width/height of the parent.
                //In this setup the element will stretch horizontally but stay the same vertically if the parent element is scaled.
                UIElementPosition.GetAnchors(AnchorPos.DownDownLeft),//Anchor is in the lower left corner of the parent. Anchor is in the lower right corner of the parent.

                //Define Offset and therefor the size of the element.
                //Min: distance to this elements Min anchor.
                //Max: distance to this elements Max anchor.
                UIElementPosition.CalcOffsets(AnchorPos.DownDownLeft, new float2(0, 0), _initCanvasHeight, _initCanvasWidth, new float2(4, 4)));

            var quagganTextureNode1 = new TextureNode(
                "Quaggan1",
                vsNineSlice,
                psNineSlice,
                new Texture(AssetStorage.Get <ImageData>("testTex.jpg")),
                //In this setup the element will stay in the upper left corner of the parent and will not be stretched at all.
                UIElementPosition.GetAnchors(AnchorPos.TopTopLeft), //Anchor is in the lower right corner.Anchor is in the lower left corner.
                UIElementPosition.CalcOffsets(AnchorPos.TopTopLeft, new float2(2.5f, 0), 3, 6, new float2(1, 1)),

                new float2(1, 1),
                new float4(0.1f, 0.1f, 0.1f, 0.09f),
                1, 1, 1, 1,
                borderScaleFactor
                );

            var nineSliceTextureNode = new TextureNode(
                "testImage",
                vsNineSlice,
                psNineSlice,
                new Texture(AssetStorage.Get <ImageData>("9SliceSprites-4.png")),
                //In this setup the element will stay in the upper right corner of the parent and will not be stretched at all.
                UIElementPosition.GetAnchors(AnchorPos.TopTopRight),//Anchor is in the upper right corner.//Anchor is in the upper right corner.

                UIElementPosition.CalcOffsets(AnchorPos.TopTopRight, new float2(_initCanvasWidth - 6, _initCanvasHeight - 3), _initCanvasHeight, _initCanvasWidth, new float2(6, 3)),

                new float2(2, 3),
                new float4(0.1f, 0.1f, 0.1f, 0.1f),
                2.5f, 2.5f, 2.5f, 2.5f,
                borderScaleFactor
                )
            {
                Children = new ChildList()
                {
                    quagganTextureNode1, text
                }
            };

            var quagganTextureNode = new TextureNode(
                "Quaggan",
                vsNineSlice,
                psNineSlice,
                new Texture(AssetStorage.Get <ImageData>("testTex.jpg")),
                //In this setup the element will stay in the upper left corner of the parent and will not be stretched at all.
                UIElementPosition.GetAnchors(AnchorPos.TopTopLeft), //Anchor is in the lower right corner.Anchor is in the lower left corner.
                UIElementPosition.CalcOffsets(AnchorPos.TopTopLeft, new float2(0, _initCanvasHeight - 1), _initCanvasHeight, _initCanvasWidth, new float2(6, 1)),
                new float2(5, 1),
                new float4(0.1f, 0.1f, 0.1f, 0.09f),
                1, 1, 1, 1,
                borderScaleFactor
                );

            var quagganTextureNode2 = new TextureNode(
                "Quaggan",
                vsNineSlice,
                psNineSlice,
                new Texture(AssetStorage.Get <ImageData>("testTex.jpg")),
                //In this setup the element will stay in the upper left corner of the parent and will not be stretched at all.
                UIElementPosition.GetAnchors(AnchorPos.TopTopLeft), //Anchor is in the lower right corner.Anchor is in the lower left corner.
                UIElementPosition.CalcOffsets(AnchorPos.TopTopLeft, new float2(0, _initCanvasHeight - 3), _initCanvasHeight, _initCanvasWidth, new float2(6, 1)),
                new float2(5, 1),
                new float4(0.1f, 0.1f, 0.1f, 0.09f),
                1, 1, 1, 1,
                borderScaleFactor
                );

            var quagganTextureNode3 = new TextureNode(
                "Quaggan",
                vsNineSlice,
                psNineSlice,
                new Texture(AssetStorage.Get <ImageData>("testTex.jpg")),
                //In this setup the element will stay in the upper left corner of the parent and will not be stretched at all.
                UIElementPosition.GetAnchors(AnchorPos.StretchVertical), //Anchor is in the lower right corner. Anchor is in the lower left corner.
                UIElementPosition.CalcOffsets(AnchorPos.StretchVertical, new float2(0, _initCanvasHeight - 5), _initCanvasHeight, _initCanvasWidth, new float2(6, 1)),
                new float2(5, 1),
                new float4(0.1f, 0.1f, 0.1f, 0.09f),
                1, 1, 1, 1,
                borderScaleFactor
                );

            var canvas = new CanvasNode(
                "Canvas",
                _canvasRenderMode,
                new MinMaxRect
            {
                Min = new float2(-_canvasWidth / 2, -_canvasHeight / 2f),
                Max = new float2(_canvasWidth / 2, _canvasHeight / 2f)
            })
            {
                Children = new ChildList()
                {
                    //Simple Texture Node, contains a Blt"ed" texture.
                    bltTextureNode,
                    //Add nine sliced textures to canvas
                    catTextureNode,
                    quagganTextureNode,
                    nineSliceTextureNode,
                    quagganTextureNode2,
                    quagganTextureNode3,
                    fps
                }
            };

            var canvasMat = ShaderCodeBuilder.MakeShaderEffect(new float4(1, 0, 0, 1));

            canvas.AddComponent(canvasMat);
            canvas.AddComponent(new Plane());
            canvas.AddComponent(_btnCanvas);

            return(new SceneContainer
            {
                Children = new List <SceneNode>
                {
                    //Add canvas.

                    new SceneNode()
                    {
                        Components = new List <SceneComponent>()
                        {
                            new Transform()
                            {
                                Translation = new float3(0, 0, 0)
                            }
                        },
                        Children = new ChildList()
                        {
                            canvas
                        }
                    },
                }
            });
        }
Ejemplo n.º 22
0
        public void Save(string path)
        {
            this.CompactBuffers();

            OptFileNodes optNodes = new OptFileNodes();

            Dictionary <string, bool> texturesWriten = this.Textures.Keys.ToDictionary(t => t, t => false);

            foreach (Mesh mesh in this.Meshes)
            {
                mesh.SortLods();

                NodeGroupNode meshNode = new NodeGroupNode();

                RotationScaleNode      rotationScaleNode   = new RotationScaleNode();
                MeshDescriptorNode     descriptorNode      = new MeshDescriptorNode();
                MeshVerticesNode       verticesNode        = new MeshVerticesNode();
                TextureCoordinatesNode textureVerticesNode = new TextureCoordinatesNode();
                VertexNormalsNode      vertexNormalsNode   = new VertexNormalsNode();

                rotationScaleNode.Pivot = mesh.RotationScale.Pivot;
                rotationScaleNode.Look  = mesh.RotationScale.Look;
                rotationScaleNode.Up    = mesh.RotationScale.Up;
                rotationScaleNode.Right = mesh.RotationScale.Right;

                descriptorNode.MeshType      = mesh.Descriptor.MeshType;
                descriptorNode.ExplosionType = mesh.Descriptor.ExplosionType;
                descriptorNode.Span          = mesh.Descriptor.Span;
                descriptorNode.Center        = mesh.Descriptor.Center;
                descriptorNode.Min           = mesh.Descriptor.Min;
                descriptorNode.Max           = mesh.Descriptor.Max;
                descriptorNode.TargetId      = mesh.Descriptor.TargetId;
                descriptorNode.Target        = mesh.Descriptor.Target;

                foreach (Vector vertex in mesh.Vertices)
                {
                    verticesNode.Vertices.Add(vertex);
                }

                foreach (TextureCoordinates textureVertex in mesh.TextureCoordinates)
                {
                    textureVerticesNode.TextureVertices.Add(textureVertex);
                }

                foreach (Vector vertexNormal in mesh.VertexNormals)
                {
                    vertexNormalsNode.Normals.Add(vertexNormal);
                }

                meshNode.Nodes.Add(verticesNode);
                meshNode.Nodes.Add(textureVerticesNode);
                meshNode.Nodes.Add(vertexNormalsNode);
                meshNode.Nodes.Add(descriptorNode);
                meshNode.Nodes.Add(rotationScaleNode);

                FaceGroupingNode faceGroupingNode = new FaceGroupingNode();

                foreach (var lod in mesh.Lods)
                {
                    NodeGroupNode lodNode = new NodeGroupNode();

                    foreach (var faceGroup in lod.FaceGroups)
                    {
                        if (faceGroup.Textures.Count != 0)
                        {
                            List <Node> texturesNodes = new List <Node>();

                            foreach (var textureName in faceGroup.Textures)
                            {
                                if (!texturesWriten.ContainsKey(textureName) || texturesWriten[textureName])
                                {
                                    NodeReferenceNode textureNode = new NodeReferenceNode()
                                    {
                                        Reference = textureName
                                    };

                                    texturesNodes.Add(textureNode);
                                }
                                else
                                {
                                    var texture = this.Textures[textureName];

                                    TextureNode textureNode = new TextureNode();
                                    textureNode.Name     = texture.Name;
                                    textureNode.UniqueId = 0; // texture.Id
                                    textureNode.Width    = texture.Width;
                                    textureNode.Height   = texture.Height;
                                    textureNode.Palettes = texture.Palette;
                                    textureNode.Bytes    = texture.ImageData;

                                    if (texture.AlphaData != null)
                                    {
                                        TextureAlphaNode alphaNode = new TextureAlphaNode();
                                        alphaNode.Bytes = texture.AlphaData;

                                        textureNode.Nodes.Add(alphaNode);
                                    }

                                    texturesNodes.Add(textureNode);

                                    texturesWriten[textureName] = true;
                                }
                            }

                            if (texturesNodes.Count == 1)
                            {
                                lodNode.Nodes.Add(texturesNodes[0]);
                            }
                            else
                            {
                                NodeSwitchNode switchNode = new NodeSwitchNode();

                                foreach (var textureNode in texturesNodes)
                                {
                                    switchNode.Nodes.Add(textureNode);
                                }

                                lodNode.Nodes.Add(switchNode);
                            }
                        }

                        FaceDataNode faceDataNode = new FaceDataNode();

                        faceDataNode.EdgesCount = faceGroup.EdgesCount;

                        foreach (var face in faceGroup.Faces)
                        {
                            FaceDataNodeData faceData = new FaceDataNodeData
                            {
                                VerticesIndex           = face.VerticesIndex,
                                EdgesIndex              = face.EdgesIndex,
                                TextureCoordinatesIndex = face.TextureCoordinatesIndex,
                                VertexNormalsIndex      = face.VertexNormalsIndex,
                                Normal             = face.Normal,
                                TexturingDirection = face.TexturingDirection,
                                TexturingMagniture = face.TexturingMagniture
                            };

                            faceDataNode.Faces.Add(faceData);
                        }

                        lodNode.Nodes.Add(faceDataNode);
                    }

                    faceGroupingNode.Distances.Add(lod.Distance);
                    faceGroupingNode.Nodes.Add(lodNode);
                }

                NodeGroupNode faceGroupingNodeGroup = new NodeGroupNode();
                faceGroupingNodeGroup.Nodes.Add(Node.Null);
                faceGroupingNodeGroup.Nodes.Add(Node.Null);
                faceGroupingNodeGroup.Nodes.Add(Node.Null);
                faceGroupingNodeGroup.Nodes.Add(faceGroupingNode);

                meshNode.Nodes.Add(faceGroupingNodeGroup);

                foreach (var hardpoint in mesh.Hardpoints)
                {
                    meshNode.Nodes.Add(new HardpointNode()
                    {
                        HardpointType = hardpoint.HardpointType,
                        Position      = hardpoint.Position
                    });
                }

                foreach (var engineGlow in mesh.EngineGlows)
                {
                    meshNode.Nodes.Add(new EngineGlowNode()
                    {
                        IsDisabled = engineGlow.IsDisabled,
                        CoreColor  = engineGlow.CoreColor,
                        OuterColor = engineGlow.OuterColor,
                        Position   = engineGlow.Position,
                        Format     = engineGlow.Format,
                        Look       = engineGlow.Look,
                        Up         = engineGlow.Up,
                        Right      = engineGlow.Right
                    });
                }

                optNodes.Nodes.Add(meshNode);
            }

            foreach (var texture in texturesWriten.Where(t => !t.Value))
            {
                this.Textures.Remove(texture.Key);
            }

            optNodes.Save(path);
            this.FileName = path;
        }
Ejemplo n.º 23
0
        private SceneContainer CreateGui()
        {
            float canvasScaleFactor = _initWidth / _canvasWidth;
            float borderScaleFactor = 1;

            if (_canvasRenderMode == CanvasRenderMode.Screen)
            {
                borderScaleFactor = canvasScaleFactor;
            }

            GuiButton btnFuseeLogo = new()
            {
                Name = "Canvas_Button"
            };

            btnFuseeLogo.OnMouseEnter += BtnLogoEnter;
            btnFuseeLogo.OnMouseExit  += BtnLogoExit;
            btnFuseeLogo.OnMouseDown  += BtnLogoDown;

            Texture     guiFuseeLogo = new(AssetStorage.Get <ImageData>("FuseeText.png"));
            TextureNode fuseeLogo    = TextureNode.Create(
                "fuseeLogo",
                guiFuseeLogo,
                GuiElementPosition.GetAnchors(AnchorPos.TopTopLeft),
                GuiElementPosition.CalcOffsets(AnchorPos.TopTopLeft, new float2(0, _canvasHeight - 0.5f), _canvasHeight, _canvasWidth, new float2(1.75f, 0.5f)), float2.One);

            fuseeLogo.AddComponent(btnFuseeLogo);

            SceneNode markModelContainer = new()
            {
                Name = "MarkModelContainer",
            };

            CanvasNode canvas = new(
                "Canvas",
                _canvasRenderMode,
                new MinMaxRect
            {
                Min = new float2(-_canvasWidth / 2f, -_canvasHeight / 2f),
                Max = new float2(_canvasWidth / 2f, _canvasHeight / 2f)
            }
                )
            { Children = new ChildList()
              {
                  fuseeLogo, markModelContainer
              } };

            for (int i = 0; i < _uiInput.Count; i++)
            {
                var item = _uiInput[i];
                if (item.AnnotationKind != UserInterfaceHelper.AnnotationKind.Confirmed)
                {
                    UserInterfaceHelper.CreateAndAddCircleAnnotationAndLine(markModelContainer, item.AnnotationKind, item.Size, _uiInput[i].AnnotationCanvasPos, borderScaleFactor,
                                                                            "#" + i + " " + item.SegmentationClass + ", " + item.Probability.ToString(CultureInfo.GetCultureInfo("en-gb")));
                }
                else
                {
                    UserInterfaceHelper.CreateAndAddCircleAnnotationAndLine(markModelContainer, item.AnnotationKind, item.Size, _uiInput[i].AnnotationCanvasPos, borderScaleFactor,
                                                                            "#" + i + " " + item.SegmentationClass);
                }
            }

            return(new SceneContainer
            {
                Children = new List <SceneNode>
                {
                    //Add canvas.
                    canvas
                }
            });
        }
Ejemplo n.º 24
0
        public void Pack(ref int targetWidth, int targetHeight, int padding, bool correctPow2)
        {
            //
            // Very simple packing.. top->bottom left->right
            // Uses fixed height packing to ensure, that textures can tile vertically..
            // Allows scale factor of individual textures..
            // Works best with pow2 textures..
            //

            if ((padding % 2) != 0)
            {
                Debug.LogWarning("Padding not an even number");
                padding += 1;
            }


            // Maximal height of a node, to ensure V tiling is possible
            int maxHeight = targetHeight;

            // Set corrected size according to padding and scale..
            for (int i = 0; i < nodes.Count; i++)
            {
                TextureNode node = nodes[i];

                node.packedRect.x      = 0;
                node.packedRect.y      = 0;
                node.packedRect.width  = Mathf.Round(node.sourceRect.width * node.scale.x);
                node.packedRect.height = Mathf.Min(maxHeight, Mathf.Round(node.sourceRect.height * node.scale.y));

                if (node.tileV)
                {
                    node.packedRect.height = maxHeight;
                }

                if (correctPow2)
                {
                    node.packedRect.width  = (float)Mathf.ClosestPowerOfTwo((int)node.packedRect.width);
                    node.packedRect.height = (float)Mathf.ClosestPowerOfTwo((int)node.packedRect.height);
                    //    Debug.Log("Corrected size: "+node.packedRect.width+","+node.packedRect.height);
                }
            }

            //
            // Sort nodes according to corrected size..
            nodes.Sort(delegate(TextureNode a, TextureNode b) { return(a.CompareTo(b)); });

            int interiorw = 0;
            int interiorh = 0;

            for (int i = 0; i < nodes.Count; i++)
            {
                TextureNode node = nodes[i];
                bool        good = false;

                // left - right first
                for (int x = 0; x < interiorw; x++)
                {
                    node.packedRect.x = x;
                    node.packedRect.y = 0;
                    good = true;

                    // top - bottom
                    for (int y = 0; y <= interiorh; y++)
                    {
                        good = true;
                        node.packedRect.y = y;

                        for (int j = 0; j < i; j++)
                        {
                            TextureNode node2 = nodes[j];
                            if (TextureNode.Overlap(node, node2))
                            {
                                good = false;
                                // No point in searching for free place in top - bottom if node2.tileV is true, so exit loop 'top - bottom'
                                if (node2.tileV)
                                {
                                    y = interiorh;
                                }
                                else
                                {
                                    y = (int)(node2.packedRect.y + node2.packedRect.height);
                                }
                                break;
                            }
                        }

                        if (good)
                        {
                            break;
                        }
                    }
                    if (good)
                    {
                        break;
                    }
                }

                if (!good)
                {
                    // no good position inside, so push onto the right hand side at the top
                    node.packedRect.x = interiorw;
                    node.packedRect.y = 0;
                }

                interiorw = Mathf.Max(interiorw, (int)(node.packedRect.x + node.packedRect.width));
                interiorh = Mathf.Max(interiorh, (int)(node.packedRect.y + node.packedRect.height));
            }

            //
            // Minimal width is padding*2, or 64
            //
            int minimalWidth = Mathf.Max(Mathf.ClosestPowerOfTwo(padding * 2), 64);
            int finalWidth   = Mathf.Clamp(Mathf.ClosestPowerOfTwo(interiorw), minimalWidth, targetWidth);

            // Best match..
            targetWidth = finalWidth;

            //
            // copy values
            atlasWidth   = targetWidth;
            atlasHeight  = targetHeight;
            atlasPadding = padding;

            //
            // Scale to fit
            //
            float scaleU = targetWidth / ((float)interiorw);
            float scaleV = targetHeight / ((float)interiorh);

            for (int i = 0; i < nodes.Count; i++)
            {
                TextureNode node = nodes[i];

                // packed rect
                node.packedRect.x      *= scaleU;
                node.packedRect.y      *= scaleV;
                node.packedRect.width  *= scaleU;
                node.packedRect.height *= scaleV;

                // padding is done post scaling, to ensure margin is enough
                if (node.tileV)
                {
                    node.packedRect.y      = 0.0f;
                    node.packedRect.height = targetHeight;
                    node.packedRect.x     += padding / 2;
                    node.packedRect.width -= padding;
                }
                else
                {
                    node.packedRect.x      += padding / 2;
                    node.packedRect.y      += padding / 2;
                    node.packedRect.width  -= padding;
                    node.packedRect.height -= padding;
                }

                if (node.packedRect.width < 1)
                {
                    node.packedRect.width = 1;
                }
                if (node.packedRect.height < 1)
                {
                    node.packedRect.height = 1;
                }

                // round to clean pixel values
                node.packedRect.x      = Mathf.Round(node.packedRect.x);      // - 0.5f;// +0.5f;
                node.packedRect.y      = Mathf.Round(node.packedRect.y);      // - 0.5f;// +0.5f;
                node.packedRect.width  = Mathf.Round(node.packedRect.width);  // - 0.5f;// +1.0f;// +0.5f;
                node.packedRect.height = Mathf.Round(node.packedRect.height); // - 0.5f;// +1.0f;// +0.5f;

                // uv rect
                node.uvRect.x      = node.packedRect.x / targetWidth;
                node.uvRect.y      = node.packedRect.y / targetHeight;
                node.uvRect.width  = node.packedRect.width / targetWidth;
                node.uvRect.height = node.packedRect.height / targetHeight;
            }
        }
Ejemplo n.º 25
0
 protected internal override void CopyScriptableObjects(System.Func <ScriptableObject, ScriptableObject> replaceSerializableObject)
 {
     TextureNode.ConnectRemapFloats(this, replaceSerializableObject);
 }
Ejemplo n.º 26
0
 private static void AreEqual(TextureNode expected, TextureNode actual, string path)
 {
     Assert.AreEqual(expected == null ? "NULL" : "NOT_NULL", actual == null ? "NULL" : "NOT_NULL", path);
     //todo:
 }
Ejemplo n.º 27
0
    public override bool Calculate()
    {
        allInputsReady();

        if (m_Loops == 0 && (Inputs[0].connection == null || Inputs[0].connection.IsValueNull))//!allInputsReady())
        {
            Debug.LogError(" m_LoopCount set to 0 input 0 is null");
            m_Loops = 0;
            return(false);
        }
        if (m_Loops > 0 && (Inputs[1].connection == null || Inputs[1].connection.IsValueNull))//!allInputsReady())
        {
            Debug.LogError(" m_LoopCount set to 1 input 1 is null");
            m_Loops = 1;
            return(false);
        }
        if (m_Loops == 0)
        {
            Outputs[0].SetValue <TextureParam>(Inputs[0].GetValue <TextureParam>());
        }
        else
        {
            //check if any of our connects to Output Looped, output straight back to us
            //if so that creates a render case where the same renderTexture is the input and the output, so make a copy
            bool inputIsOutput = false;
            foreach (var c in Outputs[0].connections)
            {
                foreach (var o in c.body.Outputs)
                {
                    foreach (var c2 in o.connections)
                    {
                        if (c2.body == this)
                        {
//                            inputIsOutput = true;
                            Debug.LogError("found an in out is the same from " + o.body);
                        }
                    }
                }
            }
            if (inputIsOutput)
            {
                if (m_Temp == null)
                {
                    m_Temp = new TextureParam(Inputs[1].GetValue <TextureParam>());
                }
                Material m = TextureNode.GetMaterial("TextureOps");
                Graphics.Blit(Inputs[1].GetValue <TextureParam>().GetHWSourceTexture(), m_Temp.m_Destination, m,
                              (int)ShaderOp.CopyColorAndAlpha);

                Outputs[0].SetValue <TextureParam>(m_Temp);
            }
            else
            {
                Outputs[0].SetValue <TextureParam>(Inputs[1].GetValue <TextureParam>());
            }
        }
        Outputs[2].SetValue <float>((float)m_Loops / (float)m_LoopCount);
        m_Loops++;
//        Debug.LogError("Loop Count Inc" + m_Loops + " / " + m_LoopCount);
        if (m_Loops >= m_LoopCount)
        {
            Outputs[1].SetValue <TextureParam>(Inputs[1].GetValue <TextureParam>());
        }
        else
        {
            if (Outputs[2] != null)
            {
                Node.ms_GlobalDirtyID++;
                SetDirty(this);
                calculated = true; //so the descendant can calculate that uses output 0
                foreach (var c in Outputs[2].connections)
                {
                    if (c != null)
                    {
                        NodeEditor.ContinueCalculation(c.body);
                    }
                }
                calculated = false;
            }
            if (Outputs[0] != null)
            {
                Node.ms_GlobalDirtyID++;
                SetDirty(this);
                calculated = true; //so the descendant can calculate that uses output 0
                foreach (var c in Outputs[0].connections)
                {
                    if (c != null)
                    {
                        NodeEditor.ContinueCalculation(c.body);
                    }
                }
                calculated = false;
            }
        }
        return(m_Loops >= m_LoopCount);
    }
Ejemplo n.º 28
0
        public static OptFile FromFile(string path)
        {
            OptFile opt = new OptFile();

            opt.FileName = path;

            OptFileNodes optNodes = OptFileNodes.FromFile(path);

            List <string> globalTexture = null;

            for (int meshId = 0; meshId < optNodes.Nodes.Count; meshId++)
            {
                if (meshId == 0 && optNodes.Nodes[meshId].NodeType == NodeType.Texture)
                {
                    TextureNode textureNode = (TextureNode)optNodes.Nodes[meshId];
                    opt.CreateTexture(textureNode);
                    globalTexture = new List <string>()
                    {
                        textureNode.Name
                    };
                    continue;
                }

                if (optNodes.Nodes[meshId].NodeType != NodeType.NodeGroup)
                {
                    throw new InvalidDataException("invalid mesh");
                }

                NodeGroupNode meshNode = (NodeGroupNode)optNodes.Nodes[meshId];

                var meshNodes = meshNode.Nodes.Union((meshNode.Nodes.Where(t => t.NodeType == NodeType.NodeGroup).FirstOrDefault() ?? new NodeGroupNode()).Nodes).ToList();

                RotationScaleNode      rotationScaleNode   = (RotationScaleNode)meshNodes.FirstOrDefault(t => t.NodeType == NodeType.RotationScale);
                MeshDescriptorNode     descriptorNode      = (MeshDescriptorNode)meshNodes.FirstOrDefault(t => t.NodeType == NodeType.MeshDescriptor);
                MeshVerticesNode       verticesNode        = (MeshVerticesNode)meshNodes.First(t => t.NodeType == NodeType.MeshVertices);
                TextureCoordinatesNode textureVerticesNode = (TextureCoordinatesNode)meshNodes.First(t => t.NodeType == NodeType.TextureCoordinates);
                VertexNormalsNode      vertexNormalsNode   = (VertexNormalsNode)meshNodes.First(t => t.NodeType == NodeType.VertexNormals);

                var hardpointsNodes  = meshNodes.Where(t => t.NodeType == NodeType.Hardpoint).Select(t => (HardpointNode)t).ToList();
                var engineGlowsNodes = meshNodes.Where(t => t.NodeType == NodeType.EngineGlow).Select(t => (EngineGlowNode)t).ToList();

                FaceGroupingNode faceGroupingNode = (FaceGroupingNode)meshNodes.First(t => t.NodeType == NodeType.FaceGrouping);

                Mesh mesh = new Mesh();

                if (rotationScaleNode != null)
                {
                    mesh.RotationScale.Pivot = rotationScaleNode.Pivot;
                    mesh.RotationScale.Look  = rotationScaleNode.Look;
                    mesh.RotationScale.Up    = rotationScaleNode.Up;
                    mesh.RotationScale.Right = rotationScaleNode.Right;
                }

                if (descriptorNode != null)
                {
                    mesh.Descriptor.MeshType      = descriptorNode.MeshType;
                    mesh.Descriptor.ExplosionType = descriptorNode.ExplosionType;
                    mesh.Descriptor.Span          = descriptorNode.Span;
                    mesh.Descriptor.Center        = descriptorNode.Center;
                    mesh.Descriptor.Min           = descriptorNode.Min;
                    mesh.Descriptor.Max           = descriptorNode.Max;
                    mesh.Descriptor.TargetId      = descriptorNode.TargetId;
                    mesh.Descriptor.Target        = descriptorNode.Target;
                }

                foreach (Vector vertex in verticesNode.Vertices)
                {
                    mesh.Vertices.Add(vertex);
                }

                foreach (TextureCoordinates textureVertex in textureVerticesNode.TextureVertices)
                {
                    mesh.TextureCoordinates.Add(textureVertex);
                }

                foreach (Vector normal in vertexNormalsNode.Normals)
                {
                    mesh.VertexNormals.Add(normal);
                }

                foreach (var hardpoint in hardpointsNodes)
                {
                    mesh.Hardpoints.Add(new Hardpoint()
                    {
                        HardpointType = hardpoint.HardpointType,
                        Position      = hardpoint.Position
                    });
                }

                foreach (var engineGlow in engineGlowsNodes)
                {
                    mesh.EngineGlows.Add(new EngineGlow()
                    {
                        IsDisabled = engineGlow.IsDisabled,
                        CoreColor  = engineGlow.CoreColor,
                        OuterColor = engineGlow.OuterColor,
                        Position   = engineGlow.Position,
                        Format     = engineGlow.Format,
                        Look       = engineGlow.Look,
                        Up         = engineGlow.Up,
                        Right      = engineGlow.Right
                    });
                }

                if (faceGroupingNode.Distances.Count != faceGroupingNode.Nodes.Count)
                {
                    throw new InvalidDataException("invalid face groups count in face grouping");
                }

                for (int lodId = 0; lodId < faceGroupingNode.Distances.Count; lodId++)
                {
                    List <string> texture = globalTexture;

                    MeshLod lod = new MeshLod();

                    lod.Distance = faceGroupingNode.Distances[lodId];

                    foreach (Node node in faceGroupingNode.Nodes[lodId].Nodes)
                    {
                        switch (node.NodeType)
                        {
                        case NodeType.Texture:
                        {
                            TextureNode textureNode = (TextureNode)node;

                            opt.CreateTexture(textureNode);
                            texture = new List <string>()
                            {
                                textureNode.Name
                            };
                            break;
                        }

                        case NodeType.NodeReference:
                            texture = new List <string>()
                            {
                                ((NodeReferenceNode)node).Reference
                            };
                            break;

                        case NodeType.NodeSwitch:
                        {
                            NodeSwitchNode switchNode = (NodeSwitchNode)node;
                            texture = new List <string>();

                            foreach (Node nodeSwitch in switchNode.Nodes)
                            {
                                switch (nodeSwitch.NodeType)
                                {
                                case NodeType.Texture:
                                {
                                    TextureNode textureNode = (TextureNode)nodeSwitch;

                                    opt.CreateTexture(textureNode);
                                    texture.Add(textureNode.Name);
                                    break;
                                }

                                case NodeType.NodeReference:
                                    texture.Add(((NodeReferenceNode)nodeSwitch).Reference);
                                    break;
                                }
                            }

                            break;
                        }

                        case NodeType.FaceData:
                        {
                            FaceDataNode faceDataNode = (FaceDataNode)node;

                            FaceGroup faceGroup = new FaceGroup();

                            if (texture != null)
                            {
                                foreach (var name in texture)
                                {
                                    faceGroup.Textures.Add(name);
                                }
                            }

                            foreach (var face in faceDataNode.Faces)
                            {
                                faceGroup.Faces.Add(new Face()
                                    {
                                        VerticesIndex           = face.VerticesIndex,
                                        EdgesIndex              = face.EdgesIndex,
                                        TextureCoordinatesIndex = face.TextureCoordinatesIndex,
                                        VertexNormalsIndex      = face.VertexNormalsIndex,
                                        Normal             = face.Normal,
                                        TexturingDirection = face.TexturingDirection,
                                        TexturingMagniture = face.TexturingMagniture
                                    });
                            }

                            foreach (var face in faceGroup.Faces)
                            {
                                if (face.VertexNormalsIndex.A >= mesh.VertexNormals.Count)
                                {
                                    face.VertexNormalsIndex = face.VertexNormalsIndex.SetA(0);
                                }

                                if (face.VertexNormalsIndex.B >= mesh.VertexNormals.Count)
                                {
                                    face.VertexNormalsIndex = face.VertexNormalsIndex.SetB(0);
                                }

                                if (face.VertexNormalsIndex.C >= mesh.VertexNormals.Count)
                                {
                                    face.VertexNormalsIndex = face.VertexNormalsIndex.SetC(0);
                                }

                                if (face.VertexNormalsIndex.D >= mesh.VertexNormals.Count)
                                {
                                    face.VertexNormalsIndex = face.VertexNormalsIndex.SetD(0);
                                }

                                if (face.TextureCoordinatesIndex.A >= mesh.TextureCoordinates.Count)
                                {
                                    face.TextureCoordinatesIndex = face.TextureCoordinatesIndex.SetA(0);
                                }

                                if (face.TextureCoordinatesIndex.B >= mesh.TextureCoordinates.Count)
                                {
                                    face.TextureCoordinatesIndex = face.TextureCoordinatesIndex.SetB(0);
                                }

                                if (face.TextureCoordinatesIndex.C >= mesh.TextureCoordinates.Count)
                                {
                                    face.TextureCoordinatesIndex = face.TextureCoordinatesIndex.SetC(0);
                                }

                                if (face.TextureCoordinatesIndex.D >= mesh.TextureCoordinates.Count)
                                {
                                    face.TextureCoordinatesIndex = face.TextureCoordinatesIndex.SetD(0);
                                }

                                if (face.VerticesIndex.A >= 0 && face.TextureCoordinatesIndex.A < 0)
                                {
                                    face.TextureCoordinatesIndex = face.TextureCoordinatesIndex.SetA(0);
                                }

                                if (face.VerticesIndex.B >= 0 && face.TextureCoordinatesIndex.B < 0)
                                {
                                    face.TextureCoordinatesIndex = face.TextureCoordinatesIndex.SetB(0);
                                }

                                if (face.VerticesIndex.C >= 0 && face.TextureCoordinatesIndex.C < 0)
                                {
                                    face.TextureCoordinatesIndex = face.TextureCoordinatesIndex.SetC(0);
                                }

                                if (face.VerticesIndex.D >= 0 && face.TextureCoordinatesIndex.D < 0)
                                {
                                    face.TextureCoordinatesIndex = face.TextureCoordinatesIndex.SetD(0);
                                }
                            }

                            lod.FaceGroups.Add(faceGroup);

                            texture = null;
                            break;
                        }
                        }
                    }

                    mesh.Lods.Add(lod);
                }

                opt.Meshes.Add(mesh);
            }

            opt.SetFaceGroupTextureWhenEmpty();

            return(opt);
        }