Ejemplo n.º 1
0
    public void AddChild(UINode n)
    {
        if (children == null)
        {
            children = new List<UINode>();
        }

        children.Add(n);
    }
Ejemplo n.º 2
0
    public void LoadUI(UINode uiNode, GameObject parentUI = null)
    {
        Debug.Log("Load UINode:" + uiNode.Prefab);
        GameObject ui = UIManager.LoadUI(uiNode.Prefab, elementCenter, parentUI);

        if (uiNode.Children != null && uiNode.Children.Count > 0)
        {
            GameObject parent = ui;
            foreach (var c in uiNode.Children)
            {
                if (c.ParentElementId != null)
                {
                    var tmp = elementCenter.Get(c.ParentElementId) as GameObject;
                    if (tmp != null)
                    {
                        parent = tmp;
                    }
                }
                LoadUI(c.Prefab, parent);
            }
        }
    }
Ejemplo n.º 3
0
    /// <summary>
    /// Convenience function that figures out the panel's correct change flag by searching the parents.
    /// </summary>
    int GetChangeFlag(UINode start)
    {
        int flag = start.changeFlag;

        if (flag == -1)
        {
            Transform trans = start.trans.parent;
            UINode sub;

            // Keep going until we find a set flag
            for (;;)
            {
                // Check the parent's flag
                if (mChildren.TryGetValue(trans, out sub))
                {
                    flag = sub.changeFlag;
                    trans = trans.parent;

                    // If the flag hasn't been set either, add this child to the hierarchy
                    if (flag == -1) mHierarchy.Add(sub);
                    else break;
                }
                else
                {
                    flag = 0;
                    break;
                }
            }

            // Update the parent flags
            foreach (UINode pc in mHierarchy) pc.changeFlag = flag;
            mHierarchy.Clear();
        }
        return flag;
    }
Ejemplo n.º 4
0
    /// <summary>
    /// Convenience function that figures out the panel's correct change flag by searching the parents.
    /// </summary>

    int GetChangeFlag(UINode start)
    {
        int flag = start.changeFlag;

        if (flag == -1)
        {
            Transform trans = start.trans.parent;
            UINode    sub;

            // Keep going until we find a set flag
            for (;;)
            {
                // Check the parent's flag
#if USE_SIMPLE_DICTIONARY
                if (trans != null && mChildren.TryGetValue(trans, out sub))
                {
#else
                if (trans != null && mChildren.Contains(trans))
                {
                    sub = (UINode)mChildren[trans];
#endif
                    flag  = sub.changeFlag;
                    trans = trans.parent;

                    // If the flag hasn't been set either, add this child to the hierarchy
                    if (flag == -1)
                    {
                        mHierarchy.Add(sub);
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    flag = 0;
                    break;
                }
            }

            // Update the parent flags
            for (int i = 0, imax = mHierarchy.size; i < imax; ++i)
            {
                UINode pc = mHierarchy.buffer[i];
                pc.changeFlag = flag;
            }
            mHierarchy.Clear();
        }
        return(flag);
    }

    /// <summary>
    /// Update the world-to-local transform matrix as well as clipping bounds.
    /// </summary>

    void UpdateTransformMatrix()
    {
        if (mUpdateTime == 0f || mMatrixTime != mUpdateTime)
        {
            mMatrixTime   = mUpdateTime;
            mWorldToLocal = cachedTransform.worldToLocalMatrix;

            if (mClipping != UIDrawCall.Clipping.None)
            {
                Vector2 size = new Vector2(mClipRange.z, mClipRange.w);

                if (size.x == 0f)
                {
                    size.x = (mCam == null) ? Screen.width  : mCam.pixelWidth;
                }
                if (size.y == 0f)
                {
                    size.y = (mCam == null) ? Screen.height : mCam.pixelHeight;
                }

                size *= 0.5f;

                mMin.x = mClipRange.x - size.x;
                mMin.y = mClipRange.y - size.y;
                mMax.x = mClipRange.x + size.x;
                mMax.y = mClipRange.y + size.y;
            }
        }
    }

    /// <summary>
    /// Run through all managed transforms and see if they've changed.
    /// </summary>

    void UpdateTransforms()
    {
        mChangedLastFrame = false;
        bool transformsChanged = false;
        bool shouldCull        = false;

#if UNITY_EDITOR
        shouldCull = (clipping != UIDrawCall.Clipping.None) && (!Application.isPlaying || mUpdateTime > mCullTime);
        if (!Application.isPlaying || !widgetsAreStatic || mWidgetsAdded || shouldCull != mCulled)
#else
        shouldCull = (clipping != UIDrawCall.Clipping.None) && (mUpdateTime > mCullTime);
        if (!widgetsAreStatic || mWidgetsAdded || shouldCull != mCulled)
#endif
        {
#if USE_SIMPLE_DICTIONARY
            foreach (KeyValuePair <Transform, UINode> child in mChildren)
            {
                UINode node = child.Value;
#else
            for (int i = 0, imax = mChildren.Count; i < imax; ++i)
            {
                UINode node = (UINode)mChildren[i];
#endif
                if (node.trans == null)
                {
                    mRemoved.Add(node.trans);
                    continue;
                }

                if (node.HasChanged())
                {
                    node.changeFlag   = 1;
                    transformsChanged = true;
#if UNITY_EDITOR
                    Vector3 s = node.trans.lossyScale;
                    if (s.x == 0)
                    {
                        s.x = 0.0001f;
                    }

                    if (s.y == 0)
                    {
                        s.y = 0.0001f;
                    }

                    if (s.z == 0)
                    {
                        s.z = 0.0001f;
                    }

                    float min = Mathf.Abs(Mathf.Min(s.x, s.y));

                    if (min == 0f)
                    {
                        Debug.LogError("Scale of 0 is invalid! Zero cannot be divided by, which causes problems. Use a small value instead, such as 0.01\n" +
                                       node.trans.lossyScale, node.trans);
                    }
#endif
                }
                else
                {
                    node.changeFlag = -1;
                }
            }

            // Clean up the deleted transforms
            for (int i = 0, imax = mRemoved.Count; i < imax; ++i)
            {
                mChildren.Remove(mRemoved[i]);
            }
            mRemoved.Clear();
        }

        // If the children weren't culled but should be, check their visibility
        if (!mCulled && shouldCull)
        {
            mCheckVisibility = true;
        }

        // If something has changed, propagate the changes *down* the tree hierarchy (to children).
        // An alternative (but slower) approach would be to do a pc.trans.GetComponentsInChildren<UIWidget>()
        // in the loop above, and mark each one as dirty.

        if (mCheckVisibility || transformsChanged || mRebuildAll)
        {
#if USE_SIMPLE_DICTIONARY
            foreach (KeyValuePair <Transform, UINode> child in mChildren)
            {
                UINode pc = child.Value;
#else
            for (int i = 0, imax = mChildren.Count; i < imax; ++i)
            {
                UINode pc = (UINode)mChildren[i];
#endif
                if (pc.widget != null)
                {
                    int visibleFlag = 1;

                    // No sense in checking the visibility if we're not culling anything (as the visibility is always 'true')
                    if (shouldCull || transformsChanged)
                    {
                        // If the change flag has not yet been determined...
                        if (pc.changeFlag == -1)
                        {
                            pc.changeFlag = GetChangeFlag(pc);
                        }

                        // Is the widget visible?
                        if (shouldCull)
                        {
                            visibleFlag = (mCheckVisibility || pc.changeFlag == 1) ? (IsVisible(pc.widget) ? 1 : 0) : pc.visibleFlag;
                        }
                    }

                    // If visibility changed, mark the node as changed as well
                    if (pc.visibleFlag != visibleFlag)
                    {
                        pc.changeFlag = 1;
                    }

                    // If the node has changed and the widget is visible (or was visible before)
                    if (pc.changeFlag == 1 && (visibleFlag == 1 || pc.visibleFlag != 0))
                    {
                        // Update the visibility flag
                        pc.visibleFlag = visibleFlag;
                        Material mat = pc.widget.material;

                        // Add this material to the list of changed materials
                        if (!mChanged.Contains(mat))
                        {
                            mChanged.Add(mat);
                            mChangedLastFrame = true;
                        }
                    }
                }
            }
        }
        mCulled          = shouldCull;
        mCheckVisibility = false;
        mWidgetsAdded    = false;
    }

    /// <summary>
    /// Update all widgets and rebuild their geometry if necessary.
    /// </summary>

    void UpdateWidgets()
    {
#if USE_SIMPLE_DICTIONARY
        foreach (KeyValuePair <Transform, UINode> c in mChildren)
        {
            UINode pc = c.Value;
#else
        for (int i = 0, imax = mChildren.Count; i < imax; ++i)
        {
            UINode pc = (UINode)mChildren[i];
#endif
            UIWidget w = pc.widget;

            // If the widget is visible, update it
            if (pc.visibleFlag == 1 && w != null && w.UpdateGeometry(ref mWorldToLocal, (pc.changeFlag == 1), generateNormals))
            {
                // We will need to refill this buffer
                if (!mChanged.Contains(w.material))
                {
                    mChanged.Add(w.material);
                    mChangedLastFrame = true;
                }
            }
            pc.changeFlag = 0;
        }
    }

    /// <summary>
    /// Update the clipping rect in the shaders and draw calls' positions.
    /// </summary>

    public void UpdateDrawcalls()
    {
        Vector4 range = Vector4.zero;

        if (mClipping != UIDrawCall.Clipping.None)
        {
            range = new Vector4(mClipRange.x, mClipRange.y, mClipRange.z * 0.5f, mClipRange.w * 0.5f);
        }

        if (range.z == 0f)
        {
            range.z = Screen.width * 0.5f;
        }
        if (range.w == 0f)
        {
            range.w = Screen.height * 0.5f;
        }

        RuntimePlatform platform = Application.platform;

        if (platform == RuntimePlatform.WindowsPlayer ||
            //platform == RuntimePlatform.WindowsWebPlayer ||
            platform == RuntimePlatform.WindowsEditor)
        {
            range.x -= 0.5f;
            range.y += 0.5f;
        }

        Transform t = cachedTransform;

        for (int i = 0, imax = mDrawCalls.size; i < imax; ++i)
        {
            UIDrawCall dc = mDrawCalls.buffer[i];
            dc.clipping     = mClipping;
            dc.clipRange    = range;
            dc.clipSoftness = mClipSoftness;
            dc.depthPass    = depthPass;

            // Set the draw call's transform to match the panel's.
            // Note that parenting directly to the panel causes unity to crash as soon as you hit Play.
            Transform dt = dc.transform;
            dt.position   = t.position;
            dt.rotation   = t.rotation;
            dt.localScale = t.lossyScale;
        }
    }

    /// <summary>
    /// Set the draw call's geometry responsible for the specified material.
    /// </summary>

    void Fill(Material mat)
    {
        // Cleanup deleted widgets
        for (int i = mWidgets.size; i > 0;)
        {
            if (mWidgets[--i] == null)
            {
                mWidgets.RemoveAt(i);
            }
        }

        // Fill the buffers for the specified material
        for (int i = 0, imax = mWidgets.size; i < imax; ++i)
        {
            UIWidget w = mWidgets.buffer[i];

            if (w.visibleFlag == 1 && w.material == mat)
            {
                UINode node = GetNode(w.cachedTransform);

                if (node != null)
                {
                    if (generateNormals)
                    {
                        w.WriteToBuffers(mVerts, mUvs, mCols, mNorms, mTans);
                    }
                    else
                    {
                        w.WriteToBuffers(mVerts, mUvs, mCols, null, null);
                    }
                }
                else
                {
                    Debug.LogError("No transform found for " + NGUITools.GetHierarchy(w.gameObject), this);
                }
            }
        }

        if (mVerts.size > 0)
        {
            // Rebuild the draw call's mesh
            UIDrawCall dc = GetDrawCall(mat, true);
            dc.depthPass = depthPass;
            dc.Set(mVerts, generateNormals ? mNorms : null, generateNormals ? mTans : null, mUvs, mCols);
        }
        else
        {
            // There is nothing to draw for this material -- eliminate the draw call
            UIDrawCall dc = GetDrawCall(mat, false);

            if (dc != null)
            {
                mDrawCalls.Remove(dc);
                NGUITools.DestroyImmediate(dc.gameObject);
            }
        }

        // Cleanup
        mVerts.Clear();
        mNorms.Clear();
        mTans.Clear();
        mUvs.Clear();
        mCols.Clear();
    }

    /// <summary>
    /// Main update function
    /// </summary>
    bool needUpdate = true;//Maifeo

    void LateUpdate()
    {
        //if (Application.platform != RuntimePlatform.WindowsEditor)
        //{
        //    needUpdate = !needUpdate;
        //    if (!needUpdate)
        //    {
        //        return;
        //    }
        //}


        mUpdateTime = Time.realtimeSinceStartup;
        UpdateTransformMatrix();
        UpdateTransforms();

        // Always move widgets to the panel's layer
        if (mLayer != gameObject.layer)
        {
            mLayer = gameObject.layer;
            UICamera uic = UICamera.FindCameraForLayer(mLayer);
            mCam = (uic != null) ? uic.cachedCamera : NGUITools.FindCameraForLayer(mLayer);
            SetChildLayer(cachedTransform, mLayer);
            for (int i = 0, imax = drawCalls.size; i < imax; ++i)
            {
                mDrawCalls.buffer[i].gameObject.layer = mLayer;
            }
        }

        UpdateWidgets();

        // If the depth has changed, we need to re-sort the widgets
        if (mDepthChanged)
        {
            mDepthChanged = false;
            mWidgets.Sort(UIWidget.CompareFunc);
        }

        // Fill the draw calls for all of the changed materials
        for (int i = 0, imax = mChanged.size; i < imax; ++i)
        {
            Fill(mChanged.buffer[i]);
        }

        // Update the clipping rects
        UpdateDrawcalls();
        mChanged.Clear();
        mRebuildAll = false;

#if UNITY_EDITOR
        mScreenSize = new Vector2(Screen.width, Screen.height);
#endif
    }
Ejemplo n.º 5
0
 public virtual void InitUI(UINode rootNode)
 {
     Init(IdIndex++);
 }
Ejemplo n.º 6
0
        public async Task <UIModel> ConvertTopologyToUIModel(TopologyModel topology)
        {
            string verboseMessage = $"{baseLogString} ConvertTopologyToUIModel method called.";

            Logger.LogVerbose(verboseMessage);

            if (topology == null)
            {
                string message = $"{baseLogString} ConvertTopologyToUIModel => Provider topology is null.";
                Logger.LogError(message);
                throw new Exception(message);
            }

            UIModel      uIModel = new UIModel();
            Stack <long> stack   = new Stack <long>();

            Logger.LogDebug($"{baseLogString} ConvertTopologyToUIModel => Calling GetReclosers method from model provider client.");
            var modelProviderClient = CeModelProviderClient.CreateClient();
            var reclosers           = await modelProviderClient.GetReclosers();

            Logger.LogDebug($"{baseLogString} ConvertTopologyToUIModel => GetReclosers method from model provider client has been called successfully.");

            uIModel.FirstNode = topology.FirstNode;
            stack.Push(topology.FirstNode);
            long nextElementGid;

            while (stack.Count > 0)
            {
                nextElementGid = stack.Pop();
                if (topology.GetElementByGid(nextElementGid, out ITopologyElement element))
                {
                    if (!reclosers.Contains(nextElementGid))
                    {
                        foreach (var child in element.SecondEnd)
                        {
                            long nextElement = child.Id;
                            if (ModelCodeHelper.ExtractTypeFromGlobalId(child.Id) == 0)
                            {
                                if (child is Field field && field.Members.Count > 0)
                                {
                                    nextElement = field.Members.First().Id;
                                }
                                else
                                {
                                    string message = $"{baseLogString} ConvertTopologyToUIModel => Error while getting field in Topology to UIModel convert. Element is not field or field is empty.";
                                    Logger.LogError(message);
                                    throw new Exception(message);
                                }
                            }

                            uIModel.AddRelation(element.Id, nextElement);
                            stack.Push(nextElement);
                        }
                    }

                    List <UIMeasurement> measurements = new List <UIMeasurement>();
                    foreach (var measurementGid in element.Measurements.Keys)
                    {
                        DMSType type = (DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(measurementGid);

                        if (type == DMSType.ANALOG)
                        {
                            Logger.LogDebug($"{baseLogString} ConvertTopologyToUIModel => Calling GetAnalogMeasurement method from measurement provider client for measurement GID {measurementGid:X16}.");
                            var measurementProviderClient       = MeasurementProviderClient.CreateClient();
                            AnalogMeasurement analogMeasurement = await measurementProviderClient.GetAnalogMeasurement(measurementGid);

                            Logger.LogDebug($"{baseLogString} ConvertTopologyToUIModel => GetAnalogMeasurement method from measurement provider client has been called successfully.");

                            measurements.Add(new UIMeasurement()
                            {
                                Gid       = analogMeasurement.Id,
                                Type      = analogMeasurement.GetMeasurementType(),
                                Value     = analogMeasurement.GetCurrentValue(),
                                AlarmType = analogMeasurement.GetAlarmType()
                            });
                        }
                        else if (type == DMSType.DISCRETE)
                        {
                            Logger.LogDebug($"{baseLogString} ConvertTopologyToUIModel => Calling GetDiscreteMeasurement method from measurement provider client for measurement GID {measurementGid:X16}.");
                            var measurementProviderClient           = MeasurementProviderClient.CreateClient();
                            DiscreteMeasurement discreteMeasurement = await measurementProviderClient.GetDiscreteMeasurement(measurementGid);

                            Logger.LogDebug($"{baseLogString} ConvertTopologyToUIModel => GetDiscreteMeasurement method from measurement provider client has been called successfully.");

                            measurements.Add(new UIMeasurement()
                            {
                                Gid       = discreteMeasurement.Id,
                                Type      = discreteMeasurement.GetMeasurementType(),
                                Value     = discreteMeasurement.GetCurrentValue(),
                                AlarmType = AlarmType.NO_ALARM
                            });
                        }
                        else
                        {
                            Logger.LogDebug($"{baseLogString} ConvertTopologyToUIModel => Calling GetDiscreteMeasurement method from measurement provider client for measurement GID {measurementGid:X16}.");
                            var measurementProviderClient           = MeasurementProviderClient.CreateClient();
                            DiscreteMeasurement discreteMeasurement = await measurementProviderClient.GetDiscreteMeasurement(measurementGid);

                            Logger.LogDebug($"{baseLogString} ConvertTopologyToUIModel => GetDiscreteMeasurement method from measurement provider client has been called successfully.");

                            measurements.Add(new UIMeasurement()
                            {
                                Gid       = discreteMeasurement.Id,
                                Type      = discreteMeasurement.GetMeasurementType(),
                                Value     = discreteMeasurement.GetCurrentValue(),
                                AlarmType = AlarmType.NO_ALARM
                            });
                        }
                    }


                    if (!uIModel.Nodes.ContainsKey(element.Id))
                    {
                        UINode newUINode = new UINode()
                        {
                            Id             = element.Id,
                            Name           = element.Name,
                            Mrid           = element.Mrid,
                            Description    = element.Description,
                            DMSType        = element.DmsType,
                            NominalVoltage = element.NominalVoltage,
                            Measurements   = measurements,
                            IsActive       = element.IsActive,
                            IsRemote       = element.IsRemote,
                            NoReclosing    = element.NoReclosing
                        };
                        uIModel.AddNode(newUINode);
                    }
                }
Ejemplo n.º 7
0
    private void UpdateTransforms()
    {
        this.mChangedLastFrame = false;
        bool flag  = false;
        bool flag2 = Time.realtimeSinceStartup > this.mCullTime;

        if (!this.widgetsAreStatic || (flag2 != this.mCulled))
        {
            int num   = 0;
            int count = this.mChildren.Count;
            while (num < count)
            {
                UINode node = (UINode)this.mChildren[num];
                if (node.trans == null)
                {
                    this.mRemoved.Add(node.trans);
                }
                else if (node.HasChanged())
                {
                    node.changeFlag = 1;
                    flag            = true;
                }
                else
                {
                    node.changeFlag = -1;
                }
                num++;
            }
            int num3 = 0;
            int num4 = this.mRemoved.Count;
            while (num3 < num4)
            {
                this.mChildren.Remove(this.mRemoved[num3]);
                num3++;
            }
            this.mRemoved.Clear();
        }
        if (!this.mCulled && flag2)
        {
            this.mCheckVisibility = true;
        }
        if ((this.mCheckVisibility || flag) || this.mRebuildAll)
        {
            int num5 = 0;
            int num6 = this.mChildren.Count;
            while (num5 < num6)
            {
                UINode start = (UINode)this.mChildren[num5];
                if (start.widget != null)
                {
                    int num7 = 1;
                    if (flag2 || flag)
                    {
                        if (start.changeFlag == -1)
                        {
                            start.changeFlag = this.GetChangeFlag(start);
                        }
                        if (flag2)
                        {
                            num7 = (!this.mCheckVisibility && (start.changeFlag != 1)) ? start.visibleFlag : (!this.IsVisible(start.widget) ? 0 : 1);
                        }
                    }
                    if (start.visibleFlag != num7)
                    {
                        start.changeFlag = 1;
                    }
                    if ((start.changeFlag == 1) && ((num7 == 1) || (start.visibleFlag != 0)))
                    {
                        start.visibleFlag = num7;
                        UIMaterial item = start.widget.material;
                        if (!this.mChanged.Contains(item))
                        {
                            this.mChanged.Add(item);
                            this.mChangedLastFrame = true;
                        }
                    }
                }
                num5++;
            }
        }
        this.mCulled          = flag2;
        this.mCheckVisibility = false;
    }
Ejemplo n.º 8
0
        /// <summary>
        /// Add or remove DaggerBasePins depending on the IPins in the filter
        /// </summary>
        public void SyncPins()
        {
            bool altered = false;

            // get the pins and convert to DaggerBasePins if they dont exisit yet
            _pins = GetPins();
            foreach (IPin pin in _pins)
            {
                PinDirection pd;
                pin.QueryDirection(out pd);
                if (pd == PinDirection.Input)
                {
                    if (GetDaggerPin(pin) == null)
                    {
                        DSInputPin inpin = new DSInputPin(pin);
                        InputPins.Add(inpin);
                        altered = true;
                    }
                }
                else
                {
                    if (GetDaggerPin(pin) == null)
                    {
                        DSOutputPin outpin = new DSOutputPin(pin);
                        OutputPins.Add(outpin);
                        altered = true;
                    }
                }
            }

            // remove any DaggerDSPins that may have vanished
            for (int i = InputPins.Count - 1; i > -1; i--)
            {
                if (!_pins.Contains((InputPins[i] as DSInputPin)._pin))
                {
                    // force the disconnect
                    InputPins[i].Disconnect(true);
                    Marshal.ReleaseComObject((InputPins[i] as DSInputPin)._pin);
                    (InputPins[i] as DSInputPin)._pin = null;
                    InputPins.Remove(InputPins[i]);
                    altered = true;
                }

                // check the major media format of the pin and set it's data type
                Type majorType = typeof(PinDataTypes.Unknown);
                bool whoops    = false;
                try
                {
                    majorType = GetPinMajorMediaType((InputPins[i] as DSInputPin)._pin);
                }
                catch
                {
                    // the pin was removed by directshow, ignore changing the data type
                    whoops = true;
                }
                finally
                {
                    if (!whoops)
                    {
                        if (InputPins[i].DataType != majorType)
                        {
                            InputPins[i].DataType = majorType;
                            altered = true;
                        }
                    }
                }
            }

            for (int i = OutputPins.Count - 1; i > -1; i--)
            {
                if (!_pins.Contains((OutputPins[i] as DSOutputPin)._pin))
                {
                    // force the disconnect
                    OutputPins[i].Disconnect(true);
                    Marshal.ReleaseComObject((OutputPins[i] as DSOutputPin)._pin);
                    (OutputPins[i] as DSOutputPin)._pin = null;
                    OutputPins.Remove(OutputPins[i]);
                    altered = true;
                }

                // check the major media format of the pin and set it's data type
                Type majorType = typeof(PinDataTypes.Unknown);
                bool whoops    = false;
                try
                {
                    majorType = GetPinMajorMediaType((OutputPins[i] as DSOutputPin)._pin);
                }
                catch
                {
                    // the pin was removed by directshow, ignore changing the data type
                    whoops = true;
                }
                finally
                {
                    if (!whoops)
                    {
                        if (OutputPins[i].DataType != majorType)
                        {
                            OutputPins[i].DataType = majorType;
                            altered = true;
                        }
                    }
                }
            }

            // if we altered anything, update the filter's ui elements and redraw the graph
            if (altered)
            {
                if (this.UINode != null)
                {
                    UINode.CalculateLayout();
                    if ((UINode as DaggerUINode).Parent != null)
                    {
                        // update the graph ui if the uinode is still part of a uigraph
                        (UINode as DaggerUINode).Parent.Invalidate();
                    }
                }
            }

            // tell the ui node to update any pin property pages
            if (UINode != null && UINode is DSFilterNodeUI)
            {
                (UINode as DSFilterNodeUI).SyncPinPropertyPages(null);
            }
        }
        private void enterLeaderBoard()
        {
            for (int i = 0; i < 20; i++)
            {
                playThemeSong();
            }

            State = GameState.Leaderboard;
            Mode  = GameMode.Demo;

            // game world
            World = new World2D(0, new RectInt(Vector2Int.One, c_GameWindowSize));
            m_LeaderBoardUINode = UINode.Engine.Instance.CreateNode(new RectInt(0, 0, 1, 1));

            int boardX     = 10;
            int boardWidth = World.TowerTopNode.Bounds.Width - 20;

            // create Hint UI
            var hintNode = UINode.Engine.Instance.CreateNode(new RectInt(boardX, 27, boardWidth, 1), null, "Hint-CanvasNode");
            var canvas   = hintNode.AddUIComponent <SingleColorCanvas>();

            canvas.CanvasPixelColor = new PixelColor(ConsoleColor.Black, ConsoleColor.DarkGray);

            var hintTextNode = UINode.Engine.Instance.CreateNode(new RectInt(0, 0, boardWidth, 1), hintNode, "Hint-TextBoxNode");
            var hintTextBox  = hintTextNode.AddUIComponent <TextBox>();

            hintTextBox.text = "ESC: main menu";
            hintTextBox.verticalAlignment   = TextBox.VerticalAlignment.Middle;
            hintTextBox.horizontalAlignment = TextBox.HorizontalAlignment.Center;


            int showCount = 5;

            // single player
            string singlePlayerBoards = "SINGLE PLAYER\n";

            for (int i = 0; i < showCount; i++)
            {
                if (i < SaveProgress.Data.SinglePlayerScores.Count)
                {
                    var    tuple = SaveProgress.Data.SinglePlayerScores[i];
                    string line  = string.Format("{0} -   {1, -12}  {2:D8}", i + 1, tuple.Item1, tuple.Item2);
                    singlePlayerBoards += "\n" + line;
                }
                else
                {
                    string line = string.Format("{0} -   {1, -12}  {2:D8}", i + 1, "empty", 0);
                    singlePlayerBoards += "\n" + line;
                }
            }

            var boardcanvasNode = UINode.Engine.Instance.CreateNode(new RectInt(boardX, 4, boardWidth, 7), m_LeaderBoardUINode, "TutorialNode");

            canvas = boardcanvasNode.AddUIComponent <SingleColorCanvas>();
            canvas.CanvasPixelColor = new PixelColor(ConsoleColor.DarkRed, ConsoleColor.Yellow);

            var textNode = UINode.Engine.Instance.CreateNode(new RectInt(0, 0, boardWidth, 7), boardcanvasNode, "TutorialNode");
            var unlitBg  = textNode.AddUIComponent <UnlitBox>();

            unlitBg.UnlitCharacter = ' ';
            var textBox = textNode.AddUIComponent <TextBox>();

            textBox.text = singlePlayerBoards;
            textBox.horizontalAlignment = TextBox.HorizontalAlignment.Center;
            textBox.verticalAlignment   = TextBox.VerticalAlignment.Top;


            // single player
            string twoPlayerBoards = "TWO PLAYERS COOP\n";

            for (int i = 0; i < showCount; i++)
            {
                if (i < SaveProgress.Data.TwoPlayerScores.Count)
                {
                    var    tuple = SaveProgress.Data.TwoPlayerScores[i];
                    string line  = string.Format("{0} -   {1, -12}  {2:D8}", i + 1, tuple.Item1, tuple.Item2);
                    twoPlayerBoards += "\n" + line;
                }
                else
                {
                    string line = string.Format("{0} -   {1, -12}  {2:D8}", i + 1, "empty", 0);
                    twoPlayerBoards += "\n" + line;
                }
            }

            boardcanvasNode         = UINode.Engine.Instance.CreateNode(new RectInt(boardX, 14, boardWidth, 7), m_LeaderBoardUINode, "TutorialNode");
            canvas                  = boardcanvasNode.AddUIComponent <SingleColorCanvas>();
            canvas.CanvasPixelColor = new PixelColor(ConsoleColor.DarkRed, ConsoleColor.Yellow);

            textNode = UINode.Engine.Instance.CreateNode(new RectInt(0, 0, boardWidth, 7), boardcanvasNode, "TutorialNode");
            unlitBg  = textNode.AddUIComponent <UnlitBox>();
            unlitBg.UnlitCharacter = ' ';
            textBox      = textNode.AddUIComponent <TextBox>();
            textBox.text = twoPlayerBoards;
            textBox.horizontalAlignment = TextBox.HorizontalAlignment.Center;
            textBox.verticalAlignment   = TextBox.VerticalAlignment.Top;
        }
Ejemplo n.º 10
0
 public override bool Add(UINode node, bool update = false)
 {
     throw new NotSupportedException("this method has been overrided");
 }
Ejemplo n.º 11
0
        public UINode DrawLayer(Layer layer, UINode parent)
        {
            UINode        node      = PSDImportUtility.InstantiateItem(PSDImporterConst.PREFAB_PATH_DROPDOWN, layer.name, parent);
            Dropdown      dropdown  = node.InitComponent <Dropdown>();
            ScrollRect    scrllRect = dropdown.template.GetComponent <ScrollRect>();
            RectTransform content   = scrllRect.content;
            Toggle        toggle    = content.GetComponentInChildren <Toggle>();

            UINode childNode = new UINode(dropdown.template, node);

            childNode.transform.SetParent(PSDImportUtility.canvas.transform);
            childNode.anchoType = UINode.AnchoType.Down | UINode.AnchoType.XStretch;
            //由于设置相对坐标需要,所以修改了部分预制体的状态
            childNode.ReprocessEvent = () => {
                RectTransform rt = childNode.InitComponent <RectTransform>();
                rt.pivot            = new Vector2(0.5f, 1);
                rt.anchoredPosition = Vector3.zero;
            };
            for (int i = 0; i < layer.images.Length; i++)
            {
                Image  image     = layer.images[i];
                string lowerName = image.name.ToLower();
                if (lowerName.StartsWith("b1_"))
                {
                    PSDImportUtility.SetPictureOrLoadColor(image, dropdown.image);
                    PSDImportUtility.SetRectTransform(image, dropdown.GetComponent <RectTransform>());
                    dropdown.name = layer.name;
                }
                else if (lowerName.StartsWith("b2_"))
                {
                    PSDImportUtility.SetPictureOrLoadColor(image, dropdown.template.GetComponent <Graphic>());
                    PSDImportUtility.SetRectTransform(image, dropdown.template);
                }
                else if (lowerName.StartsWith("b3_"))
                {
                    UnityEngine.UI.Image itemimage = (UnityEngine.UI.Image)toggle.targetGraphic;
                    PSDImportUtility.SetPictureOrLoadColor(image, itemimage);
                    content.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, image.size.height);
                }
                else if (lowerName.StartsWith("l1_"))
                {
                    PSDImportUtility.SetPictureOrLoadColor(image, dropdown.captionText);
                    float size;
                    if (float.TryParse(image.arguments[2], out size))
                    {
                        dropdown.captionText.fontSize = (int)size;
                    }
                    dropdown.captionText.text = image.arguments[3];
                }
                else if (lowerName.StartsWith("l2_"))
                {
                    PSDImportUtility.SetPictureOrLoadColor(image, dropdown.itemText);
                    float size;
                    if (float.TryParse(image.arguments[2], out size))
                    {
                        dropdown.itemText.fontSize = (int)size;
                    }
                    dropdown.itemText.text = image.arguments[3];
                }
                else if (lowerName.StartsWith("m_"))
                {
                    UnityEngine.UI.Image mask = (UnityEngine.UI.Image)toggle.graphic;
                    PSDImportUtility.SetPictureOrLoadColor(image, mask);
                }
                else
                {
                    ctrl.DrawImage(image, node);
                }
            }

            for (int i = 0; i < layer.layers.Length; i++)
            {
                Layer  child     = layer.layers[i];
                string lowerName = child.name;
                if (lowerName.StartsWith("vb_"))
                {
                    UINode barNode = ctrl.DrawLayer(child, childNode);
                    scrllRect.verticalScrollbar           = barNode.InitComponent <Scrollbar>();
                    scrllRect.verticalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHide;
                }
                else
                {
                    ctrl.DrawLayer(child, node);
                }
            }

            return(node);
        }
Ejemplo n.º 12
0
    void Update()
    {
        if (gridNodes != null)
        {
            // Next Update Cycle, check node
            if (leftMouseClicked)
            {
                foreach (UINode node in gridNodes)
                {
                    if (node.textField.GetComponent <InputField>().isFocused)
                    {
                        focusedNode = node;
                        focusedBox  = focusedNode.textField;
                        focusedBox.GetComponent <InputField>().Select();
                        break;
                    }
                }

                leftMouseClicked = false;
            }

            // Check for key presses

            if (Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift))
            {
                shiftPressed = true;
            }

            if (Input.GetMouseButtonDown(0))
            {
                leftMouseClicked = true;
            }

            // Checks for Tab pressed
            if (Input.GetKeyDown(KeyCode.Tab))
            {
                if (focusedBox == null)
                {
                    focusedNode = gridNodes[0, 0];
                    focusedBox  = focusedNode.textField;
                    focusedBox.GetComponent <InputField>().Select();
                }
                else
                {
                    if (shiftPressed)
                    {
                        focusedNode = focusedNode.GetPreviousNode();
                        focusedBox  = focusedNode.textField;
                        focusedBox.GetComponent <InputField>().Select();
                    }
                    else
                    {
                        focusedNode = focusedNode.GetNextNode();
                        focusedBox  = focusedNode.textField;
                        focusedBox.GetComponent <InputField>().Select();
                    }
                }
            }

            if (Input.GetKeyDown(KeyCode.Return))
            {
                RunSolver();
            }
        } //

        if (Input.GetKeyUp(KeyCode.LeftShift) || Input.GetKeyUp(KeyCode.RightShift))
        {
            shiftPressed = false;
        }

        // Exempt from code, don't put code here
    }
Ejemplo n.º 13
0
 private int GetChangeFlag(UINode start)
 {
     int num = start.changeFlag;
     if (num == -1)
     {
         Transform transforms = start.trans.parent;
         while (true)
         {
             if (!this.mChildren.Contains(transforms))
             {
                 num = 0;
                 break;
             }
             else
             {
                 UINode item = (UINode)this.mChildren[transforms];
                 num = item.changeFlag;
                 transforms = transforms.parent;
                 if (num != -1)
                 {
                     break;
                 }
                 else
                 {
                     UIPanel.mHierarchy.Add(item);
                 }
             }
         }
         int num1 = 0;
         int count = UIPanel.mHierarchy.Count;
         while (num1 < count)
         {
             UIPanel.mHierarchy[num1].changeFlag = num;
             num1++;
         }
         UIPanel.mHierarchy.Clear();
     }
     return num;
 }
Ejemplo n.º 14
0
 private UINode AddTransform(Transform t)
 {
     UINode uINode = null;
     UINode item = null;
     while (t != null && t != this.cachedTransform)
     {
         if (!this.mChildren.Contains(t))
         {
             uINode = new UINode(t);
             if (item == null)
             {
                 item = uINode;
             }
             this.mChildren.Add(t, uINode);
             t = t.parent;
         }
         else
         {
             if (item == null)
             {
                 item = (UINode)this.mChildren[t];
             }
             break;
         }
     }
     return item;
 }
Ejemplo n.º 15
0
 public NodeNotAddedToRootExceptionArgs(UINode currNode, UINode currRoot, string msg = "This node has been not added to root of Window System")
 {
     this.CurrNode = currNode;
     this.CurrRoot = CurrRoot;
     this.Msg      = msg;
 }
Ejemplo n.º 16
0
        private void enterInGameScene()
        {
            State       = GameState.InGame;
            IsFinished  = false;
            IsPaused    = false;
            m_InputName = new StringBuilder("");

            // frame UI
            m_PlayGroundNode = UINode.Engine.Instance.CreateNode(new RectInt(Vector2Int.Zero, c_GameWindowSize + Vector2Int.One), null, "Playground-Node");
            var playgroundCanvas = m_PlayGroundNode.AddUIComponent <SingleColorCanvas>();

            playgroundCanvas.CanvasPixelColor = new PixelColor(ConsoleColor.Black, ConsoleColor.White);

            var playgroundLayoutNode = UINode.Engine.Instance.CreateNode(new RectInt(Vector2Int.Zero, c_GameWindowSize + Vector2Int.One), m_PlayGroundNode, "PlaygroundLayout-Node");
            var layoutBitmap         = playgroundLayoutNode.AddUIComponent <Bitmap>();

            layoutBitmap.LoadFromFile("./Assets/Layout.txt", Bitmap.DrawType.Sliced);

            // game world
            World = new World2D((Mode == GameMode.SinglePlayer)? 1 : 2, new RectInt(Vector2Int.One, c_GameWindowSize));

            // register player dead event
            AliveCounter = new HashSet <int>();
            foreach (var character in World.Characters)
            {
                int id = character.Id;
                AliveCounter.Add(id);
                character.OnDie += () => handleOnPlayerDie(id);
            }

            // game UI
            RectInt gameUISize = new RectInt(new Vector2Int(0, c_GameWindowSize.Y + 1), new Vector2Int(c_GameWindowSize.X + 1, 5));

            var uiNode = UINode.Engine.Instance.CreateNode(gameUISize, null, "Game UI");
            var canvas = uiNode.AddUIComponent <SingleColorCanvas>();

            canvas.CanvasPixelColor = new PixelColor(ConsoleColor.DarkGray, ConsoleColor.White);

            RectInt panelBounds = new RectInt(new Vector2Int(0, 0), new Vector2Int(c_GameWindowSize.X + 1, 5));

            var layoutNode = UINode.Engine.Instance.CreateNode(panelBounds, uiNode, "Game UI");
            var layout     = layoutNode.AddUIComponent <Bitmap>();

            layout.LoadFromFile("./Assets/Layout-Empty.txt", Bitmap.DrawType.Sliced);

            // register character hp , create hp ui
            m_HpTexts    = new List <TextBox>();
            m_HpBarTexts = new List <TextBox>();
            for (int i = 0; i < World.Characters.Count; i++)
            {
                var character = World.Characters[i];
                character.OnHealthChanged += (int health) => handleOnCharacterHpChanged(character.Id, health);

                var textNode = UINode.Engine.Instance.CreateNode(new RectInt(3, 1 + i * 2, 10, 1), uiNode, "Game UI");
                var text     = textNode.AddUIComponent <TextBox>();
                text.text = string.Format("P{0} HP: {1, 2}/{2, 2}", i + 1, 10, Character.c_MaxHealth);
                text.horizontalAlignment = TextBox.HorizontalAlignment.Left;
                text.verticalAlignment   = TextBox.VerticalAlignment.Middle;

                m_HpTexts.Add(text);

                var hpBarCanvasNode = UINode.Engine.Instance.CreateNode(new RectInt(18, 1 + i * 2, 20, 1), uiNode, "Game UI");
                var hpBarCanvas     = hpBarCanvasNode.AddUIComponent <SingleColorCanvas>();
                hpBarCanvas.CanvasPixelColor = new PixelColor(ConsoleColor.DarkGreen, ConsoleColor.DarkGreen);

                var hpBarBackNode = UINode.Engine.Instance.CreateNode(new RectInt(0, 0, 20, 1), hpBarCanvasNode, "Game UI - Text");
                text      = hpBarBackNode.AddUIComponent <TextBox>();
                text.text = new string("                    ");

                var hpBarInsideCanvasNode = UINode.Engine.Instance.CreateNode(new RectInt(18, 1 + i * 2, 20, 1), uiNode, "Game UI - Bar");
                var hpBarInsideCanvas     = hpBarInsideCanvasNode.AddUIComponent <SingleColorCanvas>();
                hpBarInsideCanvas.CanvasPixelColor = new PixelColor(ConsoleColor.Yellow, ConsoleColor.Yellow);

                var actualInsideTextNode = UINode.Engine.Instance.CreateNode(new RectInt(0, 0, 20, 1), hpBarInsideCanvasNode, "Game UI - Bar -Text");
                text      = actualInsideTextNode.AddUIComponent <TextBox>();
                text.text = new string("                    ");

                m_HpBarTexts.Add(text);
            }

            // add level ui
            var lvlUINode = UINode.Engine.Instance.CreateNode(new RectInt(39, 1, 10, 3), uiNode);

            m_LevelText      = lvlUINode.AddUIComponent <TextBox>();
            m_LevelText.text = "LEVEL\n000";
            m_LevelText.horizontalAlignment = TextBox.HorizontalAlignment.Center;
            m_LevelText.verticalAlignment   = TextBox.VerticalAlignment.Middle;

            World.OnTotalLevelChanged += handleOnTotalLevelChanged;

            // create Hint UI
            var hintNode = UINode.Engine.Instance.CreateNode(new RectInt(0, World.TowerTopNode.Bounds.Size.Y + 7, World.TowerTopNode.Bounds.Size.X, 1), null, "Hint-CanvasNode");

            canvas = hintNode.AddUIComponent <SingleColorCanvas>();
            canvas.CanvasPixelColor = new PixelColor(ConsoleColor.Black, ConsoleColor.DarkGray);

            var hintTextNode = UINode.Engine.Instance.CreateNode(new RectInt(0, 0, World.TowerTopNode.Bounds.Size.X, 1), hintNode, "Hint-TextBoxNode");
            var hintTextBox  = hintTextNode.AddUIComponent <TextBox>();

            hintTextBox.text = "F1: turn on/off optimized mode in game\nF2: pause/resume game";
            hintTextBox.verticalAlignment   = TextBox.VerticalAlignment.Middle;
            hintTextBox.horizontalAlignment = TextBox.HorizontalAlignment.Center;

            // create GAME OVER UI
            var gameOverNode = UINode.Engine.Instance.CreateNode(new RectInt(0, World.TowerTopNode.Bounds.Size.Y / 2, World.TowerTopNode.Bounds.Size.X + 1, 5), null, "GO-CanvasNode");

            m_GameOverCanvas = gameOverNode.AddUIComponent <SingleColorCanvas>();
            m_GameOverCanvas.CanvasPixelColor = new PixelColor(ConsoleColor.DarkRed, ConsoleColor.Yellow);

            var goUnlitBoardNode = UINode.Engine.Instance.CreateNode(new RectInt(0, 0, World.TowerTopNode.Bounds.Size.X + 1, 5), gameOverNode, "GO-UnlitNode");
            var goUnlitBox       = goUnlitBoardNode.AddUIComponent <UnlitBox>();

            goUnlitBox.UnlitCharacter = ' ';

            var goTextNode = UINode.Engine.Instance.CreateNode(new RectInt(0, 0, World.TowerTopNode.Bounds.Size.X + 1, 5), gameOverNode, "GO-TextBoxNode");

            m_GameOverText      = goTextNode.AddUIComponent <TextBox>();
            m_GameOverText.text = "GAME OVER\n\n\npress enter to confirm";
            m_GameOverText.verticalAlignment   = TextBox.VerticalAlignment.Top;
            m_GameOverText.horizontalAlignment = TextBox.HorizontalAlignment.Center;

            m_InputFieldCanvasNode = UINode.Engine.Instance.CreateNode(new RectInt(0, 2, World.TowerTopNode.Bounds.Size.X + 1, 1), gameOverNode, "InputCanvasNode");
            canvas = m_InputFieldCanvasNode.AddUIComponent <SingleColorCanvas>();
            canvas.CanvasPixelColor = new PixelColor(ConsoleColor.Red, ConsoleColor.Yellow);

            var inputUnlitBoxNode = UINode.Engine.Instance.CreateNode(new RectInt(13, 0, 24, 1), m_InputFieldCanvasNode, "InputNode");

            inputUnlitBoxNode.AddUIComponent <UnlitBox>().UnlitCharacter = ' ';

            var inputTextNode = UINode.Engine.Instance.CreateNode(new RectInt(0, 0, World.TowerTopNode.Bounds.Size.X + 1, 1), inputUnlitBoxNode, "InputNode");

            m_InputText      = inputTextNode.AddUIComponent <TextBox>();
            m_InputText.text = "PLEASE INPUT YOUR NAME";
            m_InputText.verticalAlignment   = TextBox.VerticalAlignment.Middle;
            m_InputText.horizontalAlignment = TextBox.HorizontalAlignment.Center;

            gameOverNode.IsActive           = false;
            m_InputFieldCanvasNode.IsActive = false;

            // Setup bg settings
            World.BackgroundImageNode.IsActive = !m_OptimizedMode;
        }
Ejemplo n.º 17
0
 public override bool AddChild(UINode node)
 {
     throw new NotSupportedException("this method has been overrided");
 }
Ejemplo n.º 18
0
        public UINode DrawLayer(Layer layer, UINode parent)
        {
            UINode node = PSDImportUtility.InstantiateItem(PSDImporterConst.PREFAB_PATH_SLIDER, layer.name, parent); //GameObject.Instantiate(temp) as UnityEngine.UI.Slider;

            UnityEngine.UI.Slider slider = node.GetComponent <UnityEngine.UI.Slider>();
            string type = layer.arguments[0].ToUpper();

            switch (type)
            {
            case "R":
                slider.direction = Slider.Direction.RightToLeft;
                break;

            case "L":
                slider.direction = Slider.Direction.LeftToRight;
                break;

            case "T":
                slider.direction = Slider.Direction.TopToBottom;
                break;

            case "B":
                slider.direction = Slider.Direction.BottomToTop;
                break;

            default:
                break;
            }
            bool haveHandle = false;

            for (int i = 0; i < layer.images.Length; i++)
            {
                Image  image               = layer.images[i];
                string lowerName           = image.name.ToLower();
                UnityEngine.UI.Image graph = null;

                if (lowerName.StartsWith("b_"))
                {
                    graph = slider.transform.Find("Background").GetComponent <UnityEngine.UI.Image>();
                    PSDImportUtility.SetRectTransform(image, slider.GetComponent <RectTransform>());
                    slider.name = layer.name;
                }
                else if (lowerName.StartsWith("f_"))
                {
                    graph = slider.fillRect.GetComponent <UnityEngine.UI.Image>();
                }
                else if (lowerName.StartsWith("h_"))
                {
                    graph = slider.handleRect.GetComponent <UnityEngine.UI.Image>();
                    RectTransform rect = graph.GetComponent <RectTransform>();
                    rect.name             = image.name;
                    rect.sizeDelta        = new Vector2(image.size.width, 0);
                    rect.anchoredPosition = Vector2.zero;
                    haveHandle            = true;
                }

                if (graph == null)
                {
                    continue;
                }

                PSDImportUtility.SetPictureOrLoadColor(image, graph);
            }

            if (!haveHandle)
            {
                UnityEngine.Object.DestroyImmediate(slider.handleRect.parent.gameObject);
            }
            return(node);
        }
Ejemplo n.º 19
0
    private UINode ParseUINode(IDictionary<string, object> dict)
    {
        if (dict == null)
        {
            Debug.LogError("UINode dict is null");
            return null;
        }

        UINode n = new UINode();
        n.ParentElementId = GetStringFromDict("ParentElementId", dict);
        n.Prefab = GetRealPrefabPath(GetStringFromDict("Prefab", dict));
        n.AllowMultiInstance = GetBoolFromDict("AllowMultiInstance", dict);

        if (dict.ContainsKey("Children"))
        {
            IList<UINode> nodes = ParseNodes(dict["Children"]);
            n.Children = nodes;
        }

        return n;
    }
Ejemplo n.º 20
0
        private void jump_to_option(UINode settingNode)
        {
            int option_index = SettingsGroups.FindIndex(x => x.Contains(settingNode));

            OptionsNodes.set_active_node(OptionsNodes[option_index]);
        }
Ejemplo n.º 21
0
 public UiEvents(int instanceId, UINode node)
 {
     MasterNodeID     = instanceId;
     ReturnMasterNode = node;
 }
Ejemplo n.º 22
0
 private void Awake()
 {
     allAttachedUINodes  = new List <UINode>();
     currentNodeSelected = defaultNode;
 }
Ejemplo n.º 23
0
	/// <summary>
	/// Convenience function that figures out the panel's correct change flag by searching the parents.
	/// </summary>

	int GetChangeFlag (UINode start)
	{
		int flag = start.changeFlag;

		if (flag == -1)
		{
			Transform trans = start.trans.parent;
			UINode sub;

			// Keep going until we find a set flag
			for (;;)
			{
				// Check the parent's flag
#if UNITY_FLASH
				if (mChildren.TryGetValue(trans, out sub))
				{
#else
				if (mChildren.Contains(trans))
				{
					sub = (UINode)mChildren[trans];
#endif
					flag = sub.changeFlag;
					trans = trans.parent;

					// If the flag hasn't been set either, add this child to the hierarchy
					if (flag == -1) mHierarchy.Add(sub);
					else break;
				}
				else
				{
					flag = 0;
					break;
				}
			}

			// Update the parent flags
			for (int i = 0, imax = mHierarchy.Count; i < imax; ++i)
			{
				UINode pc = mHierarchy[i];
				pc.changeFlag = flag;
			}
			mHierarchy.Clear();
		}
		return flag;
	}

	/// <summary>
	/// Update the world-to-local transform matrix as well as clipping bounds.
	/// </summary>

	void UpdateTransformMatrix ()
	{
		float time = Time.realtimeSinceStartup;

		if (time == 0f || mMatrixTime != time)
		{
			mMatrixTime = time;
			mWorldToLocal = cachedTransform.worldToLocalMatrix;

			if (mClipping != UIDrawCall.Clipping.None)
			{
				Vector2 size = new Vector2(mClipRange.z, mClipRange.w);

				if (size.x == 0f) size.x = (mCam == null) ? Screen.width  : mCam.pixelWidth;
				if (size.y == 0f) size.y = (mCam == null) ? Screen.height : mCam.pixelHeight;

				size *= 0.5f;

				mMin.x = mClipRange.x - size.x;
				mMin.y = mClipRange.y - size.y;
				mMax.x = mClipRange.x + size.x;
				mMax.y = mClipRange.y + size.y;
			}
		}
	}

	/// <summary>
	/// Run through all managed transforms and see if they've changed.
	/// </summary>

	void UpdateTransforms ()
	{
		bool transformsChanged = mCheckVisibility;

		// Check to see if something has changed
#if UNITY_FLASH
		foreach (KeyValuePair<Transform, UINode> child in mChildren)
		{
			UINode node = child.Value;
#else
		for (int i = 0, imax = mChildren.Count; i < imax; ++i)
		{
			UINode node = (UINode)mChildren[i];
#endif

			if (node.trans == null)
			{
				mRemoved.Add(node.trans);
				continue;
			}

			if (node.HasChanged())
			{
				node.changeFlag = 1;
				transformsChanged = true;
			}
			else node.changeFlag = -1;
		}

		// Clean up the deleted transforms
		for (int i = 0, imax = mRemoved.Count; i < imax; ++i) mChildren.Remove(mRemoved[i]);
		mRemoved.Clear();

		// If something has changed, propagate the changes *down* the tree hierarchy (to children).
		// An alternative (but slower) approach would be to do a pc.trans.GetComponentsInChildren<UIWidget>()
		// in the loop above, and mark each one as dirty.

		if (transformsChanged || mRebuildAll)
		{
#if UNITY_FLASH
			foreach (KeyValuePair<Transform, UINode> child in mChildren)
			{
				UINode pc = child.Value;
#else
			for (int i = 0, imax = mChildren.Count; i < imax; ++i)
			{
				UINode pc = (UINode)mChildren[i];
#endif

				if (pc.widget != null)
				{
					// If the change flag has not yet been determined...
					if (pc.changeFlag == -1) pc.changeFlag = GetChangeFlag(pc);

					// Is the widget visible?
					int visibleFlag = (mCheckVisibility || pc.changeFlag == 1) ? (IsVisible(pc.widget) ? 1 : 0) : pc.visibleFlag;

					// If visibility changed, mark the node as changed as well
					if (pc.visibleFlag != visibleFlag) pc.changeFlag = 1;

					// If the node has changed and the widget is visible (or was visible before)
					if (pc.changeFlag == 1 && (visibleFlag == 1 || pc.visibleFlag != 0))
					{
						// Update the visibility flag
						pc.visibleFlag = visibleFlag;
						Material mat = pc.widget.material;

						// Add this material to the list of changed materials
						if (!mChanged.Contains(mat)) mChanged.Add(mat);
					}
				}
			}
		}
		mCheckVisibility = false;
	}

	/// <summary>
	/// Update all widgets and rebuild their geometry if necessary.
	/// </summary>

	void UpdateWidgets ()
	{
#if UNITY_FLASH
		foreach (KeyValuePair<Transform, UINode> c in mChildren)
		{
			UINode pc = c.Value;
#else
		for (int i = 0, imax = mChildren.Count; i < imax; ++i)
		{
			UINode pc = (UINode)mChildren[i];
#endif
			UIWidget w = pc.widget;

			// If the widget is visible, update it
			if (pc.visibleFlag == 1 && w != null && w.UpdateGeometry(ref mWorldToLocal, (pc.changeFlag == 1), generateNormals))
			{
				// We will need to refill this buffer
				if (!mChanged.Contains(w.material))
				{
					mChanged.Add(w.material);
				}
			}
		}
	}

	/// <summary>
	/// Update the clipping rect in the shaders and draw calls' positions.
	/// </summary>

	public void UpdateDrawcalls ()
	{
		Vector4 range = Vector4.zero;

		if (mClipping != UIDrawCall.Clipping.None)
		{
			range = new Vector4(mClipRange.x, mClipRange.y, mClipRange.z * 0.5f, mClipRange.w * 0.5f);
		}

		if (range.z == 0f) range.z = Screen.width * 0.5f;
		if (range.w == 0f) range.w = Screen.height * 0.5f;

		RuntimePlatform platform = Application.platform;

		if (platform == RuntimePlatform.WindowsPlayer ||
			platform == RuntimePlatform.WindowsWebPlayer ||
			platform == RuntimePlatform.WindowsEditor)
		{
			range.x -= 0.5f;
			range.y += 0.5f;
		}

		Transform t = cachedTransform;

		for (int i = 0, imax = mDrawCalls.Count; i < imax; ++i)
		{
			UIDrawCall dc = mDrawCalls[i];
			dc.clipping = mClipping;
			dc.clipRange = range;
			dc.clipSoftness = mClipSoftness;
			dc.depthPass = depthPass;

			// Set the draw call's transform to match the panel's.
			// Note that parenting directly to the panel causes unity to crash as soon as you hit Play.
			Transform dt = dc.transform;
			dt.position = t.position;
			dt.rotation = t.rotation;
			dt.localScale = t.lossyScale;
		}
	}

	/// <summary>
	/// Set the draw call's geometry responsible for the specified material.
	/// </summary>

	void Fill (Material mat)
	{
		// Cleanup deleted widgets
		for (int i = mWidgets.Count; i > 0; ) if (mWidgets[--i] == null) mWidgets.RemoveAt(i);

		// Fill the buffers for the specified material
		for (int i = 0, imax = mWidgets.Count; i < imax; ++i)
		{
			UIWidget w = mWidgets[i];

			if (w.visibleFlag == 1 && w.material == mat)
			{
				UINode node = GetNode(w.cachedTransform);

				if (node != null)
				{
					if (generateNormals) w.WriteToBuffers(mVerts, mUvs, mCols, mNorms, mTans);
					else w.WriteToBuffers(mVerts, mUvs, mCols, null, null);
				}
				else
				{
					Debug.LogError("No transform found for " + NGUITools.GetHierarchy(w.gameObject), this);
				}
			}
		}

		if (mVerts.size > 0)
		{
			// Rebuild the draw call's mesh
			UIDrawCall dc = GetDrawCall(mat, true);
			dc.depthPass = depthPass;
			dc.Set(mVerts, generateNormals ? mNorms : null, generateNormals ? mTans : null, mUvs, mCols);
		}
		else
		{
			// There is nothing to draw for this material -- eliminate the draw call
			UIDrawCall dc = GetDrawCall(mat, false);

			if (dc != null)
			{
				mDrawCalls.Remove(dc);
				NGUITools.DestroyImmediate(dc.gameObject);
			}
		}

		// Cleanup
		mVerts.Clear();
		mNorms.Clear();
		mTans.Clear();
		mUvs.Clear();
		mCols.Clear();
	}

	/// <summary>
	/// Main update function
	/// </summary>

	void LateUpdate ()
	{
		UpdateTransformMatrix();
		UpdateTransforms();

		// Always move widgets to the panel's layer
		if (mLayer != gameObject.layer)
		{
			mLayer = gameObject.layer;
			UICamera uic = UICamera.FindCameraForLayer(mLayer);
			mCam = (uic != null) ? uic.cachedCamera : NGUITools.FindCameraForLayer(mLayer);
			SetChildLayer(cachedTransform, mLayer);
			for (int i = 0, imax = drawCalls.Count; i < imax; ++i) mDrawCalls[i].gameObject.layer = mLayer;
		}

		UpdateWidgets();

		// If the depth has changed, we need to re-sort the widgets
		if (mDepthChanged)
		{
			mDepthChanged = false;
			mWidgets.Sort(UIWidget.CompareFunc);
		}

		// Fill the draw calls for all of the changed materials
		for (int i = 0, imax = mChanged.Count; i < imax; ++i) Fill(mChanged[i]);

		// Update the clipping rects
		UpdateDrawcalls();
		mChanged.Clear();
		mRebuildAll = false;

#if UNITY_EDITOR
		mScreenSize = new Vector2(Screen.width, Screen.height);
#endif
	}

#if UNITY_EDITOR

	/// <summary>
	/// Draw a visible pink outline for the clipped area.
	/// </summary>

	void OnDrawGizmos ()
	{
		if (mDebugInfo == DebugInfo.Gizmos && mClipping != UIDrawCall.Clipping.None)
		{
			Vector2 size = new Vector2(mClipRange.z, mClipRange.w);

			if (size.x == 0f) size.x = mScreenSize.x;
			if (size.y == 0f) size.y = mScreenSize.y;

			Gizmos.matrix = transform.localToWorldMatrix;
			Gizmos.color = Color.magenta;
			Gizmos.DrawWireCube(new Vector2(mClipRange.x, mClipRange.y), size);
		}
	}
Ejemplo n.º 24
0
    private static string GetNodePath(string componentGuid, List <UINode> uiNodeList)
    {
        if (string.IsNullOrEmpty(componentGuid) || (null == uiNodeList || uiNodeList.Count <= 0))
        {
            return(null);
        }
        UINode selfNode = uiNodeList.Find(p =>
        {
            List <string> componentsGuid = p.ObjNode.ComponetsGuid;
            if (null != componentsGuid && componentsGuid.Count > 0)
            {
                string guid = componentsGuid.Find(pp => { return(pp.Equals(componentGuid)); });
                return(!string.IsNullOrEmpty(guid));
            }
            return(false);
        });

        if (null == selfNode)
        {
            selfNode = uiNodeList.Find(p =>
            {
                return(p.ObjNode.Guid.Equals(componentGuid));
            });
        }

        if (null == selfNode)
        {
            return(null);
        }
        Debug.Log("selfNode is " + selfNode.ObjNode.Name);

        //查找父节点
        UINode parentNode = selfNode.ParentNode;

        if (null == parentNode) //没有父节点,说明是根节点
        {
            return(selfNode.ObjNode.Name);
        }

        UINode searchNode = selfNode;
        var    sb         = new StringBuilder();

        while (true)
        {
            if (null == searchNode)
            {
                break;
            }

            UINode pNode = searchNode.ParentNode;
            if (null != pNode && null != pNode.ParentNode)  //过滤掉预制体节点
            {
                sb.Insert(0, string.Format("/{0}", pNode.ObjNode.Name));
            }
            searchNode = pNode;
        }

        sb.Append(string.Format("/{0}", selfNode.ObjNode.Name));
        sb.Remove(0, 1);
        return(sb.ToString());
    }
Ejemplo n.º 25
0
        /// <summary>
        /// Walks a generated AST (Abstract Syntax Tree) and creates the elements of this UIScreen.
        /// </summary>
        /// <param name="State">A ParserState instance.</param>
        /// <param name="node">The root node of the AST.</param>
        private void WalkTree(UIParser.ParserState State, AstNode node, ref ParseResult Result)
        {
            NodeType NType = (NodeType)Enum.Parse(typeof(NodeType), node.ToString(), true);

            switch (NType)
            {
            case NodeType.DefineImage:     //Defines an image and loads a texture for it.
                DefineImageNode ImgNode = (DefineImageNode)UINode.GetNode(node);
                UIImage         Img     = new UIImage(ImgNode, m_Screen);
                Result.Elements.Add(ImgNode.Name, Img);
                break;

            case NodeType.DefineString:     //Defines a string with a name.
                DefineStringNode StrNode = (DefineStringNode)UINode.GetNode(node);
                Result.Strings.Add(StrNode.Name, StringManager.StrTable(State.CurrentStringTable)[StrNode.StrIndex]);
                break;

            case NodeType.AddButton:     //Defines a button.
                AddButtonNode ButtonNode = (AddButtonNode)UINode.GetNode(node);
                UIButton      Btn        = new UIButton(ButtonNode, Result, m_Screen);
                Result.Elements.Add(ButtonNode.Name, Btn);

                break;

            case NodeType.AddText:
                AddTextNode TextNode = (AddTextNode)UINode.GetNode(node);
                UILabel     Lbl      = new UILabel(TextNode, Result, m_Screen);
                Result.Elements.Add(TextNode.Name, Lbl);
                break;

            case NodeType.AddTextEdit:
                AddTextEditNode TextEditNode = (AddTextEditNode)UINode.GetNode(node);
                UITextEdit      Txt          = new UITextEdit(TextEditNode, State, m_Screen);
                Result.Elements.Add(TextEditNode.Name, Txt);
                break;

            case NodeType.AddSlider:
                AddSliderNode SliderNode = (AddSliderNode)UINode.GetNode(node);
                UISlider      Slider     = new UISlider(SliderNode, State, m_Screen);
                Result.Elements.Add(SliderNode.Name, Slider);
                break;

            case NodeType.SetSharedProperties:     //Assigns a bunch of shared properties to declarations following the statement.
                State.InSharedPropertiesGroup = true;
                SetSharedPropsNode SharedPropsNode = (SetSharedPropsNode)UINode.GetNode(node);

                if (SharedPropsNode.StringTable != null)
                {
                    State.CurrentStringTable = (int)SharedPropsNode.StringTable;
                }

                if (SharedPropsNode.ControlPosition != null)
                {
                    State.Position[0] = SharedPropsNode.ControlPosition.Numbers[0];
                    State.Position[1] = SharedPropsNode.ControlPosition.Numbers[1];
                    break;
                }

                if (SharedPropsNode.Color != null)
                {
                    State.Color   = new Color();
                    State.Color.R = (byte)SharedPropsNode.Color.Numbers[0];
                    State.Color.G = (byte)SharedPropsNode.Color.Numbers[1];
                    State.Color.B = (byte)SharedPropsNode.Color.Numbers[2];
                }

                if (SharedPropsNode.TextColor != null)
                {
                    State.TextColor   = new Color();
                    State.TextColor.R = (byte)SharedPropsNode.TextColor.Numbers[0];
                    State.TextColor.G = (byte)SharedPropsNode.TextColor.Numbers[1];
                    State.TextColor.B = (byte)SharedPropsNode.TextColor.Numbers[2];
                }

                if (SharedPropsNode.TextColorSelected != null)
                {
                    State.TextColorSelected   = new Color();
                    State.TextColorSelected.R = (byte)SharedPropsNode.TextColorSelected.Numbers[0];
                    State.TextColorSelected.G = (byte)SharedPropsNode.TextColorSelected.Numbers[1];
                    State.TextColorSelected.B = (byte)SharedPropsNode.TextColorSelected.Numbers[2];
                }

                if (SharedPropsNode.TextColorHighlighted != null)
                {
                    State.TextColorHighlighted   = new Color();
                    State.TextColorHighlighted.R = (byte)SharedPropsNode.TextColorHighlighted.Numbers[0];
                    State.TextColorHighlighted.G = (byte)SharedPropsNode.TextColorHighlighted.Numbers[1];
                    State.TextColorHighlighted.B = (byte)SharedPropsNode.TextColorHighlighted.Numbers[2];
                }

                if (SharedPropsNode.TextColorDisabled != null)
                {
                    State.TextColorDisabled   = new Color();
                    State.TextColorDisabled.R = (byte)SharedPropsNode.TextColorDisabled.Numbers[0];
                    State.TextColorDisabled.G = (byte)SharedPropsNode.TextColorDisabled.Numbers[1];
                    State.TextColorDisabled.B = (byte)SharedPropsNode.TextColorDisabled.Numbers[2];
                }

                if (SharedPropsNode.BackColor != null)
                {
                    State.BackColor   = new Color();
                    State.BackColor.R = (byte)SharedPropsNode.BackColor.Numbers[0];
                    State.BackColor.G = (byte)SharedPropsNode.BackColor.Numbers[1];
                    State.BackColor.B = (byte)SharedPropsNode.BackColor.Numbers[2];
                }

                if (SharedPropsNode.CursorColor != null)
                {
                    State.CursorColor   = new Color();
                    State.CursorColor.R = (byte)SharedPropsNode.CursorColor.Numbers[0];
                    State.CursorColor.G = (byte)SharedPropsNode.CursorColor.Numbers[1];
                    State.CursorColor.B = (byte)SharedPropsNode.CursorColor.Numbers[2];
                }

                if (SharedPropsNode.TextButton)
                {
                    State.TextButton = true;
                }

                if (SharedPropsNode.Opaque != null)
                {
                    State.IsOpaque = (SharedPropsNode.Opaque == 1) ? true : false;
                }

                if (SharedPropsNode.Transparent != null)
                {
                    State.IsTransparent = (SharedPropsNode.Transparent == 1) ? true : false;
                }

                if (SharedPropsNode.Alignment != null)
                {
                    State.Alignment = (int)SharedPropsNode.Alignment;
                }

                if (SharedPropsNode.Image != "")
                {
                    State.Image = SharedPropsNode.Image;
                }

                if (SharedPropsNode.Tooltip != "")
                {
                    State.Tooltip = SharedPropsNode.Tooltip;
                }

                if (SharedPropsNode.Text != "")
                {
                    State.Caption = SharedPropsNode.Text;
                }

                if (SharedPropsNode.Size != null)
                {
                    State.Size = new Vector2(SharedPropsNode.Size.Numbers[0], SharedPropsNode.Size.Numbers[1]);
                }

                if (SharedPropsNode.Orientation != null)
                {
                    State.Orientation = (int)SharedPropsNode.Orientation;
                }

                if (SharedPropsNode.Font != null)
                {
                    State.Font = (int)SharedPropsNode.Font;
                }

                if (SharedPropsNode.Opaque != null)
                {
                    State.Opaque = (int)SharedPropsNode.Opaque;
                }

                break;

            case NodeType.SetControlProperties:     //Sets a bunch of properties to a specified control.
                SetControlPropsNode ControlPropsNode = (SetControlPropsNode)UINode.GetNode(node);

                UIControl Ctrl = new UIControl(ControlPropsNode, m_Screen, State);
                Result.Controls.Add(ControlPropsNode.Control, Ctrl);

                if (State.InSharedPropertiesGroup)
                {
                    UIElement Test = new UIElement(m_Screen, null);
                    //Script implicitly created an object... :\
                    if (!Result.Elements.TryGetValue(ControlPropsNode.Control, out Test))
                    {
                        Result.Elements.Add(ControlPropsNode.Control, new UIElement(m_Screen, null));

                        if (Ctrl.Image != null)
                        {
                            Result.Elements[ControlPropsNode.Control].Image = new UIImage(Ctrl.Image);
                        }

                        Result.Elements[ControlPropsNode.Control].Position = Ctrl.Position;
                    }
                }

                break;

            case NodeType.End:
                State.InSharedPropertiesGroup = false;
                State.Image      = "";    //Reset
                State.TextButton = false; //Reset
                State.Color      = new Color();
                State.Caption    = "";
                State.Size       = new Vector2(0, 0);
                State.Alignment  = 0;
                State.Font       = 0;
                //TODO: Reset more?
                break;
            }

            foreach (AstNode child in node.ChildNodes)
            {
                WalkTree(State, child, ref Result);
            }
        }
Ejemplo n.º 26
0
    /// <summary>
    /// Add the specified widget to the managed list.
    /// </summary>

    public void AddWidget(UIWidget w)
    {
        if (w != null)
        {
#if UNITY_EDITOR
            if (w.cachedTransform.parent != null)
            {
                UIWidget parentWidget = NGUITools.FindInParents <UIWidget>(w.cachedTransform.parent.gameObject);

                if (parentWidget != null)
                {
                    w.cachedTransform.parent = parentWidget.cachedTransform.parent;
                    Debug.LogError("You should never nest widgets! Parent them to a common game object instead. Forcefully changing the parent.", w);

                    // If the error above gets triggered, it means that you parented one widget to another.
                    // If left unchecked, this may lead to odd behavior in the UI. Consider restructuring your UI.
                    // For example, if you were trying to do this:

                    // Widget #1
                    //  |
                    //  +- Widget #2

                    // You can do this instead, fixing the problem:

                    // GameObject (scale 1, 1, 1)
                    //  |
                    //  +- Widget #1
                    //  |
                    //  +- Widget #2
                }
            }
#endif
#if OLD_UNITY
            UINode node = AddTransform(w.cachedTransform);

            if (node != null)
            {
                node.widget   = w;
                w.visibleFlag = 1;

                if (!mWidgets.Contains(w))
                {
                    mWidgets.Add(w);

                    if (!mChanged.Contains(w.material))
                    {
                        mChanged.Add(w.material);
                    }

                    mDepthChanged = true;
                    mWidgetsAdded = true;
                }
            }
            else
            {
                Debug.LogError("Unable to find an appropriate root for " + NGUITools.GetHierarchy(w.cachedGameObject) +
                               "\nPlease make sure that there is at least one game object above this widget!", w.cachedGameObject);
            }
#else
            if (!mWidgets.Contains(w))
            {
                mWidgets.Add(w);

                if (!mChanged.Contains(w.material))
                {
                    mChanged.Add(w.material);
                }

                mDepthChanged = true;
            }
#endif
        }
    }
Ejemplo n.º 27
0
    private void ToScreen()
    {
        float overallScale = 1f;

        //change node scale case the grid is too big.
        if (Size > 65)
        {
            overallScale = (Size - 1) / 64f;
        }

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

            //spawn the node
            GameObject nodeGO = (GameObject)Instantiate(nodePrefab, node.pos, Quaternion.identity, transform);

            //Change Scale
            nodeGO.transform.localScale = new Vector3(overallScale, overallScale, 1f);

            nodeGO.name = "node " + node.ID;
            UINode uiNode = nodeGO.GetComponent <UINode> ();
            if (uiNode != null)
            {
                uiNode.node = node;
            }

            Nodes[i].GO = nodeGO;

            //spawn links
            for (int j = 0; j < node.links.Count; j++)
            {
                Node link = node.links[j];

                bool contains = false;
                for (int k = 0; k < AllLinks.Count; k++)
                {
                    if (AllLinks[k].HasNodes(node, link))
                    {
                        contains = true;
                        break;
                    }
                }

                if (!contains)
                {
                    //prep the link
                    //angulo
                    double angle = Mathf.Atan2(link.pos.y - node.pos.y, link.pos.x - node.pos.x) * Mathf.Rad2Deg + 90;
                    //posição
                    Vector2 pos = (link.pos + node.pos) / 2;
                    //scale
                    float linkLengthScale = Vector2.Distance(node.pos, link.pos);

                    GameObject linkGO = Instantiate(linkPrefab, pos, Quaternion.identity, transform);
                    linkGO.transform.localScale  = new Vector3(overallScale, linkLengthScale * 4, 1f);
                    linkGO.transform.eulerAngles = new Vector3(0f, 0f, (float)angle);

                    AllLinks.Add(new Link(node, link, linkGO));
                }
            }
        }

        SetCamera();
    }
Ejemplo n.º 28
0
    /// <summary>
    /// Add the specified transform to the managed list.
    /// </summary>
    UINode AddTransform(Transform t)
    {
        UINode node = null;
        UINode retVal = null;

        // Add transforms all the way up to the panel
        while (t != null && t != cachedTransform)
        {
            // If the node is already managed, we're done
            if (mChildren.TryGetValue(t, out node))
            {
                if (retVal == null) retVal = node;
                break;
            }
            else
            {
                // The node is not yet managed -- add it to the list
                node = new UINode(t);
                if (retVal == null) retVal = node;
                mChildren.Add(t, node);
                t = t.parent;
            }
        }
        return retVal;
    }
Ejemplo n.º 29
0
 private UINode GetNodeHelper(UINode nodeToCheck)
 {
     return(null);
 }
Ejemplo n.º 30
0
 public ChildIsRootException(string message, UINode sender, UINode child)
 {
     Child   = child;
     Sender  = sender;
     Message = message;
 }
Ejemplo n.º 31
0
        public UINode DrawLayer(Layer layer, UINode parent)
        {
            UINode node = PSDImportUtility.InstantiateItem(PSDImporterConst.PREFAB_PATH_SCROLLVIEW, layer.name, parent);

            UnityEngine.UI.ScrollRect scrollRect = node.GetComponent <UnityEngine.UI.ScrollRect>();

            UINode childNode = PSDImportUtility.InstantiateItem(PSDImporterConst.PREFAB_PATH_IMAGE, "Viewport", node);

            scrollRect.viewport = childNode.GetComponent <RectTransform>();
            childNode.AddComponent <Mask>();
            childNode.anchoType = UINode.AnchoType.XStretch | UINode.AnchoType.YStretch;

            UnityEngine.UI.Image graph = scrollRect.GetComponent <UnityEngine.UI.Image>();
            bool havebg = false;

            for (int i = 0; i < layer.images.Length; i++)
            {
                Image image = layer.images[i];

                if (image.name.ToLower().StartsWith("b_"))
                {
                    havebg = true;

                    PSDImportUtility.SetPictureOrLoadColor(image, graph);

                    PSDImportUtility.SetRectTransform(image, graph.GetComponent <RectTransform>());
                }
                else
                {
                    ctrl.DrawImage(image, node);
                }
            }

            if (!havebg)
            {
                UnityEngine.Object.DestroyImmediate(graph);
                PSDImportUtility.SetRectTransform(layer, scrollRect.GetComponent <RectTransform>(), parent.GetComponent <RectTransform>());
            }

            PSDImportUtility.SetRectTransform(layer, childNode.GetComponent <RectTransform>(), scrollRect.GetComponent <RectTransform>());

            if (layer.arguments != null)
            {
                string type = layer.arguments[0].ToUpper();
                switch (type)
                {
                case "V":
                    scrollRect.vertical   = true;
                    scrollRect.horizontal = false;
                    break;

                case "H":
                    scrollRect.vertical   = false;
                    scrollRect.horizontal = true;
                    break;

                case "VH":
                case "HV":
                    scrollRect.vertical   = true;
                    scrollRect.horizontal = true;
                    break;

                default:
                    break;
                }
            }

            if (layer.layers != null)
            {
                for (int i = 0; i < layer.layers.Length; i++)
                {
                    Layer  child          = layer.layers[i];
                    string childLowerName = child.name;
                    UINode c_Node         = ctrl.DrawLayer(child, childNode);

                    if (childLowerName.StartsWith("c_"))
                    {
                        scrollRect.content = c_Node.GetComponent <RectTransform>();
                    }
                    else if (childLowerName.StartsWith("vb_"))
                    {
                        scrollRect.verticalScrollbar           = c_Node.GetComponent <Scrollbar>();
                        scrollRect.verticalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHide;
                    }
                    else if (childLowerName.StartsWith("hb_"))
                    {
                        scrollRect.horizontalScrollbar           = c_Node.GetComponent <Scrollbar>();
                        scrollRect.horizontalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHide;
                    }
                }
            }
            return(node);
        }