Ejemplo n.º 1
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="da">The DA object can be used to retrieve data from input parameters and
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess da)
        {
            string path = null;

            if (!da.GetData(0, ref path))
            {
                return;
            }

            if (Initialized)
            {
                da.SetDataList(0, WebWindow.InputValues);
                da.SetDataList(1, WebWindow.InputIds);
            }
            else
            {
                //WebWindow = new WebWindow(path);
                //WebWindow.Show();
                LaunchWindow(path);
                Initialized = true;
            }

            GH_Document doc = OnPingDocument();

            doc?.ScheduleSolution(500, ScheduleCallback);
            //this.ExpireSolution(true);
        }
        protected override void AfterSolveInstance()
        {
            //if (!this.on) return;
            GH_Document ghDocument = OnPingDocument();

            ghDocument.ScheduleSolution(1000, new GH_Document.GH_ScheduleDelegate(this.ScheduleCallBack));
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            if (HoloConnect.deviceFinder == null)
            {
                HoloConnect.deviceFinder = new FindServer();
                HoloConnect.deviceFinder.StartScanning();
            }
            // Get inputs.
            string remoteIP = this.defaultIP;

            if (!DA.GetData(0, ref remoteIP))
            {
                return;
            }
            //////////////////////////////////////////////////////
            if (this.connect == null)             // New Connection.
            {
                this.connect = new Connection(remoteIP);
            }
            else if (this.connect.remoteIP != remoteIP)
            {
                // If IP Changed first Disconnect the old one.
                this.connect.Disconnect();
                this.connect = new Connection(remoteIP);
            }

            this.connect.status = this.status;
            if (this.status)
            {
                // Start connections
                bool success = this.connect.Connect();
                if (success)
                {
                    this.connect.TransmitIP();
                }
                string message = (success) ? "Connection established." : "Connection failed, please check your network connection and try again.";
                UniversalDebug(message, (success) ? GH_RuntimeMessageLevel.Remark : GH_RuntimeMessageLevel.Error);
            }
            else
            {
                this.connect.Disconnect();
            }
            //////////////////////////////////////////////////////
            // Output.
            DA.SetData(0, this.connect);
                        #if DEBUG
            DA.SetData(1, this.debugMessages[this.debugMessages.Count - 1]);
                        #endif

            // Expire Solution.
            if ((connect.status) && (connect.PendingMessages))
            {
                GH_Document document = this.OnPingDocument();
                if (document != null)
                {
                    document.ScheduleSolution(HoloConnect.expireDelay, ScheduleCallback);
                }
            }
        }
Ejemplo n.º 4
0
 /// <summary>
 /// This procedure contains the user code. Input parameters are provided as regular arguments,
 /// Output parameters as ref arguments. You don't have to assign output parameters,
 /// they will have a default value.
 /// </summary>
 private void RunScript(bool reset, string path, string controlComponentName, ref object A)
 {
     if (reset)
     {
         _controlComponentName = controlComponentName;
         _path = path;
         GrasshopperDocument.ScheduleSolution(5, SolutionCallback);
     }
 }
        protected override void AfterSolveInstance()
        {
            if (!this.run)
            {
                return;
            }
            GH_Document ghDocument = OnPingDocument();

            ghDocument.ScheduleSolution((int)speed, new GH_Document.GH_ScheduleDelegate(this.ScheduleCallBack));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Get inputs.
            List <RobotData> inputRobots = new List <RobotData>();
            Connection       connect     = null;

            if (!DA.GetDataList(0, inputRobots))
            {
                return;
            }
            if (!DA.GetData <Connection>(1, ref connect))
            {
                return;
            }
            //////////////////////////////////////////////////////
            // Process data.
            if (connect.status)
            {
                // If connection open start acting.

                // Send robot data.
                byte[] bytes = EncodeUtilities.EncodeData("HOLOBOTS", inputRobots.ToArray(), out string currentMessage);
                if (this.flagForce || (this.lastMessage != currentMessage))
                {
                    connect.tcpSender.QueueUpData(bytes);
                    //bool success = connect.tcpSender.flagSuccess;
                    //string message = connect.tcpSender.debugMessages[connect.tcpSender.debugMessages.Count-1];
                    //if (success)
                    //	this.lastMessage = currentMessage;
                    //UniversalDebug(message, (success) ? GH_RuntimeMessageLevel.Remark : GH_RuntimeMessageLevel.Error);
                }
            }
            else
            {
                this.lastMessage = string.Empty;
                UniversalDebug("Set 'Send' on true in HoloFab 'HoloConnect'.", GH_RuntimeMessageLevel.Warning);
            }
            //////////////////////////////////////////////////////
            // Output.
                        #if DEBUG
            DA.SetData(0, RobotStreaming.debugMessages[RobotStreaming.debugMessages.Count - 1]);
                        #endif

            // Expire Solution.
            if ((connect.status) && (connect.PendingMessages))
            {
                GH_Document document = this.OnPingDocument();
                if (document != null)
                {
                    document.ScheduleSolution(RobotStreaming.expireDelay, ScheduleCallback);
                }
            }
        }
Ejemplo n.º 7
0
        protected override void SolveInstance(IGH_DataAccess da)
        {
            // get input from gh component inputs
            string path  = null;
            bool   show  = false;
            string title = null;

            // get input
            if (!da.GetData(0, ref path))
            {
                return;
            }
            if (!da.GetData <bool>(1, ref show))
            {
                return;
            }
            da.GetData(2, ref title);
            da.GetData(3, ref _height);
            da.GetData(4, ref _width);


            if (!show)
            {
                return;
            }

            if (Initialized)
            {
                // if there's a new path, navigate to it
                if (_oldPath != path)
                {
                    _webWindow.Navigate(path);
                    _oldPath = path;
                }

                da.SetDataList(0, _webWindow.InputValues);
                da.SetDataList(1, _webWindow.InputIds);
                da.SetDataList(2, _webWindow.InputNames);
                da.SetDataList(3, _webWindow.InputTypes);
                da.SetData(4, _webWindow);
            }
            else
            {
                LaunchWindow(path, title);
                Initialized = true;
                _oldPath    = path;
            }

            GH_Document doc = OnPingDocument();

            doc?.ScheduleSolution(500, document => ExpireSolution(false));
        }
        protected override void AfterSolveInstance()
        {
            if (!this.run || reset || staticSolver)
            {
                return;
            }
            GH_Document gH_Document = base.OnPingDocument();

            if (gH_Document == null)
            {
                return;
            }
            GH_Document.GH_ScheduleDelegate gH_ScheduleDelegate = new GH_Document.GH_ScheduleDelegate(this.ScheduleCallback);
            gH_Document.ScheduleSolution(1, gH_ScheduleDelegate);
        }
Ejemplo n.º 9
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            bool _reset = false;

            DA.GetData <bool>("Reset", ref _reset);
            this.iAgentSystems = new List <AgentSystemBase>();
            DA.GetDataList <AgentSystemBase>("Agent Systems", this.iAgentSystems);

            int _timestep = 2000;

            DA.GetData <int>("Timestep", ref _timestep);
            TimeStep = _timestep;


            if (_reset || this.solver == null)
            {
                foreach (AgentSystemBase iAgentSystem in this.iAgentSystems)
                {
                    iAgentSystem.Reset();
                }
                this.solver = new BuilderSolver(this.iAgentSystems);
            }
            else
            {
                this.solver.AgentSystems = this.iAgentSystems;
                bool _execute = false;
                DA.GetData <bool>("Execute", ref _execute);
                if (_execute)
                {
                    this.solver.ExecuteSingleStep();
                    GH_Document doc = OnPingDocument();
                    if (doc != null)
                    {
                        doc.ScheduleSolution(TimeStep, ScheduleCallback);
                    }
                }
            }

            DA.SetDataList("Display Geometries", (IEnumerable)this.solver.GetDisplayGeometries());
            DA.SetDataList("All Agent Systems", (IEnumerable)this.solver.AgentSystems);
            DA.SetData("Iteration Count", (object)this.solver.IterationCount);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            bool  run   = false;
            Model input = null;

            MeshUtil.GmshParams gmshParams = null;

            DA.GetData(0, ref run);
            DA.GetData(1, ref input);
            DA.GetData(2, ref gmshParams);

            RhinoDoc    doc = RhinoDoc.ActiveDoc;
            GH_Document GrasshopperDocument = this.OnPingDocument();

            if (undoGH)
            {
                Rhino.RhinoApp.RunScript("_undo", false);
                undoGH = false;
                done   = true;
            }

            if (run && !done)
            {
                model = input.Clone() as Model;
                model.BuildGmshFile(doc, gmshParams);

                undoGH = true;
                GrasshopperDocument.ScheduleSolution(0, ScheduleCallback);
            }

            else if (!run)
            {
                done = false;
            }

            DA.SetData(0, model);
            if (model != null)
            {
                DA.SetData(1, model.GetModelFilePath(GuanacoUtil.FileType.geo));
            }
        }
Ejemplo n.º 11
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string cmdOutput = "Not processed";
            //string paramMod = "";
            GH_ObjectWrapper _abstractSocket = new GH_ObjectWrapper();

            if (_clientSocket == null)
            {
                if (!DA.GetData(0, ref _abstractSocket))
                {
                    return;
                }
                _abstractSocket.CastTo(ref _clientSocket);
            }
            else if (_clientSocket != null && !DA.GetData(0, ref _abstractSocket))
            {
                try
                {
                    _clientSocket = null;
                    return;
                }
                catch
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Waiting For Connection...");
                    return;
                }
            }

            IPEndPoint remoteIpEndPoint = _clientSocket.RemoteEndPoint as IPEndPoint;

            cmdOutput = callFromCmd(remoteIpEndPoint.ToString());
            DA.SetData(0, cmdOutput);

            GH_Document doc = OnPingDocument();

            if (doc != null)
            {
                doc.ScheduleSolution(1000, ScheduleCallback);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            bool  run   = false;
            Model input = null;

            MeshUtil.GmshParams gmshParams = null;
            bool reducedIntegration        = false;

            DA.GetData(0, ref run);
            DA.GetData(1, ref input);
            DA.GetData(2, ref gmshParams);
            DA.GetData(3, ref reducedIntegration);

            RhinoDoc    doc = RhinoDoc.ActiveDoc;
            GH_Document GrasshopperDocument = this.OnPingDocument();

            if (undoGH)
            {
                Rhino.RhinoApp.RunScript("_undo", false);
                undoGH = false;
                done   = true;
            }

            if (run && !done)
            {
                model = input.Clone() as Model;
                model.MeshModel(doc, gmshParams, GHUtil.GmshPath(GrasshopperDocument), reducedIntegration);

                undoGH = true;
                GrasshopperDocument.ScheduleSolution(0, ScheduleCallback);
            }

            else if (!run)
            {
                done = false;
            }

            DA.SetData(0, model);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Fields
            GH_ObjectWrapper abstractSocket = new GH_ObjectWrapper();
            bool             triggerRead    = false;
            int refreshRate = 0;

            E6POS  currentPos    = new E6POS();
            E6AXIS currentAngles = new E6AXIS();

            bool getSocket = DA.GetData(0, ref abstractSocket);

            //Check input
            if (_clientSocket == null)
            {
                if (!getSocket)
                {
                    return;
                }
                abstractSocket.CastTo(ref _clientSocket);
            }
            else if (_clientSocket != null && !getSocket)
            {
                try
                {
                    _clientSocket = null;
                    return;
                }
                catch
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Waiting For Connection...");
                    return;
                }
            }
            if (!DA.GetData(1, ref triggerRead))
            {
                return;
            }
            if (!DA.GetData(2, ref refreshRate))
            {
                return;
            }
            if (refreshRate < 15)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                  "WARNING: Refresh rate too low, this can cause performance issues for grasshopper. The maximum robot read speed is 5ms (for all messages)");
            }
            if (refreshRate < 5)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  "Refresh Rate too low. Absolute maximum speed is 5ms. This is not recommended. Try to stay in the region of ~20-70 ms");
                return;
            }

            //If trigger is pressed, read data and output.
            if (triggerRead)
            {
                string response = Util.ReadVariable(ref _clientSocket, "$POS_ACT", this);
                currentPos.DeserializeE6POS(response);
                CurrentPos = currentPos;

                string response2 = Util.ReadVariable(ref _clientSocket, "$AXIS_ACT", this);
                currentAngles.DeserializeE6AXIS(response2);
                CurrentAngles = currentAngles;
            }

            if (!CurrentAngles.IsNull() && !CurrentPos.IsNull())
            {
                DA.SetDataList(0, CurrentAngles.GetAxisValues());
                DA.SetData(1, new GH_Plane(CurrentPos.GetPlane()));
                DA.SetDataList(2, new List <double> {
                    CurrentPos.X, CurrentPos.Y, CurrentPos.Z
                });
                DA.SetDataList(3, new List <double> {
                    CurrentPos.A, CurrentPos.B, CurrentPos.C
                });
                DA.SetData(4, CurrentPos.SerializedString);
                DA.SetData(5, CurrentAngles.SerializedString);
            }

            if (this.Params.Input[1].Sources[0].GetType() == typeof(GH_BooleanToggle) && triggerRead)
            {
                GH_Document doc = OnPingDocument();
                doc?.ScheduleSolution(refreshRate, ScheduleCallback);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Get inputs.
            List <RobotData>         inputRobots     = new List <RobotData>();
            GH_Structure <GH_Number> inputAxisAngles = new GH_Structure <GH_Number> {
            };
            Connection connect = null;

            if (!DA.GetDataList <RobotData>(0, inputRobots))
            {
                return;
            }
            if (!DA.GetDataTree(1, out inputAxisAngles))
            {
                return;
            }
            if (!DA.GetData <Connection>(2, ref connect))
            {
                return;
            }
            // Check inputs.
            if ((inputAxisAngles.Paths.Count > 1) && (inputAxisAngles.Paths.Count != inputRobots.Count))
            {
                UniversalDebug("The number of Branches of Axis Angles should be one or equal to the number of HoloBot objects.",
                               GH_RuntimeMessageLevel.Error);
                return;
            }
            // if (inputAxisAngles.Count != 6) {
            //  Positioner.debugMessages.Add("Component: Controller: The number of Axis should be equal to the number of Robot Joints.");
            //  return;
            // }
            //////////////////////////////////////////////////////
            // Process data.
            if (connect.status)
            {
                // If connection open start acting.
                UniversalDebug("Robots Found: " + inputRobots.Count + ", Axis Count, " + inputAxisAngles.Paths.Count);
                List <RobotControllerData> robotControllers = new List <RobotControllerData>();
                for (int i = 0; i < inputRobots.Count; i++)
                {
                    List <double> currentRobotAxisValues = new List <double> {
                    };
                    int index = (inputAxisAngles.Paths.Count > 1) ? i : 0;
                    Console.WriteLine(index);
                    double currentValue;
                    for (int j = 0; j < inputAxisAngles[index].Count; j++)
                    {
                        currentValue = (double)inputAxisAngles[index][j].Value;
                        currentRobotAxisValues.Add(currentValue * (180.0 / Math.PI));
                    }
                    robotControllers.Add(new RobotControllerData(inputRobots[i].robotID, currentRobotAxisValues));
                }

                // Send robot controller data.
                byte[] bytes = EncodeUtilities.EncodeData("CONTROLLER", robotControllers, out string currentMessage);
                if (this.flagForce || (this.lastMessage != currentMessage))
                {
                    connect.udpSender.QueueUpData(bytes);
                    //bool success = connect.udpSender.success;
                    //string message = connect.udpSender.debugMessages[connect.udpSender.debugMessages.Count-1];
                    //if (success)
                    //	this.lastMessage = currentMessage;
                    //UniversalDebug(message, (success) ? GH_RuntimeMessageLevel.Remark : GH_RuntimeMessageLevel.Error);
                }
            }
            else
            {
                this.lastMessage = string.Empty;
                UniversalDebug("Set 'Send' on true in HoloFab 'HoloConnect'.", GH_RuntimeMessageLevel.Warning);
            }
            //////////////////////////////////////////////////////
            // Output.
                        #if DEBUG
            DA.SetData(0, this.debugMessages[this.debugMessages.Count - 1]);
                        #endif

            // Expire Solution.
            if ((connect.status) && (connect.PendingMessages))
            {
                GH_Document document = this.OnPingDocument();
                if (document != null)
                {
                    document.ScheduleSolution(Controller.expireDelay, ScheduleCallback);
                }
            }
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Get inputs.
            Connection connect = null;

            if (!DA.GetData(0, ref connect))
            {
                return;
            }
            //////////////////////////////////////////////////////
            // Process data.
            if (connect.status)
            {
                // If connection open start acting.
                // Prepare to receive UI data.
                try {
                    if (connect.udpReceiver.dataMessages.Count > 0)
                    {
                        UIReceiver.currentInput = connect.udpReceiver.dataMessages.Peek();
                        UIReceiver.currentInput = EncodeUtilities.StripSplitter(UIReceiver.currentInput);
                        if (UIReceiver.lastInputs != UIReceiver.currentInput)
                        {
                            UIReceiver.lastInputs = UIReceiver.currentInput;
                            UniversalDebug("New Message without Message Splitter removed: " + currentInput);
                            string[] messageComponents = UIReceiver.currentInput.Split(new string[] { EncodeUtilities.headerSplitter }, 2, StringSplitOptions.RemoveEmptyEntries);
                            if (messageComponents.Length > 1)
                            {
                                string header = messageComponents[0], content = messageComponents[1];
                                UniversalDebug("Header: " + header + ", content: " + content);
                                if (header == "UIDATA")
                                {
                                    // If any new data received - process it.
                                    UIData data = JsonConvert.DeserializeObject <UIData>(content);
                                    UIReceiver.currentBools  = new List <bool> (data.bools);
                                    UIReceiver.currentInts   = new List <int> (data.ints);
                                    UIReceiver.currentFloats = new List <float> (data.floats);
                                    UniversalDebug("Data Received!");
                                    connect.udpReceiver.dataMessages.Dequeue();                                     // Actually remove from the queue since it has been processed.
                                }
                                // else
                                //	UniversalDebug("Header Not Recognized!", GH_RuntimeMessageLevel.Warning);
                            }
                            else
                            {
                                UniversalDebug("Data not Received!", GH_RuntimeMessageLevel.Warning);
                            }
                        }
                        else
                        {
                            UniversalDebug("Improper Message!", GH_RuntimeMessageLevel.Warning);
                        }
                    }
                    else
                    {
                        UniversalDebug("No data received.");
                    }
                } catch {
                    UniversalDebug("Error Processing Data.", GH_RuntimeMessageLevel.Error);
                }
            }
            else
            {
                // If connection disabled - reset memoty.
                UIReceiver.lastInputs    = string.Empty;
                UIReceiver.currentBools  = new List <bool>();
                UIReceiver.currentInts   = new List <int>();
                UIReceiver.currentFloats = new List <float>();
                UniversalDebug("Set 'Send' on true in HoloFab 'HoloConnect'", GH_RuntimeMessageLevel.Warning);
            }
            //////////////////////////////////////////////////////
            // Output.
            DA.SetDataList(0, UIReceiver.currentBools);
            DA.SetDataList(1, UIReceiver.currentInts);
            DA.SetDataList(2, UIReceiver.currentFloats);
                        #if DEBUG
            DA.SetData(3, this.debugMessages[this.debugMessages.Count - 1]);
                        #endif

            // Expire Solution.
            if (connect.status)
            {
                GH_Document document = this.OnPingDocument();
                if (document != null)
                {
                    document.ScheduleSolution(UIReceiver.expireDelay, ScheduleCallback);
                }
            }
        }
Ejemplo n.º 16
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Plane            _targetPlane    = new Plane();
            Plane            _worldPlane     = new Plane(new Point3d(0, 0, 0), new Vector3d(0, 0, 1), new Vector3d(0, 1, 0));
            GH_ObjectWrapper _abstractSocket = new GH_ObjectWrapper();
            string           _variableRead   = "NA";
            string           _variableWrite  = "NA";
            bool             _triggerRead    = false;
            bool             _triggerWrite   = false;

            if (_clientSocket == null)
            {
                if (!DA.GetData(0, ref _abstractSocket))
                {
                    return;
                }
                _abstractSocket.CastTo(ref _clientSocket);
            }

            if (!DA.GetData(1, ref _targetPlane))
            {
                return;
            }
            if (!DA.GetData(2, ref _worldPlane))
            {
                return;
            }
            if (!DA.GetData(3, ref _variableRead))
            {
                return;
            }
            if (!DA.GetData(4, ref _variableWrite))
            {
                return;
            }
            if (!DA.GetData(5, ref _triggerRead))
            {
                return;
            }
            if (!DA.GetData(6, ref _triggerWrite))
            {
                return;
            }


            if (_triggerRead)
            {
                string response = Util.ReadVariable(ref _clientSocket, _variableRead, this);
                DA.SetData(0, response);
            }

            if (_triggerWrite)
            {
                string targetE6 = Util.calculateTargetE6Pos(_targetPlane, _worldPlane);
                string response = Util.WriteVariable(ref _clientSocket, _variableWrite, "hi", this);
                DA.SetData(1, response);
            }

            GH_Document doc = OnPingDocument();

            if (doc != null)
            {
                // Schedule loop for every 20ms
                doc.ScheduleSolution(20, ScheduleCallback);
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //CheckType();
            // Get inputs.
            string       message;
            List <Mesh>  inputMeshes = new List <Mesh>();
            List <Color> inputColor  = new List <Color>();
            Connection   connect     = null;

            if (!DA.GetDataList(0, inputMeshes))
            {
                return;
            }
            DA.GetDataList(1, inputColor);
            if (!DA.GetData <Connection>(2, ref connect))
            {
                return;
            }
            // Check inputs.
            if ((inputColor.Count > 1) && (inputColor.Count != inputMeshes.Count))
            {
                message = (inputColor.Count > inputMeshes.Count) ?
                          "The number of Colors does not match the number of Mesh objects. Extra colors will be ignored." :
                          "The number of Colors does not match the number of Mesh objects. The last color will be repeated.";
                UniversalDebug(message, GH_RuntimeMessageLevel.Warning);
            }
            ////////////////////////////////////////////////////////////////////

            // If connection open start acting.
            if (connect.status)
            {
                // Encode mesh data.
                List <MeshData> inputMeshData = new List <MeshData> {
                };
                for (int i = 0; i < inputMeshes.Count; i++)
                {
                    Color currentColor = inputColor[Math.Min(i, inputColor.Count)];
                    inputMeshData.Add(MeshUtilities.EncodeMesh(inputMeshes[i], currentColor));
                }
                // Send mesh data.
                byte[] bytes = EncodeUtilities.EncodeData("MESHSTREAMING", inputMeshData, out string currentMessage);
                if (this.flagForce || (this.lastMessage != currentMessage))
                {
                    //bool success = false;
                    if (this.sourceType == SourceType.TCP)
                    {
                        connect.tcpSender.QueueUpData(bytes);
                        //success = connect.tcpSender.flagSuccess;
                        //message = connect.tcpSender.debugMessages[connect.tcpSender.debugMessages.Count-1];
                    }
                    else
                    {
                        connect.udpSender.QueueUpData(bytes);
                        //success = connect.udpSender.flagSuccess;
                        //message = connect.udpSender.debugMessages[connect.udpSender.debugMessages.Count-1];
                    }
                    //if (success)
                    //	this.lastMessage = currentMessage;
                    //UniversalDebug(message, (success) ? GH_RuntimeMessageLevel.Remark : GH_RuntimeMessageLevel.Error);
                }
            }
            else
            {
                this.lastMessage = string.Empty;
                UniversalDebug("Set 'Send' on true in HoloFab 'HoloConnect'", GH_RuntimeMessageLevel.Warning);
            }

            // Output.
                        #if DEBUG
            DA.SetData(0, this.debugMessages[this.debugMessages.Count - 1]);
                        #endif

            // Expire Solution.
            if ((connect.status) && (connect.PendingMessages))
            {
                GH_Document document = this.OnPingDocument();
                if (document != null)
                {
                    document.ScheduleSolution(MeshStreaming.expireDelay, ScheduleCallback);
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Fields
            GH_ObjectWrapper abstractSocket = new GH_ObjectWrapper();
            string           varRead        = "";
            bool             triggerRead    = false;
            int refreshRate = 0;

            bool getSocket = DA.GetData(0, ref abstractSocket);

            //Check input
            if (_clientSocket == null)
            {
                if (!getSocket)
                {
                    return;
                }
                abstractSocket.CastTo(ref _clientSocket);
            }
            else if (_clientSocket != null && !getSocket)
            {
                try
                {
                    _clientSocket = null;
                    return;
                }
                catch
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Waiting For Connection...");
                    return;
                }
            }
            if (!DA.GetData(1, ref varRead))
            {
                return;
            }
            if (!DA.GetData(2, ref triggerRead))
            {
                return;
            }
            if (!DA.GetData(3, ref refreshRate))
            {
                return;
            }

            if (refreshRate < 15)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                  "WARNING: Refresh rate too low, this can cause performance issues for grasshopper. The maximum robot read speed is 5ms (for all messages)");
            }
            if (refreshRate < 5)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  "Refresh Rate too low. Absolute maximum speed is 5ms. This is not recommended. Try more in the region of ~20-70 ms");
                return;
            }

            //If trigger is pressed, read data and output.
            if (triggerRead)
            {
                string response = Util.ReadVariable(ref _clientSocket, varRead, this);
                DA.SetData(0, response);
                if (this.Params.Input[2].Sources[0].GetType() == typeof(GH_BooleanToggle))
                {
                    GH_Document doc = OnPingDocument();
                    doc?.ScheduleSolution(refreshRate, ScheduleCallback);
                }
            }
        }
Ejemplo n.º 19
0
        static public void SetValueList(GH_Document doc, GH_Component comp, int InputIndex, List <KeyValuePair <string, string> > valuePairs, string name)
        {
            if (valuePairs.Count == 0)
            {
                return;
            }

            GH_DocumentIO docIO = new GH_DocumentIO();

            docIO.Document = new GH_Document();

            if (docIO.Document == null)
            {
                return;
            }
            doc.MergeDocument(docIO.Document);

            docIO.Document.SelectAll();
            docIO.Document.ExpireSolution();
            docIO.Document.MutateAllIds();
            IEnumerable <IGH_DocumentObject> objs = docIO.Document.Objects;

            doc.DeselectAll();
            doc.UndoUtil.RecordAddObjectEvent("Create Accent List", objs);
            doc.MergeDocument(docIO.Document);

            doc.ScheduleSolution(10, chanegValuelist);

            void chanegValuelist(GH_Document document)
            {
                IList <IGH_Param> sources = comp.Params.Input[InputIndex].Sources;
                int inputs = sources.Count;

                // If nothing has been conected create a new component
                if (inputs == 0)
                {
                    //instantiate  new value list and clear it
                    GH_ValueList vl = new GH_ValueList();
                    vl.ListItems.Clear();
                    vl.NickName = name;
                    vl.Name     = name;

                    //Create values for list and populate it
                    for (int i = 0; i < valuePairs.Count; ++i)
                    {
                        var item = new GH_ValueListItem(valuePairs[i].Key, valuePairs[i].Value);
                        vl.ListItems.Add(item);
                    }

                    //Add value list to the document
                    document.AddObject(vl, false, 1);

                    //get the pivot of the "accent" param
                    System.Drawing.PointF currPivot = comp.Params.Input[InputIndex].Attributes.Pivot;
                    //set the pivot of the new object
                    vl.Attributes.Pivot = new System.Drawing.PointF(currPivot.X - 210, currPivot.Y - 11);

                    // Connect to input
                    comp.Params.Input[InputIndex].AddSource(vl);
                }

                // If inputs exist replace the existing ones
                else
                {
                    for (int i = 0; i < inputs; ++i)
                    {
                        if (sources[i].Name == "Value List" | sources[i].Name == name)
                        {
                            //instantiate  new value list and clear it
                            GH_ValueList vl = new GH_ValueList();
                            vl.ListItems.Clear();
                            vl.NickName = name;
                            vl.Name     = name;

                            //Create values for list and populate it
                            for (int j = 0; j < valuePairs.Count; ++j)
                            {
                                var item = new GH_ValueListItem(valuePairs[j].Key, valuePairs[j].Value);
                                vl.ListItems.Add(item);
                            }

                            document.AddObject(vl, false, 1);
                            //set the pivot of the new object
                            vl.Attributes.Pivot = sources[i].Attributes.Pivot;

                            var currentSource = sources[i];
                            comp.Params.Input[InputIndex].RemoveSource(sources[i]);

                            currentSource.IsolateObject();
                            document.RemoveObject(currentSource, false);

                            //Connect new vl
                            comp.Params.Input[InputIndex].AddSource(vl);
                        }
                        else
                        {
                            //Do nothing if it dosent mach any of the above
                        }
                    }
                }
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Fields
            GH_ObjectWrapper abstractSocket = new GH_ObjectWrapper();
            string           varWrite       = "";
            string           varData        = "";
            bool             run            = false;
            int refreshRate = 0;

            //Check input
            if (_clientSocket == null)
            {
                if (!DA.GetData(0, ref abstractSocket))
                {
                    return;
                }
                abstractSocket.CastTo(ref _clientSocket);
            }
            else if (_clientSocket != null && !DA.GetData(0, ref abstractSocket))
            {
                try
                {
                    _clientSocket = null;
                    return;
                }
                catch
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Waiting For Connection...");
                    return;
                }
            }
            if (!DA.GetData(1, ref varWrite))
            {
                return;
            }
            if (!DA.GetData(2, ref varData))
            {
                return;
            }
            if (!DA.GetData(3, ref run))
            {
                return;
            }
            if (!DA.GetData(4, ref refreshRate))
            {
                return;
            }

            if (Encoding.ASCII.GetBytes(varData).Length > 255)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "MessageSize is too big, messages can only contain a maximum of 255 bytes. Yours is: " + Encoding.ASCII.GetBytes(varData).Length);
            }

            if (refreshRate < 15)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                  "WARNING: Refresh rate too low, this can cause performance issues for grasshopper. The maximum robot read speed is 5ms (for all messages)");
            }
            if (refreshRate < 5)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  "Refresh Rate too low. Absolute maximum speed is 5ms. This is not recommended. Try more in the region of ~20-70 ms");
                return;
            }


            if (run)
            {
                string response = Util.WriteVariable(ref _clientSocket, varWrite, varData, this);
                _oResponse = response;

                if (this.Params.Input[3].Sources[0].GetType() == typeof(GH_BooleanToggle))
                {
                    GH_Document doc = OnPingDocument();
                    doc?.ScheduleSolution(refreshRate, ScheduleCallback);
                }
            }

            DA.SetData(0, _oResponse);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Fields
            E6AXIS           e6Axis         = new E6AXIS();
            GH_ObjectWrapper abstractSocket = new GH_ObjectWrapper();
            string           writeVariable  = "";
            List <double>    axisValues     = new List <double>();
            bool             run            = false;
            int refreshRate = 0;

            //Check input
            if (_clientSocket == null)
            {
                if (!DA.GetData(0, ref abstractSocket))
                {
                    return;
                }
                abstractSocket.CastTo(ref _clientSocket);
            }
            else if (_clientSocket != null && !DA.GetData(0, ref abstractSocket))
            {
                try
                {
                    _clientSocket = null;
                    return;
                }
                catch
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Waiting For Connection...");
                    return;
                }
            }
            if (!DA.GetData(1, ref writeVariable))
            {
                return;
            }
            if (!DA.GetDataList(2, axisValues))
            {
                return;
            }
            if (axisValues.Count != 6)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Make sure to only give 6 axis values.");
            }
            if (!DA.GetData(3, ref run))
            {
                return;
            }
            if (!DA.GetData(4, ref refreshRate))
            {
                return;
            }
            if (refreshRate < 15)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                  "WARNING: Refresh rate too low, this can cause performance issues for grasshopper. The maximum robot read speed is 5ms (for all messages)");
            }
            if (refreshRate < 5)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  "Refresh Rate too low. Absolute maximum speed is 5ms. This is not recommended. Try more in the region of ~20-70 ms");
                return;
            }

            if (axisValues.Count == 6)
            {
                e6Axis.SerializeE6AXIS(axisValues[0], axisValues[1], axisValues[2], axisValues[3], axisValues[4],
                                       axisValues[5]);
            }

            if (run)
            {
                string response = Util.WriteVariable(ref _clientSocket, writeVariable, e6Axis.SerializedString, this);
                _writtenValues = response;

                if (this.Params.Input[3].Sources[0].GetType() == typeof(GH_BooleanToggle))
                {
                    GH_Document doc = OnPingDocument();
                    doc?.ScheduleSolution(refreshRate, ScheduleCallback);
                }
            }

            DA.SetData(0, _writtenValues);
        }
Ejemplo n.º 22
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            if (mySender == null)
            {
                return;
            }

            if (this.EnableRemoteControl)
            {
                this.Message = "JobQueue: " + JobQueue.Count;
            }

            StreamId = mySender.StreamId;

            DA.SetData(0, Log);
            DA.SetData(1, mySender.StreamId);

            if (!mySender.IsConnected)
            {
                return;
            }

            if (WasSerialised && FirstSendUpdate)
            {
                FirstSendUpdate = false;
                return;
            }

            this.State = "Expired";

            // All flags are good to start an update
            if (!this.EnableRemoteControl && !this.ManualMode)
            {
                UpdateData();
                return;
            }
            //
            else if (!this.EnableRemoteControl && this.ManualMode)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "State is expired, update push is required.");
                return;
            }

            #region RemoteControl

            // Code below deals with the remote control functionality.
            // Proceed at your own risk.
            if (JobQueue.Count == 0)
            {
                SetDefaultState();
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Updated default state for remote control.");
                return;
            }

            // prepare solution and exit
            if (!SolutionPrepared && JobQueue.Count != 0)
            {
                System.Collections.DictionaryEntry t = JobQueue.Cast <DictionaryEntry>().ElementAt(0);
                Document.ScheduleSolution(1, PrepareSolution);
                return;
            }

            // send out solution and exit
            if (SolutionPrepared)
            {
                SolutionPrepared = false;
                var BucketObjects    = GetData();
                var BucketLayers     = GetLayers();
                var convertedObjects = Converter.Serialise(BucketObjects).Select(obj =>
                {
                    if (ObjectCache.ContainsKey(obj.Hash))
                    {
                        return new SpecklePlaceholder()
                        {
                            Hash = obj.Hash, _id = ObjectCache[obj.Hash]._id
                        }
                    }
                    ;
                    return(obj);
                });


                // theoretically this should go through the same flow as in DataSenderElapsed(), ie creating
                // buckets for staggered updates, etc. but we're lazy to untangle that logic for now

                var responseClone  = mySender.StreamCloneAsync(this.StreamId).Result;
                var responseStream = new SpeckleStream();

                responseStream.IsComputedResult = true;

                responseStream.Objects = convertedObjects.ToList();
                responseStream.Layers  = BucketLayers;

                List <SpeckleInput>  speckleInputs  = null;
                List <SpeckleOutput> speckleOutputs = null;
                GetSpeckleParams(ref speckleInputs, ref speckleOutputs);

                responseStream.GlobalMeasures = new { input = speckleInputs, output = speckleOutputs };

                // go unblocking
                var responseCloneUpdate = mySender.StreamUpdateAsync(responseClone.Clone.StreamId, responseStream).ContinueWith(tres =>
                {
                    mySender.SendMessage(CurrentJobClient, new { eventType = "compute-response", streamId = responseClone.Clone.StreamId });
                });


                JobQueue.RemoveAt(0);
                this.Message = "JobQueue: " + JobQueue.Count;

                if (JobQueue.Count != 0)
                {
                    Rhino.RhinoApp.MainApplicationWindow.Invoke(ExpireComponentAction);
                }
            }

            #endregion
        }
Ejemplo n.º 23
0
        /// <summary>
        ///  Event of Nesting Finish, that make the process and paint the nested objects
        /// </summary>
        /// <param name="sender"> object: Support all classes in the .NET Framework class hierachy and provides low-level service to derived classes.</param>
        /// <param name="e"> RhinoNestEventArgs: Class used in events.</param>
        private void nesting_OnNestingFinish(object sender, EventArgs e)
        {
            //For the nested objects
            if (_nesting.NestingResult.NestedObjects != null)
            {
                var listguid = new List <Guid>();
                //creation and cleans for the var
                var objresult       = _nesting.NestingResult.NestedObjects;
                var nestedGeometry2 = new RhinoNestObject[objresult.Count];
                var objtrans        = new Transform[objresult.Count];

                //get the objects
                objresult.Keys.CopyTo(nestedGeometry2, 0);
                objresult.Values.CopyTo(objtrans, 0);

                var curves = new List <Curve>();
                //do the modify to every object (position and rotation) and add to the list of curves
                for (int i = 0; i < objresult.Count; i++)
                {
                    curves.Add(nestedGeometry2[i].ExternalCurve.DuplicateCurve());

                    foreach (var id in nestedGeometry2[i].SubObjectsIds)
                    {
                        listguid.Add(RhinoDoc.ActiveDoc.Objects.Transform(id, objtrans[i], false));
                    }

                    curves[i].Transform(objtrans[i]);

                    listguid.Add(RhinoDoc.ActiveDoc.Objects.AddCurve(curves[i]));
                }
                _mycurves.AddRange(listguid);
                //add every object to a buffer for put on the output
                _buffOut.Add(new List <RhinoNestObject>());
                for (int i = 0; i < objresult.Count; i++)
                {
                    _buffOut[_tryies].Add(new RhinoNestObject(curves[i]));
                }

                //create var for make the report
                var rnProject = new RhinoNestProject(_nesting.NestingResult, _sheets2);
                var objs      = new List <Tuple <RhinoNestObject, Transform, List <Guid> > >();
                for (int i = 0; i < _nesting.NestingResult.NestedObjects.Count; i++)
                {
                    var guids = new List <Guid> {
                        listguid[i]
                    };
                    var tup = new Tuple <RhinoNestObject, Transform, List <Guid> >(nestedGeometry2[i], objtrans[i], guids);
                    objs.Add(tup);
                }

                _sheetsresults.Add(new RhinoNestSheetResult(rnProject, objs));

                //get the bound for print if it isn't the first sheet and print it  if is the first don't print the sheet
                var print = _sheets2.GetBounds();
                _mycurves.Add(RhinoDoc.ActiveDoc.Objects.AddPolyline(print));
                //add trie for the next time
                _tryies++;

                //redraw all
                RhinoDoc.ActiveDoc.Views.Redraw();
            }

            //if there is more object for nest
            if (_nesting.NestingResult.RemainingObjects.Any())
            {
                //get the remaining object and count how many is for nest
                var   send  = _nesting.NestingResult.RemainingObjects;
                Int32 count = 0;
                foreach (var item in send)
                {
                    count = count + item.Parameters.RemainingCopies;
                }

                //if have ramaining object to nest
                if (count > 0 && _buffold != count)
                {
                    _nonest.Clear();

                    _buffold = count;
                    _nonest.AddRange(send);

                    //move the sheet it's being used
                    _sheets2.NextPosition();

                    //renew the nesting
                    _nesting = new RhinoNestNesting(send, _sheets2, _parameters);

                    //delete the actual events
                    _nesting.OnNestingFinish         -= nesting_OnNestingFinish;
                    _nesting.OnNestingProgressChange -= Nesting_OnNestingProgressChange;

                    //create the new events
                    _nesting.OnNestingFinish         += nesting_OnNestingFinish;
                    _nesting.OnNestingProgressChange += Nesting_OnNestingProgressChange;

                    //start nasting again
                    _nesting.StartNesting();
                }
                else
                {
                    // if it's not item to nest then call to shedulesolution for the expire solution
                    _setOutput = true;
                    GH_Document doc = OnPingDocument();
                    if (doc != null)
                    {
                        doc.ScheduleSolution(1, MyCallback);
                    }
                }
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Get inputs.
            List <string>  inputText          = new List <string>();
            List <Point3d> inputTextLocations = new List <Point3d>();
            List <double>  inputTextSize      = new List <double>();
            List <Color>   inputTextColor     = new List <Color>();
            Connection     connect            = null;

            if (!DA.GetDataList(0, inputText))
            {
                return;
            }
            if (!DA.GetDataList(1, inputTextLocations))
            {
                return;
            }
            DA.GetDataList(2, inputTextSize);
            DA.GetDataList(3, inputTextColor);
            if (!DA.GetData <Connection>(4, ref connect))
            {
                return;
            }
            // Check inputs.
            if (inputTextLocations.Count != inputText.Count)
            {
                UniversalDebug("The number of 'tag locations' and 'tag texts' should be equal.",
                               GH_RuntimeMessageLevel.Error);
                return;
            }
            if ((inputTextSize.Count > 1) && (inputTextSize.Count != inputText.Count))
            {
                UniversalDebug("The number of 'tag text sizes' should be one or equal to one or the number of 'tag texts'.",
                               GH_RuntimeMessageLevel.Error);
                return;
            }
            if ((inputTextColor.Count > 1) && (inputTextColor.Count != inputText.Count))
            {
                UniversalDebug("The number of 'tag text colors' should be one or equal to one or the number of 'tag texts'.",
                               GH_RuntimeMessageLevel.Error);
                return;
            }
            //////////////////////////////////////////////////////
            // Process data.
            if (connect.status)
            {
                // If connection open start acting.
                List <string> currentTexts = new List <string>()
                {
                };
                List <float[]> currentTextLocations = new List <float[]>()
                {
                };
                List <float> currentTextSizes = new List <float>()
                {
                };
                List <int[]> currentTextColors = new List <int[]>()
                {
                };
                for (int i = 0; i < inputText.Count; i++)
                {
                    float currentSize  = (float)((inputTextSize.Count > 1) ? inputTextSize[i] : inputTextSize[0]);
                    Color currentColor = (inputTextColor.Count > 1) ? inputTextColor[i] : inputTextColor[0];
                    currentTexts.Add(inputText[i]);
                    currentTextLocations.Add(EncodeUtilities.EncodeLocation(inputTextLocations[i]));
                    currentTextSizes.Add((float)Math.Round(currentSize / 1000.0, 3));
                    currentTextColors.Add(EncodeUtilities.EncodeColor(currentColor));
                }
                TagData tags = new TagData(currentTexts, currentTextLocations, currentTextSizes, currentTextColors);

                // Send tag data.
                byte[] bytes = EncodeUtilities.EncodeData("HOLOTAG", tags, out string currentMessage);
                if (this.flagForce || (this.lastMessage != currentMessage))
                {
                    connect.udpSender.QueueUpData(bytes);
                    //bool success = connect.udpSender.flagSuccess;
                    //string message = connect.udpSender.debugMessages[connect.udpSender.debugMessages.Count-1];
                    //if (success)
                    //	this.lastMessage = currentMessage;
                    //UniversalDebug(message, (success) ? GH_RuntimeMessageLevel.Remark : GH_RuntimeMessageLevel.Error);
                }
            }
            else
            {
                this.lastMessage = string.Empty;
                UniversalDebug("Set 'Send' on true in HoloFab 'HoloConnect'", GH_RuntimeMessageLevel.Warning);
            }
            //////////////////////////////////////////////////////
            // Output.
                        #if DEBUG
            DA.SetData(0, this.debugMessages[this.debugMessages.Count - 1]);
                        #endif

            // Expire Solution.
            if ((connect.status) && (connect.PendingMessages))
            {
                GH_Document document = this.OnPingDocument();
                if (document != null)
                {
                    document.ScheduleSolution(HoloTag.expireDelay, ScheduleCallback);
                }
            }
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Get inputs.
            Connection connect = null;

            if (!DA.GetData(0, ref connect))
            {
                return;
            }
            //////////////////////////////////////////////////////
            // Process data.
            if (connect.status)
            {
                // If connection open start acting.
                if (!UIReceiver.flagProcessed)
                {
                    UIReceiver.flagProcessed = true;
                    // Send local IPAddress for device to communicate back.
                    byte[] bytes = EncodeUtilities.EncodeData("IPADDRESS", NetworkUtilities.LocalIPAddress(), out string currentMessage);
                    connect.udpSender.Send(bytes);
                    bool success = connect.udpSender.success;
                    UniversalDebug("Sent local IP.");
                }

                // Prepare to receive UI data.
                try {
                    if (!connect.udpReceiver.flagDataRead)
                    {
                        connect.udpReceiver.flagDataRead = true;
                        UIReceiver.currentInput          = connect.udpReceiver.dataMessages[connect.udpReceiver.dataMessages.Count - 1];
                        if (UIReceiver.lastInputs != currentInput)
                        {
                            currentInput          = EncodeUtilities.StripSplitter(currentInput);
                            UIReceiver.lastInputs = currentInput;
                            UniversalDebug("New Message without Message Splitter removed: " + currentInput);
                            string[] messageComponents = currentInput.Split(new string[] { EncodeUtilities.headerSplitter }, 2, StringSplitOptions.RemoveEmptyEntries);
                            if (messageComponents.Length > 1)
                            {
                                string header = messageComponents[0], content = messageComponents[1];
                                UniversalDebug("Header: " + header + ", content: " + content);
                                if (header == "UIDATA")
                                {
                                    // If any new data received - process it.
                                    UIData data = JsonConvert.DeserializeObject <UIData>(content);
                                    UIReceiver.currentBools  = new List <bool> (data.bools);
                                    UIReceiver.currentInts   = new List <int> (data.ints);
                                    UIReceiver.currentFloats = new List <float> (data.floats);
                                    UniversalDebug("Data Received!");
                                }
                                else
                                {
                                    UniversalDebug("Header Not Recognized!", GH_RuntimeMessageLevel.Warning);
                                }
                            }
                            else
                            {
                                UniversalDebug("Data not Received!", GH_RuntimeMessageLevel.Warning);
                            }
                        }
                        else
                        {
                            UniversalDebug("Improper Message!", GH_RuntimeMessageLevel.Warning);
                        }
                    }
                    else
                    {
                        UniversalDebug("No data received.");
                    }
                } catch {
                    UniversalDebug("Error Processing Data.", GH_RuntimeMessageLevel.Error);
                }
            }
            else
            {
                // If connection disabled - stop receiving.
                UIReceiver.flagProcessed = false;
                UIReceiver.lastInputs    = string.Empty;
                UIReceiver.currentBools  = new List <bool>();
                UIReceiver.currentInts   = new List <int>();
                UIReceiver.currentFloats = new List <float>();
                UniversalDebug("Set 'Send' on true in HoloFab 'HoloConnect'", GH_RuntimeMessageLevel.Warning);
            }
            //////////////////////////////////////////////////////
            // Output.
            DA.SetDataList(0, UIReceiver.currentBools);
            DA.SetDataList(1, UIReceiver.currentInts);
            DA.SetDataList(2, UIReceiver.currentFloats);
                        #if DEBUG
            DA.SetData(3, this.debugMessages[this.debugMessages.Count - 1]);
                        #endif

            // Expire Solution.
            if (connect.status)
            {
                GH_Document document = this.OnPingDocument();
                if (document != null)
                {
                    document.ScheduleSolution(UIReceiver.expireDelay, ScheduleCallback);
                }
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Document    GrasshopperDocument = base.OnPingDocument();
            bool           run        = new bool();
            bool           reset      = new bool();
            int            iterations = new int();
            int            interval   = new int();
            List <Point3d> agents     = new List <Point3d>();

            if (!DA.GetData(0, ref run))
            {
                return;
            }
            if (!DA.GetData(1, ref reset))
            {
                return;
            }
            if (!DA.GetData(2, ref iterations))
            {
                return;
            }
            if ((!DA.GetData(3, ref interval)) | (interval < 1))
            {
                return;
            }
            if (!DA.GetDataList(4, agents))
            {
                return;
            }
            if (!DA.GetData(5, ref fitness))
            {
                return;
            }
            if (!DA.GetData(6, ref c1))
            {
                return;
            }
            if (!DA.GetData(7, ref c2))
            {
                return;
            }
            if (!DA.GetData(8, ref influence))
            {
                return;
            }
            if (!DA.GetData(9, ref max))
            {
                return;
            }
            if (!DA.GetDataList(10, attract))
            {
                return;
            }
            if (!DA.GetData(11, ref attractFactor))
            {
                return;
            }
            if (!DA.GetData(12, ref boundary))
            {
                return;
            }
            if (!DA.GetData(13, ref boundaryFactor))
            {
                return;
            }

            if (iterations != _maximum)
            {
                _maximum = iterations;
                _counter = iterations;
                swarm    = new Swarm(agents, fitness);
            }

            DA.SetData(0, _maximum - _counter);
            DA.SetDataList(1, output);

            _run = run;

            if (_counter == 0)
            {
                _run = false;
            }

            if (_run)
            {
                GrasshopperDocument.ScheduleSolution(interval, ScheduleCallback);
            }

            if (reset)
            {
                _maximum = iterations;
                _counter = iterations;
                swarm    = new Swarm(agents, fitness);
                GrasshopperDocument.ScheduleSolution(interval, ScheduleCallback);
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Component = this;
            doc       = Component.OnPingDocument();
            var    x = new List <double>();
            double fx = new double(); double h = new double(); int step = 0; double alpha = new double(); var eps = 1e-4;

            if (!DA.GetData("f(x)", ref fx))
            {
                return;
            }
            if (!DA.GetDataList("x", x))
            {
                return;
            }
            if (!DA.GetData("h", ref h))
            {
                return;
            }
            if (!DA.GetData("alpha", ref alpha))
            {
                return;
            }
            if (!DA.GetData("step", ref step))
            {
                return;
            }
            if (!DA.GetData("eps", ref eps))
            {
                return;
            }
            if (start == 0)
            {
                return;
            }
            if (counter == -1)
            {
                y = x;
            }
            List <Grasshopper.Kernel.Special.GH_NumberSlider> sliders = new List <Grasshopper.Kernel.Special.GH_NumberSlider>();

            for (int i = 0; i < x.Count; i++)
            {
                Grasshopper.Kernel.Special.GH_NumberSlider slider = Params.Input[1].Sources[i] as Grasshopper.Kernel.Special.GH_NumberSlider;
                sliders.Add(slider);
                if (counter == -1)
                {
                    minrange.Add((double)slider.Slider.Minimum); maxrange.Add((double)slider.Slider.Maximum);
                }
            }
            doc.NewSolution(false);
            if (agm == 1)
            {
                for (int i = 0; i < y.Count; i++)
                {
                    y[i] = Math.Min(Math.Max(y[i], minrange[i]), maxrange[i]);
                }                                                                                               //force y inside slider range
                var df = Sensitivity(sliders, y, h);
                dk = df; for (int i = 0; i < dk.Length; i++)
                {
                    dk[i] = -dk[i];
                }                                                               //dk=-df
                if (golden == 1)
                {
                    alpha = line_search_golden_section(sliders, y, dk);
                }
                var x_prev = x;
                for (int i = 0; i < x.Count; i++)
                {
                    x[i] = y[i] + alpha * dk[i];
                }                                                                 //x=y+alpha*dk
                var dk_norm     = Math.Sqrt(vec_multiply(dk, dk));
                var t_prev      = t;
                var reset_value = 0.0; for (int i = 0; i < dk.Length; i++)
                {
                    reset_value += -dk[i] * (x[i] - x_prev[i]);
                }                                                                                                          //np.dot(-dk,x-x_prev)
                if (reset_value <= 0.0)
                {
                    t = 0.5 * (1.0 + Math.Sqrt(1.0 + 4.0 * Math.Pow(t_prev, 2)));//t=0.50*(1.0+np.sqrt(1.0+4.0*t**2))
                    for (int i = 0; i < x.Count; i++)
                    {
                        y[i] = x[i] + (t_prev - 1.0) / t * (x[i] - x_prev[i]);
                    }                                                                                           //y=x+(t_prev-1.0)/t*(x-x_prev)
                }
                else
                {
                    t = 1.0; y = x;
                }
                DA.SetDataList("df(x)", df);
                DA.SetData("|df(x)|", dk_norm);
                DA.SetData("alpha", alpha);
                counter += 1;
                if (start == 1 && counter < step && dk_norm > eps)
                {
                    doc.ScheduleSolution(1, ScheduleCallback);
                }
            }
            else if (cg == 1)
            {
                if (counter == -1)
                {
                    dk = Sensitivity(sliders, x, h); for (int i = 0; i < dk.Length; i++)
                    {
                        dk[i] = -dk[i];
                    }
                    ; pk = dk;
                }                                                                                                                        //dk=-df
                for (int i = 0; i < pk.Length; i++)
                {
                    pk[i] = dk[i] + beta * pk[i];
                }                                                                    //pk=dk+beta*pk
                if (golden == 1)
                {
                    alpha = line_search_golden_section(sliders, x, pk);
                }
                for (int i = 0; i < x.Count; i++)
                {
                    x[i] = x[i] + alpha * pk[i];
                }                                                                 //x=x+alpha*pk
                var dk_prev = dk;
                dk = Sensitivity(sliders, x, h); for (int i = 0; i < dk.Length; i++)
                {
                    dk[i] = -dk[i];
                }                                                                                       //dk=-df
                beta = vec_multiply(dk, dk) / vec_multiply(dk_prev, dk_prev);
                var dk_norm = Math.Sqrt(vec_multiply(dk, dk));
                DA.SetDataList("df(x)", dk);
                DA.SetData("|df(x)|", dk_norm);
                DA.SetData("alpha", alpha);
                counter += 1;
                if (start == 1 && counter < step && dk_norm > eps)
                {
                    doc.ScheduleSolution(1, ScheduleCallback);
                }
            }
        }