public void Setup(Matrix m, Rect imageRect, RectF cropRect, bool circle, bool maintainAspectRatio)
        {
            if (circle)
            {
                maintainAspectRatio = true;
            }

            this.Matrix = new Matrix(m);

            this.MCropRect           = cropRect;
            this.MImageRect          = new RectF(imageRect);
            this.MaintainAspectRatio = maintainAspectRatio;
            this.Circling            = circle;

            this.InitialAspectRatio = this.MCropRect.Width() / this.MCropRect.Height();
            this.MDrawRect          = ComputeLayout();

            this.FocusPaint.SetARGB(125, 50, 50, 50);
            this.NoFocusPaint.SetARGB(125, 50, 50, 50);
            this.OutlinePaint.StrokeWidth = 3f;
            this.OutlinePaint.SetStyle(Paint.Style.Stroke);
            this.OutlinePaint.AntiAlias = true;

            this.MMode = ModifyMode.None;
            Init();
        }
示例#2
0
        internal virtual void SetValue(ModifyMode mode, float value)
        {
            var oldVal = m_Value;

            switch (mode)
            {
            case ModifyMode.Addition:
                m_Value += value;
                break;

            case ModifyMode.Multiplication:
                m_Value *= value;
                break;

            case ModifyMode.Divide:
                m_Value /= value;
                break;
            }

            log.DebugFormat("{0}'s {1} changed from {2} to {3}.", m_Entity.Name, AttributeCode, oldVal, m_Value);

            var ev = new FloatAttributeChangedEvent()
            {
                AttributeCode = (int)AttributeCode,
                Entity        = m_Entity.Name,
                FloatValue    = m_Value
            };
            IEventData evData = new EventData((byte)EventCode.AttributeChangedEvent, ev);

            PublishChange(evData, BroadcastOptions.All);
        }
示例#3
0
        public SPCModelSavePopup(ModifyMode configMode, string strMessage)
        {
            InitializeComponent();

            this._configMode = configMode;
            this._messge     = strMessage;
        }
示例#4
0
        // Done editing
        protected override void OnEditEnd()
        {
            base.OnEditEnd();

            // Stop editing
            mode             = ModifyMode.None;
            sectorbrightness = null;

            // Nothing changed? Then withdraw the undo
            if (editstartpos.Y == Cursor.Position.Y)
            {
                if ((General.Map.UndoRedo.NextUndo != null) &&
                    (General.Map.UndoRedo.NextUndo.TicketID == undoticket))
                {
                    General.Map.UndoRedo.WithdrawUndo();
                }
            }

            // Update
            General.Map.Map.Update();
            UpdateSelectedLabels();
            General.Interface.RefreshInfo();
            General.Interface.RedrawDisplay();
            renderer.Present();

            // If only one sector was selected, deselect it
            ICollection <Sector> orderedselection = General.Map.Map.GetSelectedSectors(true);

            if (orderedselection.Count == 1)
            {
                SelectSector(General.GetByIndex(orderedselection, 0), false, true);
            }
        }
 public void SetMode(ModifyMode mode)
 {
     if (mode != this.MMode)
     {
         this.MMode = mode;
         this.mContext.Invalidate();
     }
 }
示例#6
0
 public WI_Modify(VariableRef variable, Variable varDesc, VTQ[] data, ModifyMode mode, TaskCompletionSource <bool> promise)
 {
     Variable = variable;
     VarDesc  = varDesc;
     Data     = data;
     Mode     = mode;
     Promise  = promise;
 }
示例#7
0
        public override async Task HistorianModify(VariableRef variable, ModifyMode mode, params VTQ[] data)
        {
            JObject request = MakeSessionRequest();

            request["variable"] = new JRaw(StdJson.ObjectToString(variable));
            request["data"]     = new JRaw(StdJson.ObjectToString(data));
            request["mode"]     = new JRaw(StdJson.ValueToString(mode));
            await PostJObject("HistorianModify", request);
        }
示例#8
0
        public Task Modify(VariableRef variable, Variable varDesc, VTQ[] data, ModifyMode mode)
        {
            var promise = new TaskCompletionSource <bool>();

            if (CheckPrecondition(promise))
            {
                queue.Post(new WI_Modify(variable, varDesc, data, mode, promise));
            }
            return(promise.Task);
        }
示例#9
0
        /**
         *      node window initializer.
         *      setup nodes, points and connections from saved data.
         */
        public void InitializeNodeWindow()
        {
            minSize = new Vector2(600f, 300f);

            wantsMouseMove = true;
            modifyMode     = ModifyMode.CONNECT_ENDED;

            nodes.Add(new Node(EmitEvent, nodes.Count, "node:" + nodes.Count, new Rect(10, 10, 200, 60)));
            nodes.Add(new Node(EmitEvent, nodes.Count, "node:" + nodes.Count, new Rect(310, 110, 210, 60)));
            nodes.Add(new Node(EmitEvent, nodes.Count, "node:" + nodes.Count, new Rect(310, 210, 210, 60)));
        }
示例#10
0
        internal override void SetValue(ModifyMode mode, int value)
        {
            var maxHealthAttribute = m_Entity.GetAttribute(AttributeCode.MaxHealth) as IntAttribute;
            var maxHealth          = maxHealthAttribute.GetValue();
            var beforeHealth       = m_Value;

            switch (mode)
            {
            case ModifyMode.Addition:
                if (m_Value + value > maxHealth)
                {
                    m_Value = maxHealth;
                }
                else
                {
                    m_Value += value;
                }
                break;

            case ModifyMode.Multiplication:
                if (m_Value * value > maxHealth)
                {
                    m_Value = maxHealth;
                }
                else
                {
                    m_Value *= value;
                }
                break;
            }

            var amtChanged = m_Value - beforeHealth;

            log.InfoFormat("{0} took {1} damage. Health left: {2}", m_Entity.Name, amtChanged.ToString(), m_Value);



            var ev = new HealthChangedEvent()
            {
                Username     = m_Entity.Name,
                Damage       = amtChanged,
                CurrenHealth = m_Value
            };
            IEventData evData = new EventData((byte)EventCode.HealthUpdate, ev);

            PublishChange(evData, BroadcastOptions.All);

            if (m_Value <= 0)
            {
                m_Value = 0;
                m_Entity.Die();
                return;
            }
        }
示例#11
0
        public override async Task HistorianModify(VariableRef variable, ModifyMode mode, params VTQ[] data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }
            var request = MakeSessionRequest <HistorianModifyReq>();

            request.Variable = variable;
            request.Data     = data;
            request.Mode     = mode;
            await PostVoid(request);
        }
示例#12
0
        /// <summary>
        /// Chane in XML file and DNS list (Add or Edit a DNS)
        /// </summary>
        /// <param name="modifyMode"></param>
        /// <returns></returns>
        private bool ChangeXML(ModifyMode modifyMode)
        {
            switch (modifyMode)
            {
            case ModifyMode.Add:
                return(AddXML());

            case ModifyMode.Edit:
                return(EditXML());

            default:
                return(false);
            }
        }
示例#13
0
        // Editing
        protected override void OnEditBegin()
        {
            base.OnEditBegin();

            // No selection?
            ICollection <Sector> orderedselection = General.Map.Map.GetSelectedSectors(true);

            if (orderedselection.Count == 0)
            {
                // Make the highlight a selection if we have a highlight
                if ((highlighted != null) && !highlighted.IsDisposed)
                {
                    SelectSector(highlighted, true, false);
                    orderedselection.Add(highlighted);
                }
            }

            // Anything selected?
            if (orderedselection.Count > 0)
            {
                // Create undo
                undoticket = General.Map.UndoRedo.CreateUndo("Adjust brightness");

                // Start editing
                mode         = ModifyMode.Adjusting;
                editstartpos = Cursor.Position;

                // Keep sector brightness offsets and make the sector full brightness so we can use
                // the overlay to adjust the brightness. The surface is only updated here and again
                // with correct brightness when editing is done.
                sectorbrightness = new List <int>(orderedselection.Count);
                foreach (Sector s in orderedselection)
                {
                    int realbrightness = s.Brightness;
                    sectorbrightness.Add(realbrightness);
                    s.Brightness = 255;
                    s.UpdateCache();
                    s.Brightness = realbrightness;
                }

                // Update surface to render full bright sectors
                renderer.RedrawSurface();

                // Update
                UpdateSelectedLabels();
                UpdateOverlay();
                renderer.Present();
            }
        }
示例#14
0
        private static HistoryChangeType MapMode(ModifyMode mode)
        {
            switch (mode)
            {
            case ModifyMode.Delete: return(HistoryChangeType.Delete);

            case ModifyMode.Insert: return(HistoryChangeType.Insert);

            case ModifyMode.Update: return(HistoryChangeType.Update);

            case ModifyMode.Upsert: return(HistoryChangeType.Upsert);

            default: throw new Exception("Unknown modify mode: " + mode);
            }
        }
示例#15
0
        public SPCModelSavePopup(ModifyMode configMode, string strMessage, bool isShowNoBtn, bool hasSubconfig)
        {
            InitializeComponent();

            this._configMode = configMode;

            if (strMessage.Contains("@@n"))
            {
                strMessage = strMessage.Replace("@@n", "\n");
            }

            this._messge         = strMessage;
            this._isShowNoButton = isShowNoBtn;
            this._hasSubconfig   = hasSubconfig;
        }
示例#16
0
        private void ModifyMode_Changed(ModifyMode value)
        {
            switch (value)
            {
            case ModifyMode.Null:
                ClearBinding();
                AddDataBinding();
                if (position != -1)
                {
                    dnsBindingSource.Position = position;
                }
                cmbDNS.Visible       = true;
                txtDNS.Visible       = false;
                txtPreferred.Enabled = false;
                txtAlternate.Enabled = false;
                btnChange.Visible    = true;
                btnReset.Visible     = true;
                btnAdd.Visible       = true;
                btnEdit.Visible      = true;
                btnDelete.Visible    = true;
                btnAccept.Visible    = false;
                btnCancel.Visible    = false;
                break;

            case ModifyMode.Add:
            case ModifyMode.Edit:
                if (value == ModifyMode.Add)
                {
                    ClearBindingForInsert();
                }
                cmbDNS.Visible       = false;
                txtDNS.Visible       = true;
                txtPreferred.Enabled = true;
                txtAlternate.Enabled = true;
                btnChange.Visible    = false;
                btnReset.Visible     = false;
                btnAdd.Visible       = false;
                btnEdit.Visible      = false;
                btnDelete.Visible    = false;
                btnAccept.Visible    = true;
                btnCancel.Visible    = true;
                break;
            }
            modifyMode = value;
        }
示例#17
0
        public async Task HistorianModify(VariableRef variable, VTQ[] data, ModifyMode mode)
        {
            HistoryDBWorker?worker = WorkerByVarRef(variable);

            if (worker == null)
            {
                throw new Exception("Failed to find DB worker for variable " + variable);
            }

            Variable varDesc = CheckExistingVariable(variable);
            await worker.Modify(variable, varDesc, data, mode);

            if (data.Length > 0)
            {
                Timestamp start = data.Min(x => x.T);
                Timestamp end   = data.Max(x => x.T);
                NotifyChange(variable, start, end, MapMode(mode));
            }
        }
示例#18
0
        internal virtual void SetValue(ModifyMode mode, int value)
        {
            var oldVal = m_Value;

            switch (mode)
            {
            case ModifyMode.Addition:
                m_Value += value;
                break;

            case ModifyMode.Multiplication:
                m_Value *= value;
                break;
            }

            log.DebugFormat("{0}'s {1} changed from {2} to {3}.", m_Entity.Name, AttributeCode, oldVal, m_Value);

            // TODO: Replicate change.
        }
示例#19
0
        // When selected button is released
        protected override void OnSelectEnd()
        {
            base.OnSelectEnd();

            // Remove extension line
            extensionline = new Line2D();

            if (autopanning)
            {
                DisableAutoPanning();
                autopanning = false;
            }

            // No modifying mode
            mode = ModifyMode.None;

            // Redraw
            General.Map.Map.Update();
            General.Interface.RedrawDisplay();
        }
        public void Setup(Matrix m, Rect imageRect, RectF cropRect, bool maintainAspectRatio)
        {
            matrix = new Matrix(m);

            this.cropRect            = cropRect;
            this.imageRect           = new RectF(imageRect);
            this.maintainAspectRatio = maintainAspectRatio;

            initialAspectRatio = cropRect.Width() / cropRect.Height();
            DrawRect           = computeLayout();

            focusPaint.SetARGB(125, 50, 50, 50);
            noFocusPaint.SetARGB(125, 50, 50, 50);
            outlinePaint.StrokeWidth = 3;
            outlinePaint.SetStyle(Paint.Style.Stroke);
            outlinePaint.AntiAlias = true;

            mode = ModifyMode.None;
            init();
        }
示例#21
0
        public void Setup(Matrix m, Rect imageRect, RectF cropRect, bool maintainAspectRatio)
        {
            MatrixImage = new Matrix(m);

            _cropRect            = cropRect;
            _imageRect           = new RectF(imageRect);
            _maintainAspectRatio = maintainAspectRatio;

            _initialAspectRatio = cropRect.Width() / cropRect.Height();
            DrawRect            = ComputeLayout();

            _focusPaint.SetARGB(125, 50, 50, 50);
            _noFocusPaint.SetARGB(125, 50, 50, 50);
            _outlinePaint.StrokeWidth = 3;
            _outlinePaint.SetStyle(Paint.Style.Stroke);
            _outlinePaint.AntiAlias = true;

            _mode = ModifyMode.None;
            Init();
        }
示例#22
0
 public FloatModifier(ModifyMode mode, AttributeCode attribute, float value)
 {
     m_Attribute = attribute;
     m_Mode      = mode;
     m_Value     = value;
 }
示例#23
0
        /**
            emit event from node-GUI.
        */
        private void EmitNodeEvent(OnNodeEvent e)
        {
            switch (modifyMode) {
                case ModifyMode.CONNECT_STARTED: {
                    switch (e.eventType) {
                        /*
                            handling
                        */
                        case OnNodeEvent.EventType.EVENT_NODE_HANDLING: {

                            /*
                                animate connectionPoint under mouse if this connectionPoint is able to accept this kind of connection.
                            */
                            if (false) {
                                var candidateNodes = NodesUnderPosition(e.globalMousePosition);

                                if (!candidateNodes.Any()) break;
                                var nodeUnderMouse = candidateNodes.Last();

                                // ignore if target node is source itself.
                                if (nodeUnderMouse == e.eventSourceNode) break;

                                var candidatePoints = nodeUnderMouse.ConnectionPointUnderGlobalPos(e.globalMousePosition);

                                var sourcePoint = currentEventSource.eventSourceConnectionPoint;

                                // limit by connectable or not.
                                var connectableCandidates = candidatePoints.Where(point => IsConnectablePointFromTo(sourcePoint, point)).ToList();
                                if (!connectableCandidates.Any()) break;

                                // connectable point is exist. change line color.

                                // or, do something..
                                Debug.Log("connectable!");
                            }
                            break;
                        }

                        /*
                            drop detected.
                        */
                        case OnNodeEvent.EventType.EVENT_NODE_DROPPED: {
                            // finish connecting mode.
                            modifyMode = ModifyMode.CONNECT_ENDED;

                            /*
                                connect when dropped target is connectable from start connectionPoint.
                            */
                            {
                                var candidateNodes = NodesUnderPosition(e.globalMousePosition);

                                if (!candidateNodes.Any()) break;
                                var nodeUnderMouse = candidateNodes.Last();

                                // ignore if target node is source itself.
                                if (nodeUnderMouse == e.eventSourceNode) break;

                                var candidatePoints = nodeUnderMouse.ConnectionPointUnderGlobalPos(e.globalMousePosition);

                                var sourcePoint = currentEventSource.eventSourceConnectionPoint;

                                // limit by connectable or not.
                                var connectableCandidates = candidatePoints.Where(point => IsConnectablePointFromTo(sourcePoint, point)).ToList();
                                if (!connectableCandidates.Any()) break;

                                // target point is determined.
                                var connectablePoint = connectableCandidates.First();

                                var startNode = e.eventSourceNode;
                                var startConnectionPoint = currentEventSource.eventSourceConnectionPoint;
                                var endNode = nodeUnderMouse;
                                var endConnectionPoint = connectablePoint;

                                // reverse if connected from input to output.
                                if (startConnectionPoint.isInput) {
                                    startNode = nodeUnderMouse;
                                    startConnectionPoint = connectablePoint;
                                    endNode = e.eventSourceNode;
                                    endConnectionPoint = currentEventSource.eventSourceConnectionPoint;
                                }

                                var label = startConnectionPoint.label;
                                AddConnection(label, startNode, startConnectionPoint, endNode, endConnectionPoint);
                                SaveGraphWithReload();
                            }
                            break;
                        }

                        default: {
                            // Debug.Log("unconsumed or ignored event:" + e.eventType);
                            modifyMode = ModifyMode.CONNECT_ENDED;
                            break;
                        }
                    }
                    break;
                }
                case ModifyMode.CONNECT_ENDED: {
                    switch (e.eventType) {
                        case OnNodeEvent.EventType.EVENT_NODE_TAPPED: {

                            Undo.RecordObject(this, "Select Node");

                            var tappedNodeId = e.eventSourceNode.nodeId;
                            foreach (var node in nodes) {
                                if (node.nodeId == tappedNodeId) {
                                    node.SetActive();
                                    activeObject = new ActiveObject(AssetGraphSettings.ObjectKind.NODE, node.nodeId, node.GetPos());
                                }
                                else node.SetInactive();
                            }

                            foreach (var con in connections) {
                                con.SetInactive();
                            }
                            break;
                        }

                        /*
                            start connection handling.
                        */
                        case OnNodeEvent.EventType.EVENT_NODE_HANDLE_STARTED: {
                            modifyMode = ModifyMode.CONNECT_STARTED;
                            currentEventSource = e;
                            break;
                        }

                        /*
                            connectionPoint tapped.
                        */
                        case OnNodeEvent.EventType.EVENT_CONNECTIONPOINT_RECEIVE_TAPPED: {
                            var sourcePoint = e.eventSourceConnectionPoint;

                            var relatedConnections = connections
                                .Where(
                                    con => con.IsStartAtConnectionPoint(sourcePoint) ||
                                    con.IsEndAtConnectionPoint(sourcePoint)
                                )
                                .ToList();

                            /*
                                show menuContext for control these connections.
                            */
                            var menu = new GenericMenu();
                            menu.AddItem(
                                new GUIContent("delete all connections"),
                                false,
                                () => {
                                    Undo.RecordObject(this, "Delete All Connections");

                                    foreach (var con in relatedConnections) {
                                        var conId = con.connectionId;
                                        DeleteConnectionById(conId);
                                    }

                                    SaveGraphWithReload();
                                }
                            );
                            menu.ShowAsContext();
                            break;
                        }

                        case OnNodeEvent.EventType.EVENT_CLOSE_TAPPED: {

                            var deletingNodeId = e.eventSourceNode.nodeId;
                            DeleteNode(deletingNodeId);

                            SaveGraphWithReload();
                            InitializeGraph();
                            break;
                        }

                        case OnNodeEvent.EventType.EVENT_DUPLICATE_TAPPED: {
                            var duplicateNodeId = e.eventSourceNode.nodeId;
                            var duplicatePoint = e.globalMousePosition;
                            DuplicateNode(duplicateNodeId, duplicatePoint.x, duplicatePoint.y);
                            break;
                        }

                        /*
                            releasse detected.
                                node moved.
                                node tapped.
                        */
                        case OnNodeEvent.EventType.EVENT_NODE_RELEASED: {
                            var movedNode = e.eventSourceNode;

                            var beforePosition = activeObject.pos;
                            var afterPosition = movedNode.GetPos();

                            movedNode.SetPos(beforePosition);

                            Undo.RecordObject(this, "Move Node");

                            movedNode.SetPos(afterPosition);

                            UpdateSpacerRect();
                            SaveGraph();
                            break;
                        }

                        default: {
                            // Debug.Log("unconsumed or ignored event:" + e.eventType);
                            break;
                        }
                    }
                    break;
                }
            }

            switch (e.eventType) {
                case OnNodeEvent.EventType.EVENT_CONNECTIONPOINT_UPDATED: {
                    Debug.LogError("あーポイント追加時に線が消えちゃうのが困るよな");
                    var targetNode = e.eventSourceNode;

                    var connectionsFromThisNode = connections.Where(con => con.startNodeId == targetNode.nodeId).ToList();
                    var connectionsToThisNode = connections.Where(con => con.endNodeId == targetNode.nodeId).ToList();

                    // remove connections from this node.
                    foreach (var con in connectionsFromThisNode) {
                        connections.Remove(con);
                    }

                    // remove connections to this node.
                    foreach (var con in connectionsToThisNode) {
                        connections.Remove(con);
                    }
                    break;
                }
                case OnNodeEvent.EventType.EVENT_SAVE: {
                    SaveGraphWithReload();
                    Repaint();
                    break;
                }
            }
        }
示例#24
0
        /**
            node graph initializer.
            setup nodes, points and connections from saved data.
        */
        public void InitializeGraph()
        {
            var basePath = FileController.PathCombine(Application.dataPath, AssetBundleGraphSettings.ASSETNBUNDLEGRAPH_DATA_PATH);

            // create Temp folder under Assets/AssetBundleGraph
            if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath);

            var graphDataPath = FileController.PathCombine(basePath, AssetBundleGraphSettings.ASSETBUNDLEGRAPH_DATA_NAME);

            var deserialized = new Dictionary<string, object>();
            var lastModified = DateTime.Now;

            if (File.Exists(graphDataPath)) {

                // load
                var dataStr = string.Empty;

                using (var sr = new StreamReader(graphDataPath)) {
                    dataStr = sr.ReadToEnd();
                }

                try {
                    deserialized = Json.Deserialize(dataStr) as Dictionary<string, object>;
                } catch (Exception e) {
                    Debug.LogError("data load error:" + e + " at path:" + graphDataPath);
                    return;
                }

                var lastModifiedStr = deserialized[AssetBundleGraphSettings.ASSETBUNDLEGRAPH_DATA_LASTMODIFIED] as string;
                lastModified = Convert.ToDateTime(lastModifiedStr);

                var validatedDataDict = GraphStackController.ValidateStackedGraph(deserialized);

                var validatedDate = validatedDataDict[AssetBundleGraphSettings.ASSETBUNDLEGRAPH_DATA_LASTMODIFIED] as string;
                if (lastModifiedStr != validatedDate) {
                    // save validated graph data.
                    UpdateGraphData(validatedDataDict);

                    // reload
                    var dataStr2 = string.Empty;
                    using (var sr = new StreamReader(graphDataPath)) {
                        dataStr2 = sr.ReadToEnd();
                    }

                    deserialized = Json.Deserialize(dataStr2) as Dictionary<string, object>;

                    var lastModifiedStr2 = deserialized[AssetBundleGraphSettings.ASSETBUNDLEGRAPH_DATA_LASTMODIFIED] as string;
                    lastModified = Convert.ToDateTime(lastModifiedStr2);
                }

            } else {
                var graphData = RenewData();

                // set new empty graph data.
                deserialized = graphData;
            }

            /*
                do nothing if json does not modified after first load.
            */
            if (lastModified == lastLoaded) return;

            lastLoaded = lastModified;

            minSize = new Vector2(600f, 300f);

            wantsMouseMove = true;
            modifyMode = ModifyMode.CONNECT_ENDED;

            /*
                load graph data from deserialized data.
            */
            var nodesAndConnections = ConstructGraphFromDeserializedData(deserialized);
            nodes = nodesAndConnections.currentNodes;
            connections = nodesAndConnections.currentConnections;
        }
示例#25
0
        // When select button is pressed
        protected override void OnSelectBegin()
        {
            base.OnSelectBegin();

            if (mode != ModifyMode.None)
            {
                return;
            }

            // Used in many cases
            Vector2D delta;

            // Check what grip the mouse is over
            switch (CheckMouseGrip())
            {
            // Drag main rectangle
            case Grip.Main:
                dragoffset = -mousemappos - offset;
                mode       = ModifyMode.Dragging;
                EnableAutoPanning();
                autopanning = true;
                break;

            // Scale
            case Grip.SizeH:

                // The resize vector is a unit vector in the direction of the resize.
                // We multiply this with the sign of the current size, because the
                // corners may be reversed when the selection is flipped.
                resizevector = corners[1] - corners[0];
                resizevector = resizevector.GetNormal() * Math.Sign(scale.x);

                // Make the resize axis. This is a line with the length and direction
                // of basesize used to calculate the resize percentage.
                resizeaxis = new Line2D(corners[0], corners[0] + resizevector * texture.ScaledWidth / Math.Abs(sectorinfo[0].scale.x));

                // Original axis filter
                resizefilter = new Vector2D(1.0f, 0.0f);

                mode = ModifyMode.Resizing;
                break;

            // Scale
            case Grip.SizeV:
                // See description above
                resizevector = corners[2] - corners[1];
                resizevector = resizevector.GetNormal() * Math.Sign(scale.y);
                resizeaxis   = new Line2D(corners[1], corners[1] + resizevector * texture.ScaledHeight / Math.Abs(sectorinfo[0].scale.y));
                resizefilter = new Vector2D(0.0f, 1.0f);
                mode         = ModifyMode.Resizing;
                break;

            // Rotate
            case Grip.RotateRT:
                rotationoffset = Angle2D.PIHALF;
                if (Math.Sign(scale.x * sectorinfo[0].scale.x) < 0)
                {
                    rotationoffset += Angle2D.PI;
                }
                rotationcenter = corners[0];
                mode           = ModifyMode.Rotating;
                break;

            // Rotate
            case Grip.RotateLB:
                rotationoffset = 0f;
                if (Math.Sign(scale.y * sectorinfo[0].scale.y) < 0)
                {
                    rotationoffset += Angle2D.PI;
                }
                rotationcenter = corners[0];
                mode           = ModifyMode.Rotating;
                break;

            // Outside the selection?
            default:
                // Accept and be done with it
                General.Editing.AcceptMode();
                break;
            }
        }
示例#26
0
 public IntModifier(ModifyMode mode, AttributeCode attribute, int value)
 {
     m_Attribute = attribute;
     m_Mode      = mode;
     m_Value     = value;
 }
示例#27
0
        public override void RenderOverlay(RenderManager.CameraInfo cameraInfo)
        {
            if (MainTool.GetToolController().IsInsideUI || !Cursor.visible)
            {
                return;
            }

            ModifyMode mode = ModifyMode.None;

            MassEditOverlay.Show = ControlIsPressed;

            if (HoveredSegmentId == 0)
            {
                massEditMode = PrioritySignsMassEditMode.Min;
                return;
            }

            if (Shortcuts.ShiftIsPressed)
            {
                bool  isRoundabout = RoundaboutMassEdit.Instance.TraverseLoop(HoveredSegmentId, out var segmentList);
                Color color        = MainTool.GetToolColor(Input.GetMouseButton(0), false);
                if (isRoundabout)
                {
                    foreach (ushort segmentId in segmentList)
                    {
                        NetTool.RenderOverlay(
                            cameraInfo,
                            ref segmentId.ToSegment(),
                            color,
                            color);
                    } // end foreach
                }
                else
                {
                    SegmentTraverser.Traverse(
                        HoveredSegmentId,
                        TraverseDirection.AnyDirection,
                        TraverseSide.Straight,
                        SegmentStopCriterion.None,
                        data => {
                        NetTool.RenderOverlay(
                            cameraInfo,
                            ref data.CurSeg.segmentId.ToSegment(),
                            color,
                            color);
                        return(true);
                    });
                }
                if (!ControlIsPressed)
                {
                    mode = ModifyMode.PriorityRoad;
                }
                else if (!isRoundabout)
                {
                    mode = ModifyMode.HighPriorityRoad;
                }
                else
                {
                    mode = ModifyMode.Roundabout;
                }

                if (mode != PrevHoveredState.Mode || HoveredSegmentId != PrevHoveredState.SegmentId)
                {
                    massEditMode = PrioritySignsMassEditMode.Min;
                }
            }
            else if (ControlIsPressed)
            {
                Highlight.DrawNodeCircle(
                    cameraInfo: cameraInfo,
                    nodeId: HoveredNodeId,
                    warning: Input.GetMouseButton(0));

                mode = ModifyMode.HighPriorityJunction;

                if (mode != PrevHoveredState.Mode || HoveredNodeId != PrevHoveredState.NodeId)
                {
                    massEditMode = PrioritySignsMassEditMode.Min;
                }
            }
            else
            {
                massEditMode = PrioritySignsMassEditMode.Min;

                if (HoveredNodeId == SelectedNodeId)
                {
                    return;
                }

                // no highlight for existing priority node in sign mode
                if (TrafficPriorityManager.Instance.HasNodePrioritySign(HoveredNodeId))
                {
                    // Log._Debug($"PrioritySignsTool.RenderOverlay: HasNodePrioritySign({HoveredNodeId})=true");
                    return;
                }

                if (!TrafficPriorityManager.Instance.MayNodeHavePrioritySigns(HoveredNodeId))
                {
                    // Log._Debug($"PrioritySignsTool.RenderOverlay: MayNodeHavePrioritySigns({HoveredNodeId})=false");
                    return;
                }

                Highlight.DrawNodeCircle(
                    cameraInfo: cameraInfo,
                    nodeId: HoveredNodeId,
                    warning: Input.GetMouseButton(0));
            }

            PrevHoveredState.Mode      = mode;
            PrevHoveredState.SegmentId = HoveredSegmentId;
            PrevHoveredState.NodeId    = HoveredNodeId;
        }
 public void OnFocus()
 {
     // update handlers. these static handlers are erase when window is full-screened and badk to normal window.
     modifyMode = ModifyMode.NONE;
     NodeGUIUtility.NodeEventHandler = HandleNodeEvent;
     ConnectionGUIUtility.ConnectionEventHandler = HandleConnectionEvent;
 }
        /**
            node graph initializer.
            setup nodes, points and connections from saved data.
        */
        public void InitializeGraph()
        {
            SaveData saveData = SaveData.LoadFromDisk();

            /*
                do nothing if json does not modified after first load.
            */
            if (saveData.LastModified == lastLoaded) {
                return;
            }

            lastLoaded = saveData.LastModified;

            minSize = new Vector2(600f, 300f);

            wantsMouseMove = true;
            modifyMode = ModifyMode.NONE;

            /*
                load graph data from deserialized data.
            */
            ConstructGraphFromSaveData(saveData, out this.nodes, out this.connections);
        }
示例#30
0
 /// <summary>
 /// Set ModifyMode to mode
 /// </summary>
 /// <param name="mode">mode of ModifyMode</param>
 private void SetModifyMode(ModifyMode mode)
 {
     ModifyMode = mode;
 }
        /**
         * Handle Node Event
        */
        private void HandleNodeEvent(NodeEvent e)
        {
            switch (modifyMode) {
                case ModifyMode.CONNECTING: {
                    switch (e.eventType) {
                        /*
                            handling
                        */
                        case NodeEvent.EventType.EVENT_NODE_MOVING: {
                            // do nothing.
                            break;
                        }

                        /*
                            connection drop detected from toward node.
                        */
                        case NodeEvent.EventType.EVENT_NODE_CONNECTION_RAISED: {
                            // finish connecting mode.
                            modifyMode = ModifyMode.NONE;

                            if (currentEventSource == null) {
                                break;
                            }

                            var sourceNode = currentEventSource.eventSourceNode;
                            var sourceConnectionPoint = currentEventSource.point;

                            var targetNode = e.eventSourceNode;
                            var targetConnectionPoint = e.point;

                            if (sourceNode.Id == targetNode.Id) {
                                break;
                            }

                            if (!IsConnectablePointFromTo(sourceConnectionPoint, targetConnectionPoint)) {
                                break;
                            }

                            var startNode = sourceNode;
                            var startConnectionPoint = sourceConnectionPoint;
                            var endNode = targetNode;
                            var endConnectionPoint = targetConnectionPoint;

                            // reverse if connected from input to output.
                            if (sourceConnectionPoint.IsInput) {
                                startNode = targetNode;
                                startConnectionPoint = targetConnectionPoint;
                                endNode = sourceNode;
                                endConnectionPoint = sourceConnectionPoint;
                            }

                            var outputPoint = startConnectionPoint;
                            var inputPoint = endConnectionPoint;
                            var label = startConnectionPoint.Label;

                            // if two nodes are not supposed to connect, dismiss
                            if(!ConnectionData.CanConnect(startNode.Data, endNode.Data)) {
                                break;
                            }

                            AddConnection(label, startNode, outputPoint, endNode, inputPoint);
                            SaveGraphWithReload();
                            break;
                        }

                        /*
                            connection drop detected by started node.
                        */
                        case NodeEvent.EventType.EVENT_NODE_CONNECTION_OVERED: {
                            // finish connecting mode.
                            modifyMode = ModifyMode.NONE;

                            /*
                                connect when dropped target is connectable from start connectionPoint.
                            */
                            var node = FindNodeByPosition(e.globalMousePosition);
                            if (node == null) {
                                break;
                            }

                            // ignore if target node is source itself.
                            if (node == e.eventSourceNode) {
                                break;
                            }

                            var pointAtPosition = node.FindConnectionPointByPosition(e.globalMousePosition);
                            if (pointAtPosition == null) {
                                break;
                            }

                            var sourcePoint = currentEventSource.point;

                            // limit by connectable or not.
                            if(!IsConnectablePointFromTo(sourcePoint, pointAtPosition)) {
                                break;
                            }

                            var isInput = currentEventSource.point.IsInput;
                            var startNode = (isInput)? node : e.eventSourceNode;
                            var endNode   = (isInput)? e.eventSourceNode: node;
                            var startConnectionPoint = (isInput)? pointAtPosition : currentEventSource.point;
                            var endConnectionPoint   = (isInput)? currentEventSource.point: pointAtPosition;
                            var outputPoint = startConnectionPoint;
                            var inputPoint = endConnectionPoint;
                            var label = startConnectionPoint.Label;

                            // if two nodes are not supposed to connect, dismiss
                            if(!ConnectionData.CanConnect(startNode.Data, endNode.Data)) {
                                break;
                            }

                            AddConnection(label, startNode, outputPoint, endNode, inputPoint);
                            SaveGraphWithReload();
                            break;
                        }

                        default: {
                            modifyMode = ModifyMode.NONE;
                            break;
                        }
                    }
                    break;
                }
                case ModifyMode.NONE: {
                    switch (e.eventType) {
                        /*
                            node move detected.
                        */
                        case NodeEvent.EventType.EVENT_NODE_MOVING: {
                            var tappedNode = e.eventSourceNode;
                            var tappedNodeId = tappedNode.Id;

                            if (activeObject.idPosDict.ContainsKey(tappedNodeId)) {
                                // already active, do nothing for this node.
                                var distancePos = tappedNode.GetPos() - activeObject.idPosDict.ReadonlyDict()[tappedNodeId];

                                foreach (var node in nodes) {
                                    if (node.Id == tappedNodeId) continue;
                                    if (!activeObject.idPosDict.ContainsKey(node.Id)) continue;
                                    var relativePos = activeObject.idPosDict.ReadonlyDict()[node.Id] + distancePos;
                                    node.SetPos(relativePos);
                                }
                                break;
                            }

                            if (Event.current.shift) {
                                Undo.RecordObject(this, "Select Objects");

                                var additiveIds = new List<string>(activeObject.idPosDict.ReadonlyDict().Keys);

                                additiveIds.Add(tappedNodeId);

                                activeObject = RenewActiveObject(additiveIds);

                                UpdateActivationOfObjects(activeObject);
                                UpdateSpacerRect();
                                break;
                            }

                            Undo.RecordObject(this, "Select " + tappedNode.Name);
                            activeObject = RenewActiveObject(new List<string>{tappedNodeId});
                            UpdateActivationOfObjects(activeObject);
                            break;
                        }

                        /*
                            start connection handling.
                        */
                        case NodeEvent.EventType.EVENT_NODE_CONNECT_STARTED: {
                            modifyMode = ModifyMode.CONNECTING;
                            currentEventSource = e;
                            break;
                        }

                        case NodeEvent.EventType.EVENT_CLOSE_TAPPED: {

                            Undo.RecordObject(this, "Delete Node");

                            var deletingNodeId = e.eventSourceNode.Id;
                            DeleteNode(deletingNodeId);

                            SaveGraphWithReload();
                            InitializeGraph();
                            break;
                        }

                        /*
                            releasse detected.
                                node move over.
                                node tapped.
                        */
                        case NodeEvent.EventType.EVENT_NODE_TOUCHED: {
                            var movedNode = e.eventSourceNode;
                            var movedNodeId = movedNode.Id;

                            // already active, node(s) are just tapped or moved.
                            if (activeObject.idPosDict.ContainsKey(movedNodeId)) {

                                /*
                                    active nodes(contains tap released node) are possibly moved.
                                */
                                var movedIdPosDict = new Dictionary<string, Vector2>();
                                foreach (var node in nodes) {
                                    if (!activeObject.idPosDict.ContainsKey(node.Id)) continue;

                                    var startPos = activeObject.idPosDict.ReadonlyDict()[node.Id];
                                    if (node.GetPos() != startPos) {
                                        // moved.
                                        movedIdPosDict[node.Id] = node.GetPos();
                                    }
                                }

                                if (movedIdPosDict.Any()) {

                                    foreach (var node in nodes) {
                                        if (activeObject.idPosDict.ReadonlyDict().Keys.Contains(node.Id)) {
                                            var startPos = activeObject.idPosDict.ReadonlyDict()[node.Id];
                                            node.SetPos(startPos);
                                        }
                                    }

                                    Undo.RecordObject(this, "Move " + movedNode.Name);

                                    foreach (var node in nodes) {
                                        if (movedIdPosDict.Keys.Contains(node.Id)) {
                                            var endPos = movedIdPosDict[node.Id];
                                            node.SetPos(endPos);
                                        }
                                    }

                                    var activeObjectIds = activeObject.idPosDict.ReadonlyDict().Keys.ToList();
                                    activeObject = RenewActiveObject(activeObjectIds);
                                } else {
                                    // nothing moved, should cancel selecting this node.
                                    var cancelledActivatedIds = new List<string>(activeObject.idPosDict.ReadonlyDict().Keys);
                                    cancelledActivatedIds.Remove(movedNodeId);

                                    Undo.RecordObject(this, "Select Objects");

                                    activeObject = RenewActiveObject(cancelledActivatedIds);
                                }

                                UpdateActivationOfObjects(activeObject);

                                UpdateSpacerRect();
                                SaveGraph();
                                break;
                            }

                            if (Event.current.shift) {
                                Undo.RecordObject(this, "Select Objects");

                                var additiveIds = new List<string>(activeObject.idPosDict.ReadonlyDict().Keys);

                                // already contained, cancel.
                                if (additiveIds.Contains(movedNodeId)) {
                                    additiveIds.Remove(movedNodeId);
                                } else {
                                    additiveIds.Add(movedNodeId);
                                }

                                activeObject = RenewActiveObject(additiveIds);
                                UpdateActivationOfObjects(activeObject);

                                UpdateSpacerRect();
                                SaveGraph();
                                break;
                            }

                            Undo.RecordObject(this, "Select " + movedNode.Name);

                            activeObject = RenewActiveObject(new List<string>{movedNodeId});
                            UpdateActivationOfObjects(activeObject);

                            UpdateSpacerRect();
                            SaveGraph();
                            break;
                        }

                        default: {
                            break;
                        }
                    }
                    break;
                }
            }

            switch (e.eventType) {
                case NodeEvent.EventType.EVENT_CONNECTIONPOINT_DELETED: {
                    // deleting point is handled by caller, so we are deleting connections associated with it.
                    connections.RemoveAll( c => (c.InputPoint == e.point || c.OutputPoint == e.point) );
                    Repaint();
                    break;
                }
                case NodeEvent.EventType.EVENT_CONNECTIONPOINT_LABELCHANGED: {
                    // point label change is handled by caller, so we are changing label of connection associated with it.
                    var affectingConnections = connections.FindAll( c=> c.OutputPoint == e.point );
                    affectingConnections.ForEach(c => c.Label = e.point.Label);
                    Repaint();
                    break;
                }
                case NodeEvent.EventType.EVENT_RECORDUNDO: {
                    Undo.RecordObject(this, e.message);
                    break;
                }
                case NodeEvent.EventType.EVENT_SAVE: {
                    SaveGraphWithReload(true);
                    Repaint();
                    break;
                }
            }
        }
        private void HandleGraphGUIEvents()
        {
            //mouse drag event handling.
            switch (Event.current.type) {
            // draw line while dragging.
            case EventType.MouseDrag: {
                    switch (modifyMode) {
                    case ModifyMode.NONE: {
                            switch (Event.current.button) {
                            case 0:{// left click
                                    if (Event.current.command) {
                                        scalePoint = new ScalePoint(Event.current.mousePosition, NodeGUI.scaleFactor, 0);
                                        modifyMode = ModifyMode.SCALING;
                                        break;
                                    }

                                    selection = new AssetBundleGraphSelection(Event.current.mousePosition);
                                    modifyMode = ModifyMode.SELECTING;
                                    break;
                                }
                            case 2:{// middle click.
                                    scalePoint = new ScalePoint(Event.current.mousePosition, NodeGUI.scaleFactor, 0);
                                    modifyMode = ModifyMode.SCALING;
                                    break;
                                }
                            }
                            break;
                        }
                    case ModifyMode.SELECTING: {
                            // do nothing.
                            break;
                        }
                    case ModifyMode.SCALING: {
                            var baseDistance = (int)Vector2.Distance(Event.current.mousePosition, new Vector2(scalePoint.x, scalePoint.y));
                            var distance = baseDistance / NodeGUI.SCALE_WIDTH;
                            var direction = (0 < Event.current.mousePosition.y - scalePoint.y);

                            if (!direction) distance = -distance;

                            // var before = NodeGUI.scaleFactor;
                            NodeGUI.scaleFactor = scalePoint.startScale + (distance * NodeGUI.SCALE_RATIO);

                            if (NodeGUI.scaleFactor < NodeGUI.SCALE_MIN) NodeGUI.scaleFactor = NodeGUI.SCALE_MIN;
                            if (NodeGUI.SCALE_MAX < NodeGUI.scaleFactor) NodeGUI.scaleFactor = NodeGUI.SCALE_MAX;
                            break;
                        }
                    }

                    HandleUtility.Repaint();
                    Event.current.Use();
                    break;
                }
            }

            // mouse up event handling.
            // use rawType for detect for detectiong mouse-up which raises outside of window.
            switch (Event.current.rawType) {
            case EventType.MouseUp: {
                    switch (modifyMode) {
                    /*
                                select contained nodes & connections.
                            */
                    case ModifyMode.SELECTING: {
                            var x = 0f;
                            var y = 0f;
                            var width = 0f;
                            var height = 0f;

                            if (Event.current.mousePosition.x < selection.x) {
                                x = Event.current.mousePosition.x;
                                width = selection.x - Event.current.mousePosition.x;
                            }
                            if (selection.x < Event.current.mousePosition.x) {
                                x = selection.x;
                                width = Event.current.mousePosition.x - selection.x;
                            }

                            if (Event.current.mousePosition.y < selection.y) {
                                y = Event.current.mousePosition.y;
                                height = selection.y - Event.current.mousePosition.y;
                            }
                            if (selection.y < Event.current.mousePosition.y) {
                                y = selection.y;
                                height = Event.current.mousePosition.y - selection.y;
                            }

                            var activeObjectIds = new List<string>();

                            var selectedRect = new Rect(x, y, width, height);

                            foreach (var node in nodes) {
                                var nodeRect = new Rect(node.GetRect());
                                nodeRect.x = nodeRect.x * NodeGUI.scaleFactor;
                                nodeRect.y = nodeRect.y * NodeGUI.scaleFactor;
                                nodeRect.width = nodeRect.width * NodeGUI.scaleFactor;
                                nodeRect.height = nodeRect.height * NodeGUI.scaleFactor;
                                // get containd nodes,
                                if (nodeRect.Overlaps(selectedRect)) {
                                    activeObjectIds.Add(node.Id);
                                }
                            }

                            foreach (var connection in connections) {
                                // get contained connection badge.
                                if (connection.GetRect().Overlaps(selectedRect)) {
                                    activeObjectIds.Add(connection.Id);
                                }
                            }

                            if (Event.current.shift) {
                                // add current active object ids to new list.
                                foreach (var alreadySelectedObjectId in activeObject.idPosDict.ReadonlyDict().Keys) {
                                    if (!activeObjectIds.Contains(alreadySelectedObjectId)) activeObjectIds.Add(alreadySelectedObjectId);
                                }
                            } else {
                                // do nothing, means cancel selections if nodes are not contained by selection.
                            }

                            Undo.RecordObject(this, "Select Objects");

                            activeObject = RenewActiveObject(activeObjectIds);
                            UpdateActivationOfObjects(activeObject);

                            selection = new AssetBundleGraphSelection(Vector2.zero);
                            modifyMode = ModifyMode.NONE;

                            HandleUtility.Repaint();
                            Event.current.Use();
                            break;
                        }

                    case ModifyMode.SCALING: {
                            modifyMode = ModifyMode.NONE;
                            break;
                        }
                    }
                    break;
                }
            }
        }
示例#33
0
 /// <summary>
 /// Modifies (delete, update, insert) the history of a variable using a set of data points.
 /// </summary>
 /// <param name="variable">The variable</param>
 /// <param name="mode">The modification mode, e.g. Insert, Update, Delete</param>
 /// <param name="data">The data points used for modification</param>
 public abstract Task HistorianModify(VariableRef variable, ModifyMode mode, params VTQ[] data);
示例#34
0
        /**
            emit event from node-GUI.
        */
        private void EmitNodeEvent(OnNodeEvent e)
        {
            switch (modifyMode) {
                case ModifyMode.CONNECT_STARTED: {
                    switch (e.eventType) {
                        /*
                            handling
                        */
                        case OnNodeEvent.EventType.EVENT_NODE_MOVING: {
                            // do nothing.
                            break;
                        }

                        /*
                            connection drop detected from toward node.
                        */
                        case OnNodeEvent.EventType.EVENT_NODE_CONNECTION_RAISED: {
                            // finish connecting mode.
                            modifyMode = ModifyMode.CONNECT_ENDED;

                            if (currentEventSource == null) break;

                            var sourceNode = currentEventSource.eventSourceNode;
                            var sourceConnectionPoint = currentEventSource.eventSourceConnectionPoint;

                            var targetNode = e.eventSourceNode;
                            var targetConnectionPoint = e.eventSourceConnectionPoint;

                            if (sourceNode.nodeId == targetNode.nodeId) break;

                            if (!IsConnectablePointFromTo(sourceConnectionPoint, targetConnectionPoint)) break;

                            var startNode = sourceNode;
                            var startConnectionPoint = sourceConnectionPoint;
                            var endNode = targetNode;
                            var endConnectionPoint = targetConnectionPoint;

                            // reverse if connected from input to output.
                            if (sourceConnectionPoint.isInput) {
                                startNode = targetNode;
                                startConnectionPoint = targetConnectionPoint;
                                endNode = sourceNode;
                                endConnectionPoint = sourceConnectionPoint;
                            }

                            var label = startConnectionPoint.label;
                            AddConnection(label, startNode, startConnectionPoint, endNode, endConnectionPoint);
                            SaveGraphWithReload();
                            break;
                        }

                        /*
                            connection drop detected by started node.
                        */
                        case OnNodeEvent.EventType.EVENT_NODE_CONNECTION_OVERED: {
                            // finish connecting mode.
                            modifyMode = ModifyMode.CONNECT_ENDED;

                            /*
                                connect when dropped target is connectable from start connectionPoint.
                            */
                            var candidateNodes = NodesUnderPosition(e.globalMousePosition);

                            if (!candidateNodes.Any()) break;

                            var nodeUnderMouse = candidateNodes[0];

                            // ignore if target node is source itself.
                            if (nodeUnderMouse.nodeId == e.eventSourceNode.nodeId) break;

                            var candidatePoints = nodeUnderMouse.ConnectionPointUnderGlobalPos(e.globalMousePosition);

                            if (!candidatePoints.Any()) break;

                            var sourcePoint = currentEventSource.eventSourceConnectionPoint;

                            // limit by connectable or not.
                            var connectableCandidates = candidatePoints.Where(point => IsConnectablePointFromTo(sourcePoint, point)).ToList();
                            if (!connectableCandidates.Any()) break;

                            // target point is determined.
                            var connectablePoint = connectableCandidates.First();

                            var startNode = e.eventSourceNode;
                            var startConnectionPoint = currentEventSource.eventSourceConnectionPoint;
                            var endNode = nodeUnderMouse;
                            var endConnectionPoint = connectablePoint;

                            // reverse if connected from input to output.
                            if (startConnectionPoint.isInput) {
                                startNode = nodeUnderMouse;
                                startConnectionPoint = connectablePoint;
                                endNode = e.eventSourceNode;
                                endConnectionPoint = currentEventSource.eventSourceConnectionPoint;
                            }

                            var label = startConnectionPoint.label;
                            AddConnection(label, startNode, startConnectionPoint, endNode, endConnectionPoint);
                            SaveGraphWithReload();
                            break;
                        }

                        default: {
                            // Debug.Log("unconsumed or ignored event:" + e.eventType);
                            modifyMode = ModifyMode.CONNECT_ENDED;
                            break;
                        }
                    }
                    break;
                }
                case ModifyMode.CONNECT_ENDED: {
                    switch (e.eventType) {
                        /*
                            node move detected.
                        */
                        case OnNodeEvent.EventType.EVENT_NODE_MOVING: {
                            var tappedNode = e.eventSourceNode;
                            var tappedNodeId = tappedNode.nodeId;

                            if (activeObject.idPosDict.ContainsKey(tappedNodeId)) {
                                // already active, do nothing for this node.
                                var distancePos = tappedNode.GetPos() - activeObject.idPosDict.ReadonlyDict()[tappedNodeId];

                                foreach (var node in nodes) {
                                    if (node.nodeId == tappedNodeId) continue;
                                    if (!activeObject.idPosDict.ContainsKey(node.nodeId)) continue;
                                    var relativePos = activeObject.idPosDict.ReadonlyDict()[node.nodeId] + distancePos;
                                    node.SetPos(relativePos);
                                }
                                break;
                            }

                            if (Event.current.shift) {
                                Undo.RecordObject(this, "Select Objects");

                                var additiveIds = new List<string>(activeObject.idPosDict.ReadonlyDict().Keys);

                                additiveIds.Add(tappedNodeId);

                                activeObject = RenewActiveObject(additiveIds);

                                UpdateActivationOfObjects(activeObject);
                                UpdateSpacerRect();
                                break;
                            }

                            Undo.RecordObject(this, "Select Node");
                            activeObject = RenewActiveObject(new List<string>{tappedNodeId});
                            UpdateActivationOfObjects(activeObject);
                            break;
                        }

                        /*
                            start connection handling.
                        */
                        case OnNodeEvent.EventType.EVENT_NODE_CONNECT_STARTED: {
                            modifyMode = ModifyMode.CONNECT_STARTED;
                            currentEventSource = e;
                            break;
                        }

                        case OnNodeEvent.EventType.EVENT_CLOSE_TAPPED: {

                            Undo.RecordObject(this, "Delete Node");

                            var deletingNodeId = e.eventSourceNode.nodeId;
                            DeleteNode(deletingNodeId);

                            SaveGraphWithReload();
                            InitializeGraph();
                            break;
                        }

                        /*
                            releasse detected.
                                node move over.
                                node tapped.
                        */
                        case OnNodeEvent.EventType.EVENT_NODE_TOUCHED: {
                            var movedNode = e.eventSourceNode;
                            var movedNodeId = movedNode.nodeId;

                            // already active, node(s) are just tapped or moved.
                            if (activeObject.idPosDict.ContainsKey(movedNodeId)) {

                                /*
                                    active nodes(contains tap released node) are possibly moved.
                                */
                                var movedIdPosDict = new Dictionary<string, Vector2>();
                                foreach (var node in nodes) {
                                    if (!activeObject.idPosDict.ContainsKey(node.nodeId)) continue;

                                    var startPos = activeObject.idPosDict.ReadonlyDict()[node.nodeId];
                                    if (node.GetPos() != startPos) {
                                        // moved.
                                        movedIdPosDict[node.nodeId] = node.GetPos();
                                    }
                                }

                                if (movedIdPosDict.Any()) {

                                    foreach (var node in nodes) {
                                        if (activeObject.idPosDict.ReadonlyDict().Keys.Contains(node.nodeId)) {
                                            var startPos = activeObject.idPosDict.ReadonlyDict()[node.nodeId];
                                            node.SetPos(startPos);
                                        }
                                    }

                                    Undo.RecordObject(this, "Move Node");

                                    foreach (var node in nodes) {
                                        if (movedIdPosDict.Keys.Contains(node.nodeId)) {
                                            var endPos = movedIdPosDict[node.nodeId];
                                            node.SetPos(endPos);
                                        }
                                    }

                                    var activeObjectIds = activeObject.idPosDict.ReadonlyDict().Keys.ToList();
                                    activeObject = RenewActiveObject(activeObjectIds);
                                } else {
                                    // nothing moved, should cancel selecting this node.
                                    var cancelledActivatedIds = new List<string>(activeObject.idPosDict.ReadonlyDict().Keys);
                                    cancelledActivatedIds.Remove(movedNodeId);

                                    Undo.RecordObject(this, "Select Objects");

                                    activeObject = RenewActiveObject(cancelledActivatedIds);
                                }

                                UpdateActivationOfObjects(activeObject);

                                UpdateSpacerRect();
                                SaveGraph();
                                break;
                            }

                            if (Event.current.shift) {
                                Undo.RecordObject(this, "Select Objects");

                                var additiveIds = new List<string>(activeObject.idPosDict.ReadonlyDict().Keys);

                                // already contained, cancel.
                                if (additiveIds.Contains(movedNodeId)) {
                                    additiveIds.Remove(movedNodeId);
                                } else {
                                    additiveIds.Add(movedNodeId);
                                }

                                activeObject = RenewActiveObject(additiveIds);
                                UpdateActivationOfObjects(activeObject);

                                UpdateSpacerRect();
                                SaveGraph();
                                break;
                            }

                            Undo.RecordObject(this, "Select Node");

                            activeObject = RenewActiveObject(new List<string>{movedNodeId});
                            UpdateActivationOfObjects(activeObject);

                            UpdateSpacerRect();
                            SaveGraph();
                            break;
                        }

                        default: {
                            // Debug.Log("unconsumed or ignored event:" + e.eventType);
                            break;
                        }
                    }
                    break;
                }
            }

            switch (e.eventType) {
                case OnNodeEvent.EventType.EVENT_CONNECTIONPOINT_DELETED: {
                    var deletedConnectionPoint = e.eventSourceConnectionPoint;
                    var deletedOutputPointConnections = connections.Where(con => con.outputPoint.pointId == deletedConnectionPoint.pointId).ToList();

                    if (!deletedOutputPointConnections.Any()) break;

                    connections.Remove(deletedOutputPointConnections[0]);
                    break;
                }
                case OnNodeEvent.EventType.EVENT_CONNECTIONPOINT_LABELCHANGED: {
                    var labelChangedConnectionPoint = e.eventSourceConnectionPoint;
                    var changedLabel = labelChangedConnectionPoint.label;

                    var labelChangedOutputPointConnections = connections.Where(con => con.outputPoint.pointId == labelChangedConnectionPoint.pointId).ToList();

                    if (!labelChangedOutputPointConnections.Any()) break;

                    labelChangedOutputPointConnections[0].label = changedLabel;
                    break;
                }
                case OnNodeEvent.EventType.EVENT_BEFORESAVE: {
                    Undo.RecordObject(this, "Update Node Setting");
                    break;
                }
                case OnNodeEvent.EventType.EVENT_SAVE: {
                    SaveGraphWithReloadSilent();
                    Repaint();
                    break;
                }
            }
        }
        public void OnGUI()
        {
            DrawGUIToolBar();

            using (new EditorGUILayout.HorizontalScope()) {
                DrawGUINodeGraph();
                if(showErrors) {
                    DrawGUINodeErrors();
                }
            }

            /*
                Event Handling:
                - Supporting dragging script into window to create node.
                - Context Menu
                - NodeGUI connection.
                - Command(Delete, Copy, etc...)
            */
            switch (Event.current.type) {
                // detect dragging script then change interface to "(+)" icon.
                case EventType.DragUpdated: {
                    var refs = DragAndDrop.objectReferences;

                    foreach (var refe in refs) {
                        if (refe.GetType() == typeof(UnityEditor.MonoScript)) {
                            Type scriptTypeInfo = ((MonoScript)refe).GetClass();
                            Type inheritedTypeInfo = GetDragAndDropAcceptableScriptType(scriptTypeInfo);

                            if (inheritedTypeInfo != null) {
                                // at least one asset is script. change interface.
                                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                                break;
                            }
                        }
                    }
                    break;
                }

                // script drop on editor.
                case EventType.DragPerform: {
                    var pathAndRefs = new Dictionary<string, object>();
                    for (var i = 0; i < DragAndDrop.paths.Length; i++) {
                        var path = DragAndDrop.paths[i];
                        var refe = DragAndDrop.objectReferences[i];
                        pathAndRefs[path] = refe;
                    }
                    var shouldSave = false;
                    foreach (var item in pathAndRefs) {
                        var refe = (MonoScript)item.Value;
                        if (refe.GetType() == typeof(UnityEditor.MonoScript)) {
                            Type scriptTypeInfo = refe.GetClass();
                            Type inheritedTypeInfo = GetDragAndDropAcceptableScriptType(scriptTypeInfo);

                            if (inheritedTypeInfo != null) {
                                var dropPos = Event.current.mousePosition;
                                var scriptName = refe.name;
                                var scriptClassName = scriptName;
                                AddNodeFromCode(scriptName, scriptClassName, inheritedTypeInfo, dropPos.x, dropPos.y);
                                shouldSave = true;
                            }
                        }
                    }

                    if (shouldSave) {
                        SaveGraphWithReload();
                    }
                    break;
                }

                // show context menu
                case EventType.ContextClick: {
                    var rightClickPos = Event.current.mousePosition;
                    var menu = new GenericMenu();
                    foreach (var menuItemStr in AssetBundleGraphSettings.GUI_Menu_Item_TargetGUINodeDict.Keys) {
                        var kind = AssetBundleGraphSettings.GUI_Menu_Item_TargetGUINodeDict[menuItemStr];
                        menu.AddItem(
                            new GUIContent(menuItemStr),
                            false,
                            () => {
                                AddNodeFromGUI(kind, rightClickPos.x, rightClickPos.y);
                                SaveGraphWithReload();
                                Repaint();
                            }
                        );
                    }
                    menu.ShowAsContext();
                    break;
                }

                /*
                    Handling mouseUp at empty space.
                */
                case EventType.MouseUp: {
                    modifyMode = ModifyMode.NONE;
                    HandleUtility.Repaint();

                    if (activeObject.idPosDict.ReadonlyDict().Any()) {
                        Undo.RecordObject(this, "Unselect");

                        foreach (var activeObjectId in activeObject.idPosDict.ReadonlyDict().Keys) {
                            // unselect all.
                            foreach (var node in nodes) {
                                if (activeObjectId == node.Id) {
                                    node.SetInactive();
                                }
                            }
                            foreach (var connection in connections) {
                                if (activeObjectId == connection.Id) {
                                    connection.SetInactive();
                                }
                            }
                        }

                        activeObject = RenewActiveObject(new List<string>());

                    }

                    // clear inspector
                    if( Selection.activeObject is NodeGUIInspectorHelper || Selection.activeObject is ConnectionGUIInspectorHelper) {
                        Selection.activeObject = null;
                    }

                    break;
                }

                /*
                    scale up or down by command & + or command & -.
                */
                case EventType.KeyDown: {
                    if (Event.current.command) {
                        if (Event.current.shift && Event.current.keyCode == KeyCode.Semicolon) {
                            NodeGUI.scaleFactor = NodeGUI.scaleFactor + 0.1f;
                            if (NodeGUI.scaleFactor < NodeGUI.SCALE_MIN) NodeGUI.scaleFactor = NodeGUI.SCALE_MIN;
                            if (NodeGUI.SCALE_MAX < NodeGUI.scaleFactor) NodeGUI.scaleFactor = NodeGUI.SCALE_MAX;
                            Event.current.Use();
                            break;
                        }

                        if (Event.current.keyCode == KeyCode.Minus) {
                            NodeGUI.scaleFactor = NodeGUI.scaleFactor - 0.1f;
                            if (NodeGUI.scaleFactor < NodeGUI.SCALE_MIN) NodeGUI.scaleFactor = NodeGUI.SCALE_MIN;
                            if (NodeGUI.SCALE_MAX < NodeGUI.scaleFactor) NodeGUI.scaleFactor = NodeGUI.SCALE_MAX;
                            Event.current.Use();
                            break;
                        }
                    }
                    break;
                }

                case EventType.ValidateCommand:
                {
                    switch (Event.current.commandName) {
                    // Delete active node or connection.
                    case "Delete": {
                            if (activeObject.idPosDict.ReadonlyDict().Any()) {
                                Event.current.Use();
                            }
                            break;
                        }

                    case "Copy": {
                            if (activeObject.idPosDict.ReadonlyDict().Any()) {
                                Event.current.Use();
                            }
                            break;
                        }

                    case "Cut": {
                            if (activeObject.idPosDict.ReadonlyDict().Any()) {
                                Event.current.Use();
                            }
                            break;
                        }

                    case "Paste": {
                            if(copyField.datas == null)  {
                                break;
                            }

                            if (copyField.datas.Any()) {
                                Event.current.Use();
                            }
                            break;
                        }

                    case "SelectAll": {
                            Event.current.Use();
                            break;
                        }
                    }
                    break;
                }

                case EventType.ExecuteCommand:
                {
                    switch (Event.current.commandName) {
                        // Delete active node or connection.
                        case "Delete": {

                            if (!activeObject.idPosDict.ReadonlyDict().Any()) break;
                            Undo.RecordObject(this, "Delete Selection");

                            foreach (var targetId in activeObject.idPosDict.ReadonlyDict().Keys) {
                                DeleteNode(targetId);
                                DeleteConnectionById(targetId);
                            }

                            SaveGraphWithReload();

                            activeObject = RenewActiveObject(new List<string>());
                            UpdateActivationOfObjects(activeObject);

                            Event.current.Use();
                            break;
                        }

                        case "Copy": {
                            if (!activeObject.idPosDict.ReadonlyDict().Any()) {
                                break;
                            }

                            Undo.RecordObject(this, "Copy Selection");

                            var targetNodeIds = activeObject.idPosDict.ReadonlyDict().Keys.ToList();
                            var targetNodeJsonRepresentations = JsonRepresentations(targetNodeIds);
                            copyField = new CopyField(targetNodeJsonRepresentations, CopyType.COPYTYPE_COPY);

                            Event.current.Use();
                            break;
                        }

                        case "Cut": {
                            if (!activeObject.idPosDict.ReadonlyDict().Any()) {
                                break;
                            }

                            Undo.RecordObject(this, "Cut Selection");
                            var targetNodeIds = activeObject.idPosDict.ReadonlyDict().Keys.ToList();
                            var targetNodeJsonRepresentations = JsonRepresentations(targetNodeIds);
                            copyField = new CopyField(targetNodeJsonRepresentations, CopyType.COPYTYPE_CUT);

                            foreach (var targetId in activeObject.idPosDict.ReadonlyDict().Keys) {
                                DeleteNode(targetId);
                                DeleteConnectionById(targetId);
                            }

                            SaveGraphWithReload();
                            InitializeGraph();

                            activeObject = RenewActiveObject(new List<string>());
                            UpdateActivationOfObjects(activeObject);

                            Event.current.Use();
                            break;
                        }

                        case "Paste": {

                            if(copyField.datas == null)  {
                                break;
                            }

                            var nodeNames = nodes.Select(node => node.Name).ToList();
                            var duplicatingData = new List<NodeGUI>();

                            if (copyField.datas.Any()) {
                                var pasteType = copyField.type;
                                foreach (var copyFieldData in copyField.datas) {
                                    var nodeJsonDict = AssetBundleGraph.Json.Deserialize(copyFieldData) as Dictionary<string, object>;
                                    var pastingNode = new NodeGUI(new NodeData(nodeJsonDict));
                                    var pastingNodeName = pastingNode.Name;

                                    var nameOverlapping = nodeNames.Where(name => name == pastingNodeName).ToList();

              									switch (pasteType) {
              										case CopyType.COPYTYPE_COPY: {
                                            if (2 <= nameOverlapping.Count) {
                                                continue;
                                            }
              											break;
              										}
              										case CopyType.COPYTYPE_CUT: {
                                            if (1 <= nameOverlapping.Count) {
                                                continue;
                                            }
              											break;
              										}
              									}

              									duplicatingData.Add(pastingNode);
                                }
                            }
                            // consume copyField
                            copyField.datas = null;

                            if (!duplicatingData.Any()) {
                                break;
                            }

                            Undo.RecordObject(this, "Paste");
                            foreach (var newNode in duplicatingData) {
                                DuplicateNode(newNode);
                            }

                            SaveGraphWithReload();
                            InitializeGraph();

                            Event.current.Use();
                            break;
                        }

                        case "SelectAll": {
                            Undo.RecordObject(this, "Select All Objects");

                            var nodeIds = nodes.Select(node => node.Id).ToList();
                            activeObject = RenewActiveObject(nodeIds);

                            // select all.
                            foreach (var node in nodes) {
                                node.SetActive();
                            }
                            foreach (var connection in connections) {
                                connection.SetActive();
                            }

                            Event.current.Use();
                            break;
                        }

                        default: {
                            break;
                        }
                    }
                    break;
                }
            }
        }
        public void Setup(Matrix m, Rect imageRect, RectF cropRect, bool maintainAspectRatio)
        {
            matrix = new Matrix(m);

            this.cropRect = cropRect;
            this.imageRect = new RectF(imageRect);
            this.maintainAspectRatio = maintainAspectRatio;

            initialAspectRatio = cropRect.Width() / cropRect.Height();
            DrawRect = computeLayout();

            focusPaint.SetARGB(125, 50, 50, 50);
            noFocusPaint.SetARGB(125, 50, 50, 50);
            outlinePaint.StrokeWidth = 3;
            outlinePaint.SetStyle(Paint.Style.Stroke);
            outlinePaint.AntiAlias = true;

            mode = ModifyMode.None;
            init();
        }
 public void OnLostFocus()
 {
     modifyMode = ModifyMode.NONE;
 }
示例#38
0
        public override void RenderOverlay(RenderManager.CameraInfo cameraInfo)
        {
            if (MainTool.GetToolController().IsInsideUI || !Cursor.visible)
            {
                return;
            }

            ModifyMode mode = ModifyMode.None;

            MassEditOverlay.Show = ControlIsPressed;

            if (HoveredSegmentId == 0)
            {
                massEditMode = PrioritySignsMassEditMode.Min;
                return;
            }

            if (Shortcuts.ShiftIsPressed)
            {
                bool  isRoundabout = RoundaboutMassEdit.Instance.TraverseLoop(HoveredSegmentId, out var segmentList);
                Color color        = MainTool.GetToolColor(Input.GetMouseButton(0), false);
                if (isRoundabout)
                {
                    foreach (uint segmentId in segmentList)
                    {
                        ref NetSegment seg = ref Singleton <NetManager> .instance.m_segments.m_buffer[segmentId];
                        NetTool.RenderOverlay(
                            cameraInfo,
                            ref seg,
                            color,
                            color);
                    } // end foreach
                }
                else
                {
                    SegmentTraverser.Traverse(
                        HoveredSegmentId,
                        TraverseDirection.AnyDirection,
                        TraverseSide.Straight,
                        SegmentStopCriterion.None,
                        data => {
                        NetTool.RenderOverlay(
                            cameraInfo,
                            ref Singleton <NetManager> .instance.m_segments.m_buffer[
                                data.CurSeg.segmentId],
                            color,
                            color);
                        return(true);
                    });
                }
                if (!ControlIsPressed)
                {
                    mode = ModifyMode.PriorityRoad;
                }
                else if (!isRoundabout)
                {
                    mode = ModifyMode.HighPriorityRoad;
                }
                else
                {
                    mode = ModifyMode.Roundabout;
                }

                if (mode != PrevHoveredState.Mode || HoveredSegmentId != PrevHoveredState.SegmentId)
                {
                    massEditMode = PrioritySignsMassEditMode.Min;
                }
            }
示例#39
0
        public void EmitEvent(OnNodeEvent e)
        {
            switch (modifyMode)
            {
            case ModifyMode.CONNECT_STARTED: {
                switch (e.eventType)
                {
                /*
                 *      handling
                 */
                case OnNodeEvent.EventType.EVENT_CONNECTIONPOINT_HANDLING: {
                    /*
                     *      animate connectionPoint under mouse if this connectionPoint is able to accept this kind of connection.
                     */
                    if (false)
                    {
                        var candidateNodes = NodesUnderPosition(e.globalMousePosition);

                        if (!candidateNodes.Any())
                        {
                            break;
                        }
                        var nodeUnderMouse = candidateNodes.Last();

                        // ignore if target node is source itself.
                        if (nodeUnderMouse == e.eventSourceNode)
                        {
                            break;
                        }

                        var candidatePoints = nodeUnderMouse.ConnectionPointUnderGlobalPos(e.globalMousePosition);

                        var sourcePoint = currentEventSource.eventSourceConnectionPoint;

                        // limit by connectable or not.
                        var connectableCandidates = candidatePoints.Where(point => IsConnectablePointFromTo(sourcePoint, point)).ToList();
                        if (!connectableCandidates.Any())
                        {
                            break;
                        }

                        // connectable point is exist. change line color.

                        // or, do something..
                        Debug.Log("connectable!");
                    }
                    break;
                }

                /*
                 *      drop detected.
                 */
                case OnNodeEvent.EventType.EVENT_CONNECTIONPOINT_DROPPED: {
                    // finish connecting mode.
                    modifyMode = ModifyMode.CONNECT_ENDED;

                    /*
                     *      connect when dropped target is connectable from start connectionPoint.
                     */
                    {
                        var candidateNodes = NodesUnderPosition(e.globalMousePosition);

                        if (!candidateNodes.Any())
                        {
                            break;
                        }
                        var nodeUnderMouse = candidateNodes.Last();

                        // ignore if target node is source itself.
                        if (nodeUnderMouse == e.eventSourceNode)
                        {
                            break;
                        }

                        var candidatePoints = nodeUnderMouse.ConnectionPointUnderGlobalPos(e.globalMousePosition);

                        var sourcePoint = currentEventSource.eventSourceConnectionPoint;

                        // limit by connectable or not.
                        var connectableCandidates = candidatePoints.Where(point => IsConnectablePointFromTo(sourcePoint, point)).ToList();
                        if (!connectableCandidates.Any())
                        {
                            break;
                        }


                        // target point is determined.
                        var connectablePoint = connectableCandidates.First();

                        var startNode            = e.eventSourceNode;
                        var startConnectionPoint = currentEventSource.eventSourceConnectionPoint;
                        var endNode            = nodeUnderMouse;
                        var endConnectionPoint = connectablePoint;

                        // reverse if connected from input to output.
                        if (startConnectionPoint.isInput)
                        {
                            startNode            = nodeUnderMouse;
                            startConnectionPoint = connectablePoint;
                            endNode            = e.eventSourceNode;
                            endConnectionPoint = currentEventSource.eventSourceConnectionPoint;
                        }

                        // create new connection if same relations are not exist yet.
                        if (!connections.ContainsConnection(startNode, startConnectionPoint, endNode, endConnectionPoint))
                        {
                            connections.Add(new Connection(Guid.NewGuid().ToString(), startNode, startConnectionPoint, endNode, endConnectionPoint));
                        }
                    }
                    break;
                }

                default: {
                    // Debug.Log("unconsumed or ignored event:" + e.eventType);
                    modifyMode = ModifyMode.CONNECT_ENDED;
                    break;
                }
                }
                break;
            }

            case ModifyMode.CONNECT_ENDED: {
                switch (e.eventType)
                {
                /*
                 *      start connection handling.
                 */
                case OnNodeEvent.EventType.EVENT_CONNECTIONPOINT_HANDLE_STARTED: {
                    modifyMode         = ModifyMode.CONNECT_STARTED;
                    currentEventSource = e;
                    break;
                }

                /*
                 *      connectionPoint tapped.
                 */
                case OnNodeEvent.EventType.EVENT_CONNECTIONPOINT_RECEIVE_TAPPED: {
                    var sourcePoint = e.eventSourceConnectionPoint;

                    var relatedConnections = connections.
                                             Where(
                        con => con.IsStartAtConnectionPoint(sourcePoint) ||
                        con.IsEndAtConnectionPoint(sourcePoint)
                        ).
                                             ToList();

                    /*
                     *      show menuContext for control these connections.
                     */
                    var menu = new GenericMenu();
                    foreach (var con in relatedConnections)
                    {
                        var message = string.Empty;
                        if (sourcePoint.isInput)
                        {
                            message = "from " + con.startPointInfo;
                        }
                        if (sourcePoint.isOutput)
                        {
                            message = "to " + con.endPointInfo;
                        }

                        var conId = con.connectionId;

                        menu.AddItem(
                            new GUIContent("delete connection:" + con.label + " " + message),
                            false,
                            () => {
                                    DeleteConnection(conId);
                                }
                            );
                    }
                    menu.ShowAsContext();
                    break;
                }

                default: {
                    // Debug.Log("unconsumed or ignored event:" + e.eventType);
                    break;
                }
                }
                break;
            }
            }
        }
示例#40
0
        /// <summary>
        /// Is exists dnsName in List of DNS value
        /// </summary>
        /// <param name="dnsList">List of DNS value</param>
        /// <param name="dnsName">DNS name</param>
        /// <param name="error">Output error string</param>
        /// <returns></returns>
        public static bool IsExistsDuplicateName(List <DNS> dnsList, string dnsName, out string error, ModifyMode modifyMode)
        {
            object isExists;

            if (modifyMode == ModifyMode.Edit)
            {
                isExists = dnsList.Where(x => x.Name == dnsName).ToList();
                error    = (isExists as List <DNS>).Count > 1 ? Resources.ExistsDuplicateDNS : null;
            }
            else
            {
                isExists = dnsList.Where(x => x.Name == dnsName).FirstOrDefault();
                error    = isExists != null ? Resources.ExistsDuplicateDNS : null;
            }

            return(error != null);
        }
示例#41
0
        /**
            node window initializer.
            setup nodes, points and connections from saved data.
        */
        public void InitializeGraph()
        {
            if (reloadButtonTexture == null) {
                Debug.LogError("ローディング画像、ひどい読み方。");
                var reloadTextureSources = Resources
                    .FindObjectsOfTypeAll(typeof(Texture2D))
                    .Where(data => data.ToString().Contains("d_RotateTool"))
                    .ToList();
                if (0 < reloadTextureSources.Count) reloadButtonTexture = reloadTextureSources[0] as Texture2D;
            }

            var basePath = Path.Combine(Application.dataPath, AssetGraphSettings.ASSETGRAPH_TEMP_PATH);

            // create Temp folder under Assets/AssetGraph
            if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath);

            var graphDataPath = Path.Combine(basePath, AssetGraphSettings.ASSETGRAPH_DATA_NAME);

            var deserialized = new Dictionary<string, object>();
            var lastModified = DateTime.Now;

            if (File.Exists(graphDataPath)) {

                // load
                var dataStr = string.Empty;

                using (var sr = new StreamReader(graphDataPath)) {
                    dataStr = sr.ReadToEnd();
                }

                try {
                    deserialized = Json.Deserialize(dataStr) as Dictionary<string, object>;
                } catch (Exception e) {
                    Debug.LogError("data load error:" + e + " at path:" + graphDataPath);
                    return;
                }

                var lastModifiedStr = deserialized[AssetGraphSettings.ASSETGRAPH_DATA_LASTMODIFIED] as string;
                lastModified = Convert.ToDateTime(lastModifiedStr);

                var validatedDataDict = GraphStackController.ValidateStackedGraph(deserialized);

                var validatedDate = validatedDataDict[AssetGraphSettings.ASSETGRAPH_DATA_LASTMODIFIED] as string;
                if (lastModifiedStr != validatedDate) {
                    // save validated graph data.
                    UpdateGraphData(validatedDataDict);

                    // reload
                    var dataStr2 = string.Empty;
                    using (var sr = new StreamReader(graphDataPath)) {
                        dataStr2 = sr.ReadToEnd();
                    }

                    deserialized = Json.Deserialize(dataStr2) as Dictionary<string, object>;

                    var lastModifiedStr2 = deserialized[AssetGraphSettings.ASSETGRAPH_DATA_LASTMODIFIED] as string;
                    lastModified = Convert.ToDateTime(lastModifiedStr2);
                }

            } else {
                // renew
                var graphData = new Dictionary<string, object>{
                    {
                        AssetGraphSettings.ASSETGRAPH_DATA_LASTMODIFIED, lastModified.ToString()
                    },
                    {
                        AssetGraphSettings.ASSETGRAPH_DATA_NODES, new List<object>()
                    },
                    {
                        AssetGraphSettings.ASSETGRAPH_DATA_CONNECTIONS, new List<object>()
                    }
                };

                // save new empty graph data.
                UpdateGraphData(graphData);

                // set new empty graph data.
                deserialized = graphData;
            }

            /*
                do nothing if json does not modified after first load.
            */
            if (lastModified == lastLoaded) return;

            lastLoaded = lastModified;

            minSize = new Vector2(600f, 300f);

            wantsMouseMove = true;
            modifyMode = ModifyMode.CONNECT_ENDED;

            /*
                load graph data from deserialized data.
            */
            ConstructGraphFromDeserializedData(deserialized);
        }
        private void Init()
        {
            this.titleContent = new GUIContent("AssetBundle");
            this.selectedTarget = EditorUserBuildSettings.activeBuildTarget;

            Undo.undoRedoPerformed += () => {
                SaveGraphWithReload();
                Repaint();
            };

            modifyMode = ModifyMode.NONE;
            NodeGUIUtility.NodeEventHandler = HandleNodeEvent;
            ConnectionGUIUtility.ConnectionEventHandler = HandleConnectionEvent;

            InitializeGraph();
            Setup(ActiveBuildTarget);

            if (nodes.Any()) {
                UpdateSpacerRect();
            }
        }
示例#43
0
        public void OnGUI()
        {
            using (new EditorGUILayout.HorizontalScope(GUI.skin.box)) {
                if (GUILayout.Button(reloadButtonTexture, GUILayout.Height(18))) {
                    Setup();
                }

                if (GUILayout.Button("Build (active build target is " + EditorUserBuildSettings.activeBuildTarget + ")", GUILayout.Height(18))) {
                    Run();
                }
            }

            /*
                scroll view.
            */
            // var scaledScrollPos = Node.ScaleEffect(scrollPos);
            scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
            // scrollPos = scrollPos + (movedScrollPos - scaledScrollPos);
            {

                // draw node window x N.
                {
                    BeginWindows();

                    nodes.ForEach(node => node.DrawNode());

                    EndWindows();
                }

                // draw connection input point marks.
                foreach (var node in nodes) {
                    node.DrawConnectionInputPointMark(currentEventSource, modifyMode == ModifyMode.CONNECT_STARTED);
                }

                // draw connections.
                foreach (var con in connections) {
                    if (connectionThroughputs.ContainsKey(con.connectionId)) {
                        var throughputListDict = connectionThroughputs[con.connectionId];
                        con.DrawConnection(nodes, throughputListDict);
                    } else {
                        con.DrawConnection(nodes, new Dictionary<string, List<ThroughputAsset>>());
                    }
                }

                // draw connection output point marks.
                foreach (var node in nodes) {
                    node.DrawConnectionOutputPointMark(currentEventSource, modifyMode == ModifyMode.CONNECT_STARTED, Event.current);
                }

                /*
                    draw connecting line if modifing connection.
                */
                switch (modifyMode) {
                    case ModifyMode.CONNECT_STARTED: {
                        // from start node to mouse.
                        DrawStraightLineFromCurrentEventSourcePointTo(Event.current.mousePosition, currentEventSource);

                        break;
                    }
                    case ModifyMode.CONNECT_ENDED: {
                        // do nothing
                        break;
                    }
                    case ModifyMode.SELECTION_STARTED: {
                        GUI.DrawTexture(new Rect(selection.x, selection.y, Event.current.mousePosition.x - selection.x, Event.current.mousePosition.y - selection.y), selectionTex);
                        break;
                    }
                }

                /*
                    mouse drag event handling.
                */
                switch (Event.current.type) {

                    // draw line while dragging.
                    case EventType.MouseDrag: {
                        switch (modifyMode) {
                            case ModifyMode.CONNECT_ENDED: {
                                switch (Event.current.button) {
                                    case 0:{// left click
                                        if (Event.current.command) {
                                            scalePoint = new ScalePoint(Event.current.mousePosition, Node.scaleFactor, 0);
                                            modifyMode = ModifyMode.SCALING_STARTED;
                                            break;
                                        }

                                        selection = new AssetBundleGraphSelection(Event.current.mousePosition);
                                        modifyMode = ModifyMode.SELECTION_STARTED;
                                        break;
                                    }
                                    case 2:{// middle click.
                                        scalePoint = new ScalePoint(Event.current.mousePosition, Node.scaleFactor, 0);
                                        modifyMode = ModifyMode.SCALING_STARTED;
                                        break;
                                    }
                                }
                                break;
                            }
                            case ModifyMode.SELECTION_STARTED: {
                                // do nothing.
                                break;
                            }
                            case ModifyMode.SCALING_STARTED: {
                                var baseDistance = (int)Vector2.Distance(Event.current.mousePosition, new Vector2(scalePoint.x, scalePoint.y));
                                var distance = baseDistance / Node.SCALE_WIDTH;
                                var direction = (0 < Event.current.mousePosition.y - scalePoint.y);

                                if (!direction) distance = -distance;

                                // var before = Node.scaleFactor;
                                Node.scaleFactor = scalePoint.startScale + (distance * Node.SCALE_RATIO);

                                if (Node.scaleFactor < Node.SCALE_MIN) Node.scaleFactor = Node.SCALE_MIN;
                                if (Node.SCALE_MAX < Node.scaleFactor) Node.scaleFactor = Node.SCALE_MAX;
                                break;
                            }
                        }

                        HandleUtility.Repaint();
                        Event.current.Use();
                        break;
                    }
                }

                /*
                    mouse up event handling.
                    use rawType for detect for detectiong mouse-up which raises outside of window.
                */
                switch (Event.current.rawType) {
                    case EventType.MouseUp: {
                        switch (modifyMode) {
                            /*
                                select contained nodes & connections.
                            */
                            case ModifyMode.SELECTION_STARTED: {
                                var x = 0f;
                                var y = 0f;
                                var width = 0f;
                                var height = 0f;

                                if (Event.current.mousePosition.x < selection.x) {
                                    x = Event.current.mousePosition.x;
                                    width = selection.x - Event.current.mousePosition.x;
                                }
                                if (selection.x < Event.current.mousePosition.x) {
                                    x = selection.x;
                                    width = Event.current.mousePosition.x - selection.x;
                                }

                                if (Event.current.mousePosition.y < selection.y) {
                                    y = Event.current.mousePosition.y;
                                    height = selection.y - Event.current.mousePosition.y;
                                }
                                if (selection.y < Event.current.mousePosition.y) {
                                    y = selection.y;
                                    height = Event.current.mousePosition.y - selection.y;
                                }

                                var activeObjectIds = new List<string>();

                                var selectedRect = new Rect(x, y, width, height);

                                foreach (var node in nodes) {
                                    var nodeRect = new Rect(node.GetRect());
                                    nodeRect.x = nodeRect.x * Node.scaleFactor;
                                    nodeRect.y = nodeRect.y * Node.scaleFactor;
                                    nodeRect.width = nodeRect.width * Node.scaleFactor;
                                    nodeRect.height = nodeRect.height * Node.scaleFactor;
                                    // get containd nodes,
                                    if (nodeRect.Overlaps(selectedRect)) {
                                        activeObjectIds.Add(node.nodeId);
                                    }
                                }

                                foreach (var connection in connections) {
                                    // get contained connection badge.
                                    if (connection.GetRect().Overlaps(selectedRect)) {
                                        activeObjectIds.Add(connection.connectionId);
                                    }
                                }

                                if (Event.current.shift) {
                                    // add current active object ids to new list.
                                    foreach (var alreadySelectedObjectId in activeObject.idPosDict.ReadonlyDict().Keys) {
                                        if (!activeObjectIds.Contains(alreadySelectedObjectId)) activeObjectIds.Add(alreadySelectedObjectId);
                                    }
                                } else {
                                    // do nothing, means cancel selections if nodes are not contained by selection.
                                }

                                Undo.RecordObject(this, "Select Objects");

                                activeObject = RenewActiveObject(activeObjectIds);
                                UpdateActivationOfObjects(activeObject);

                                selection = new AssetBundleGraphSelection(Vector2.zero);
                                modifyMode = ModifyMode.CONNECT_ENDED;

                                HandleUtility.Repaint();
                                Event.current.Use();
                                break;
                            }

                            case ModifyMode.SCALING_STARTED: {
                                modifyMode = ModifyMode.CONNECT_ENDED;
                                break;
                            }
                        }
                        break;
                    }
                }

                // set rect for scroll.
                if (nodes.Any()) {
                    GUILayoutUtility.GetRect(new GUIContent(string.Empty), GUIStyle.none, GUILayout.Width(spacerRectRightBottom.x), GUILayout.Height(spacerRectRightBottom.y));
                }
            }
            EditorGUILayout.EndScrollView();

            /*
                detect
                    dragging some script into window.
                    right click.
                    connection end mouse up.
                    command(Delete, Copy, and more)
            */
            switch (Event.current.type) {
                // detect dragging script then change interface to "(+)" icon.
                case EventType.DragUpdated: {
                    var refs = DragAndDrop.objectReferences;

                    foreach (var refe in refs) {
                        if (refe.GetType() == typeof(UnityEditor.MonoScript)) {
                            var type = ((MonoScript)refe).GetClass();

                            var inherited = IsAcceptableScriptType(type);

                            if (inherited != null) {
                                // at least one asset is script. change interface.
                                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                                break;
                            }
                        }
                    }
                    break;
                }

                // script drop on editor.
                case EventType.DragPerform: {
                    var pathAndRefs = new Dictionary<string, object>();
                    for (var i = 0; i < DragAndDrop.paths.Length; i++) {
                        var path = DragAndDrop.paths[i];
                        var refe = DragAndDrop.objectReferences[i];
                        pathAndRefs[path] = refe;
                    }
                    var shouldSave = false;
                    foreach (var item in pathAndRefs) {
                        var path = item.Key;
                        var refe = (MonoScript)item.Value;
                        if (refe.GetType() == typeof(UnityEditor.MonoScript)) {
                            var type = refe.GetClass();
                            var inherited = IsAcceptableScriptType(type);

                            if (inherited != null) {
                                var dropPos = Event.current.mousePosition;
                                var scriptName = refe.name;
                                var scriptType = scriptName;// name = type.
                                var scriptPath = path;
                                AddNodeFromCode(scriptName, scriptType, scriptPath, inherited, Guid.NewGuid().ToString(), dropPos.x, dropPos.y);
                                shouldSave = true;
                            }
                        }
                    }

                    if (shouldSave) SaveGraphWithReload();
                    break;
                }

                // show context menu
                case EventType.ContextClick: {
                    var rightClickPos = Event.current.mousePosition;
                    var menu = new GenericMenu();
                    foreach (var menuItemStr in AssetBundleGraphSettings.GUI_Menu_Item_TargetGUINodeDict.Keys) {
                        var targetGUINodeNameStr = AssetBundleGraphSettings.GUI_Menu_Item_TargetGUINodeDict[menuItemStr];
                        menu.AddItem(
                            new GUIContent(menuItemStr),
                            false,
                            () => {
                                AddNodeFromGUI(string.Empty, targetGUINodeNameStr, Guid.NewGuid().ToString(), rightClickPos.x, rightClickPos.y);
                                SaveGraphWithReload();
                                Repaint();
                            }
                        );
                    }
                    menu.ShowAsContext();
                    break;
                }

                /*
                    handling mouse up
                         -> drag released -> release modifyMode.
                */
                case EventType.MouseUp: {
                    modifyMode = ModifyMode.CONNECT_ENDED;
                    HandleUtility.Repaint();

                    if (activeObject.idPosDict.ReadonlyDict().Any()) {
                        Undo.RecordObject(this, "Unselect");

                        foreach (var activeObjectId in activeObject.idPosDict.ReadonlyDict().Keys) {
                            // unselect all.
                            foreach (var node in nodes) {
                                if (activeObjectId == node.nodeId) node.SetInactive();
                            }
                            foreach (var connection in connections) {
                                if (activeObjectId == connection.connectionId) connection.SetInactive();
                            }
                        }

                        activeObject = RenewActiveObject(new List<string>());
                    }

                    break;
                }

                /*
                    scale up or down by command & + or command & -.
                */
                case EventType.KeyDown: {
                    if (Event.current.command) {
                        if (Event.current.shift && Event.current.keyCode == KeyCode.Semicolon) {
                            Node.scaleFactor = Node.scaleFactor + 0.1f;
                            if (Node.scaleFactor < Node.SCALE_MIN) Node.scaleFactor = Node.SCALE_MIN;
                            if (Node.SCALE_MAX < Node.scaleFactor) Node.scaleFactor = Node.SCALE_MAX;
                            Event.current.Use();
                            break;
                        }

                        if (Event.current.keyCode == KeyCode.Minus) {
                            Node.scaleFactor = Node.scaleFactor - 0.1f;
                            if (Node.scaleFactor < Node.SCALE_MIN) Node.scaleFactor = Node.SCALE_MIN;
                            if (Node.SCALE_MAX < Node.scaleFactor) Node.scaleFactor = Node.SCALE_MAX;
                            Event.current.Use();
                            break;
                        }
                    }
                    break;
                }

                case EventType.ValidateCommand: {
                    switch (Event.current.commandName) {
                        // Delete active node or connection.
                        case "Delete": {

                            if (!activeObject.idPosDict.ReadonlyDict().Any()) break;
                            Undo.RecordObject(this, "Delete Selection");

                            foreach (var targetId in activeObject.idPosDict.ReadonlyDict().Keys) {
                                DeleteNode(targetId);
                                DeleteConnectionById(targetId);
                            }

                            SaveGraphWithReload();
                            InitializeGraph();

                            activeObject = RenewActiveObject(new List<string>());
                            UpdateActivationOfObjects(activeObject);

                            Event.current.Use();
                            break;
                        }

                        case "Copy": {
                            if (!activeObject.idPosDict.ReadonlyDict().Any()) {
                                break;
                            }

                            Undo.RecordObject(this, "Copy Selection");

                            var targetNodeIds = activeObject.idPosDict.ReadonlyDict().Keys.ToList();
                            var targetNodeJsonRepresentations = JsonRepresentations(targetNodeIds);
                            copyField = new CopyField(targetNodeJsonRepresentations, CopyType.COPYTYPE_COPY);

                            Event.current.Use();
                            break;
                        }

                        case "Cut": {
                            if (!activeObject.idPosDict.ReadonlyDict().Any()) {
                                break;
                            }

                            Undo.RecordObject(this, "Cut Selection");
                            var targetNodeIds = activeObject.idPosDict.ReadonlyDict().Keys.ToList();
                            var targetNodeJsonRepresentations = JsonRepresentations(targetNodeIds);
                            copyField = new CopyField(targetNodeJsonRepresentations, CopyType.COPYTYPE_CUT);

                            foreach (var targetId in activeObject.idPosDict.ReadonlyDict().Keys) {
                                DeleteNode(targetId);
                                DeleteConnectionById(targetId);
                            }

                            SaveGraphWithReload();
                            InitializeGraph();

                            activeObject = RenewActiveObject(new List<string>());
                            UpdateActivationOfObjects(activeObject);

                            Event.current.Use();
                            break;
                        }

                        case "Paste": {
                            var nodeNames = nodes.Select(node => node.name).ToList();
                            var duplicatingData = new List<Node>();

                            if (copyField.datas.Any()) {
                                var pasteType = copyField.type;
                                foreach (var copyFieldData in copyField.datas) {
                                    var nodeJsonDict = Json.Deserialize(copyFieldData) as Dictionary<string, object>;
                                    var pastingNode = NodeFromJsonDict(nodes.Count, nodeJsonDict);
                                    var pastingNodeName = pastingNode.name;

                                    var nameOverlapping = nodeNames.Where(name => name == pastingNodeName).ToList();

              									switch (pasteType) {
              										case CopyType.COPYTYPE_COPY: {
              											if (2 <= nameOverlapping.Count) continue;
              											break;
              										}
              										case CopyType.COPYTYPE_CUT: {
              											if (1 <= nameOverlapping.Count) continue;
              											break;
              										}
              									}

              									duplicatingData.Add(pastingNode);
                                }
                            }

                            if (!duplicatingData.Any()) break;

                            Undo.RecordObject(this, "Paste");
                            foreach (var newNode in duplicatingData) {
                                DuplicateNode(newNode);
                            }

                            SaveGraphWithReload();
                            InitializeGraph();

                            Event.current.Use();
                            break;
                        }

                        case "SelectAll": {
                            Undo.RecordObject(this, "Select All Objects");

                            var nodeIds = nodes.Select(node => node.nodeId).ToList();
                            activeObject = RenewActiveObject(nodeIds);

                            // select all.
                            foreach (var node in nodes) {
                                node.SetActive();
                            }
                            foreach (var connection in connections) {
                                connection.SetActive();
                            }

                            Event.current.Use();
                            break;
                        }

                        default: {
                            break;
                        }
                    }
                    break;
                }
            }
        }