Quantcast
Channel: Grasshopper Developer - McNeel Forum
Viewing all 3642 articles
Browse latest View live

Syntax Highlighting - C# Script

$
0
0

@dsonntag wrote:

Not sure what happens there, but the code snippet as attached does not get recognized by the C# editor. Seems to be the generic which he doesn’t like. What’s weird is that in Rh5 it is recognized properly. It is a bit inconvenient because everything is red and the formatting of the code which comes afterwards get’s completely messed up.

test_code_editor.gh (1.8 KB) snippet

Posts: 2

Participants: 2

Read full topic


Docstrings after SDK compilation mode

General questions about listeners in Custom GH Components

$
0
0

@marcsyp wrote:

I have been writing a lot of components with event listeners lately and I have a few general questions about implementation so that I can be aware of best practices.

  1. I have a lot of things that I typically need to update (trigger new component solutions) when a new Rhino document has loaded. Typically, I use the output of my custom RhinoDoc listener component to manually expire these downstream components. Take this example, for instance:

Here I am updating the Wombat “Get Document Units” component using my listener (offscreen) + MetaHopper. First question is this: Is it safe to write a document units component that incorporates its own document listener and use that instead? Is it safe to write a whole bunch of components that have their own internal document listeners and use them all over a large definition?

Is this conservative approach of using a single document listener in the document and manually expiring downstream components via Metahopper actually providing any safety/benefit? Because if not, I would probably be adding listeners of all kinds to a lot of my components. This holds true for layer events, viewport events, etc. I’m concerned about execution flow (and triggering multiple downstream operations/race conditions/invalid flags, etc), which is why I’ve been doing it this way. I realize that the gaps introduced by using Metahopper’s ExpireSolution everywhere has its own concerns, probably.

  1. After hours and hours of debugging various components, I became alarmed that the standard practice that I’ve been using for years essentially detaches and attaches a listener every time the component is solved, which isn’t a big deal for listeners that are “set it and forget it”, but for listeners that have selective expiration of outputs based on the event results and call ExpireSolution, I feel like there is way too much listener hijinx going on (see the preposterous SelectedLayersListener example I posted last week). Would you recommend storing the “Active” state in a static variable so that I can determine whether or not to remove/add listeners only when absolutely necessary? Or does it not matter?

Thanks!

Marc

Posts: 3

Participants: 2

Read full topic

Implementing Rhino/Grasshopper file in a Win Form application

$
0
0

@eissamail wrote:

Dear All,

I am building a C#.NET application and I want to be able to preview Rhino and Grasshopper files from my application without using Rhino and Grasshopper applications.

Does anyone have any idea on how to make this?

Thanks in advance :wink:

Posts: 1

Participants: 1

Read full topic

Set gh_slider value

$
0
0

@woojsung wrote:

Hi all,

I am building c# component that automatically generates gh_numbersliders and set max,min and current value. I managed to set the max and min value using the code below, but i cannot figure out how to set the current value.

  var ghSlider = new Grasshopper.Kernel.Special.GH_NumberSlider();
  gid = ghSlider.InstanceGuid;
  gids.Add(gid, new GH_Path(i));
  ghSlider.CreateAttributes();
  ghSlider.SetSliderValue((decimal) 22);
  //ghSlider.TrySetSliderValue((decimal) 22);
  //ghSlider.Slider.Value = (decimal) 22; 
  ghSlider.Slider.DecimalPlaces = 0;
  ghSlider.Slider.Maximum = (decimal) max;
  ghSlider.Slider.Minimum = (decimal) min;

Tried slider.value, SetSliderValue, TrySetSliderValue, but no matter what i do, i got sliders with the handle way off the component, which means set value didn’t work. Any idea? Thanks in advance.

W

Posts: 2

Participants: 1

Read full topic

Trying to mimic Radial Grid component

$
0
0

@bhattprathmesh.89 wrote:

Namaste All,
I am trying to make a radial grid component similar to the one from the paneling tool plugin which I had recently downloaded. I think I have got it almost, attaching the file and images
Capture%201
The last input of the component (FC) is full circle which creates a full circle ignoring the angle,
How do i incorporate it in my def.And how can I improve my existing one

Thanks a Ton!! :smiley:
RADIAL GRID TOOL EXERCISE.gh (7.1 KB)

Posts: 1

Participants: 1

Read full topic

How to debug a grasshopper breakpoint?

$
0
0

@andrealu2012 wrote:

i am writing a video capture component in C#
this is the code:

when i use the component,it works and update every frame ,looks like animation…it fine
but after running several minute(1 or 2 minitues),gh will show a dialog:


i translate the chinese into english in the picture…
2 questions:
how to fix that problem,and how to debug that(because it cannot use breakpoint in visual studio,i tried,but failed…)
Thank you very much!

Posts: 1

Participants: 1

Read full topic

Attractor Point Object Rotation


How to do some thing,when the component itself been deleted?

$
0
0

@andrealu2012 wrote:

i am writing a custom component ,i create a thread to do something.
main code is like this:


my question is : if i delete this component from canvas (when the thread is running),how to do to stop the thread and delete the thread ?
thank you!

Posts: 2

Participants: 2

Read full topic

Draw Full Names not working on dynamically added parameters?

$
0
0

@harmatb wrote:

I am creating a component which can change it’s inputs based on user input.
First of, as I know this is not the most grasshoppiest way, the reasoning behind the dynamic component is it encapsulates an ever expanding host of very similar components (cross section macros for a FEA software) each with their own number of numeric parameters (height, width, left flange angle, etc).

The parameters are added like this:

            Param_Number param = new Param_Number();
            param.Name = attr.Key.Name + " [" + attr.Key.Unit + "]";
            param.NickName = attr.Key.Nick;
            param.Description = attr.Key.Desc;
            param.SetPersistentData(new GH_Number(attr.Key.DefaultValue));
            Params.RegisterInputParam(param);
            Params.OnParametersChanged();
            OnDisplayExpired(true);
            ExpireSolution(true);

Now the slight problem is, for some reason if I check the “Display Full Names” option in the GH Display options, these parameters are still only shown with their NickNames.

Is there some other plumbing required to handle the dynamic parameter manipulation?
The class does not implement IGH_VariableParameterComponent as this is not a ZUI like component (but it did not help either), the user can not directly add/remove parameters, only choose which “section macro” would he like to create.

Posts: 1

Participants: 1

Read full topic

Galapagos solver implementation

Rhinocommon Surface Normal is wrong

Getting Component/Wire/Param connected to Undo Records

$
0
0

@verina_cristie wrote:

Hi, I understand that with Undo Records we are able to get the last action done by user (e.g: Add Component, Add Wire, Slider Change etc). Is it possible to get the component (guid, pivot, etc) / input-output param / value of slider attached to these actions?

Posts: 1

Participants: 1

Read full topic

Animation with Up-Vector / tilt

$
0
0

@void_studio wrote:

Is there a way of setting up an animation in rhino 6 including a camera “up-vector”/camera tilt?
Specifically I would like to do this from a C# component in GH.
In the rhinocommon documentation I can see CameraPoints and TargetPoints but some way of setting rotation around the camera axis seems to be missing.

Posts: 4

Participants: 3

Read full topic

Part segmenting + OpenNest

$
0
0

@fpagel01 wrote:

I apologize if this has been discussed elsewhere, but I couldn’t find anything. Basically, I work with “jigs” or plywood gridwork parts that are assembled for temporary purposes. (They are typical “dog boned” together but joinery is not important to this discussion. ) I would like to write a grasshopper definition that takes parts (some which are larger than able to fit on one sheet of plywood) and chops them into smaller parts and nests them, then intelligently moves the chopping lines to minimize the amount of nested material. Do you guys think this can be done? Or does this start to approach on AI as the definiation will have to “learn” with each nesting cycle?

Posts: 4

Participants: 2

Read full topic


ScheduleSolution, ExpireSolution and external events

$
0
0

@marton.krauter wrote:

Dear All,

EDIT: Added a non-Excel dependent version to the second post…

I am trying to create a (VB) component that issues a solution recalculation on a change of a referenced Excel workbook (cells) using Excel interop services. I have attached a model with a minimum set of components and lines of code to demonstrate the issue I am struggling with.

Imports Microsoft.Office.Interop

Private Sub RunScript(ByVal P As System.Object, ByRef B As Object)
   RhinoApp.WriteLine("--- Script staring...")
   app = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
   wb = app.Workbooks.Open(P)
   B = "Now"
End Sub

Private app As Excel.Application
WithEvents Private wb As Excel.Workbook
Private counter As int32

Private Sub SheetChange(ByVal Sh As Object, ByVal Target As Object) Handles wb.SheetChange
  counter = counter + 1
  RhinoApp.WriteLine("Workbook changed " & counter & " times, issuing ExpireSolution in 5 secs...")
  Component.OnPingDocument.ScheduleSolution(5000, AddressOf Schedule_CB)
End Sub

Private Sub Schedule_CB()
  RhinoApp.WriteLine("Recalculating, SolutionState: " & Component.OnPingDocument.SolutionState)
  Component.ExpireSolution(True)
End Sub

So far:

  • The event handler works fine. Actually, if I put ExpireSolution there, the model performs pretty well and does its job.
  • However, of course, in that case if the next change event occurs earlier than the solution finishes, it will throw the object expired during a solution exception (which is definitely reasonable)
  • As I read I should use ScheduleSolution to handle such cases, and issue the ExpireSolution from its callback. I tried to implement it, but ended up having an endless loop of recalculations at the first time the event occurs.
  • Callback reached fine, timing is ok. Examining SolutionState does not help, it switches from 2 (PostProcess) to 0 (PreProcess) but never reaches 1 (Process).
  • It seems to me it is not an issue of instantly rescheduling a solution (as there is no delay), but the callback function getting called over and over again.

image

To reproduce using the attached model:

  • Probably need to reference the ‘Microsoft.Office.Interop.Excel.dll’ library on your system. Look for folders in the Global Assembly Cache (GAC) tree of Windows. Different Office versions (i.e. using 14 instead of 15) should work fine.
  • Create and save an empty Excel workbook to a location of your choice (of course you can use an existing one)
  • Modify the ‘Path/File’ container in the model accordingly
  • Make a change in any sheets of the Excel workbook
  • If all goes right (haha), you will end up with a (warning!) crashed Rhino.

(Technical details: Rhino 6.16.19190.7001, 07/09/2019, Grasshopper 1.0.0007, Windows 10, Office 2016)

Any help is truly appreciated, thank you!

Marton

ScheduleSolutionExcel.gh (4.3 KB)

Posts: 3

Participants: 1

Read full topic

Looking for Efficent Type Testing and Type Conversion

$
0
0

@Nicolas_Azel wrote:

The Question

I’m wondering if there is a more efficient way to check the type of IGH_GOO in order to cast it to alternative types.

Use Case

Given a list of GH_Goo items of multiple non-geometry types [ GH_Integer, GH_Boolean, GH_Number , GH_Time, ect], identify the type in order to specify the correct corresponding type within an external library.

Current Strategy

//'attributes' is a GH_Structure<IGH_Goo> with mixed data types
//'fs' is a FeatureSet defined by an external library 

//retrieve the IGH_Goo item to try and identify the type of
var typeItem = attributes.get_Branch(thisFieldPath)[thisFieldIndex];
string fieldName= "typeItem's DataTable Column Name";

//sequentially try and identify the type with 'if' statments
if (typeItem is Grasshopper.Kernel.Types.GH_Number)
    {
     fs.DataTable.Columns.Add(new DataColumn(fieldName, typeof(double)));
    }
else if (typeItem is Grasshopper.Kernel.Types.GH_Integer)
    {
      fs.DataTable.Columns.Add(new DataColumn(fieldName, typeof(int)));
    }
else
    {
       fs.DataTable.Columns.Add(new DataColumn(fieldName, typeof(string)));
    }

//-----------------------------------------------------------------------//
// after FeatureSet DataTable Columns have been made with the correct type
// iterate over attributes and converting them to correct type 
// then adding them to the DataTable

foreach (var thisAttribute in attributes.get_Branch(path))
  {
      // 1) check DataColumn type
      //  2) convert attribute to corisponding type 
      //  3) add converted attribute to DataRow
  if (fs.DataTable.Columns[fields[thisIndex]].DataType == typeof(double))
   {
     feature.DataRow[fields[thisIndex]] = Convert.ToDouble(thisAttribute.ToString());
   }
  if (fs.DataTable.Columns[fields[thisIndex]].DataType == typeof(int))
   {
     feature.DataRow[fields[thisIndex]] = Convert.ToInt32(thisAttribute.ToString());
   }
  else
   {
     feature.DataRow[fields[thisIndex]] = thisAttribute.ToString(); 
   }
 }

Imagined Alternative

I imagen there would be a way to retrieve the IGH_Goo’s Type and then look that type up in a Dictionary for its corresponding value. Perhaps “enum GH_IO.Types.GH_Types” could be used along with “Enum.GetName()” to help? Here is an example below:

//'attributes' is a GH_Structure<IGH_Goo> with mixed data types
var typeItem = attributes.get_Branch(thisFieldPath)[thisFieldIndex];

Dictionary<string, Type> typeMap = new Dictionary<string, Type> { 
      { "gh_int32",  typeof(short)    }, 
      { "gh_int64",  typeof(long)     }, 
      { "gh_double", typeof(double)   },
      { "gh_decimal",typeof(float)    },
      { "gh_date",   typeof(DateTime) }, 
      { "gh_guid",   typeof(string)   }, 
      { "gh_string", typeof(string)   }
 };

var fieldType = typeMap[ TypeOf(typeItem) ]; //The Magic 'TypeOf' Method I'm looking for...
string fieldName = "typeItem's DataTable Column Name";
fs.DataTable.Columns.Add(new DataColumn(fieldName, fieldType)); //'fs' is a FeatureSet defined by an external library 

Other Disscussions on this:


Posts: 2

Participants: 2

Read full topic

Saving geometry for easy access in C#

$
0
0

@erikforsberg95 wrote:

Hi everyone!

I’m creating some custom components in c# in visual studio and I’m currently trying to create a component where the user gets to pick a house type from a list of 5 types (A-E). I’ve created a house class where I store the properties of the house and the user can later “explode” the object to get back all the properties of the selected house.

What I’m thinking is that it would be neat to render low level version of the house when the user picks the type by default, inside the component itself, instead of having to reference the geometry and interpolate which I’m doing right now.

What do you think is the best way of doing this? Should I save the data to a .json file somehow and reference that file in c# or is there a way of actually saving a brep as pure c# code in Rhinocommon?

Thank you!
Erik

Posts: 2

Participants: 2

Read full topic

Creating a parametric truss for a 3D alignment

$
0
0

@andersmunthe wrote:

Hi! I am fairly new to Grasshopper, and I am trying to recreate a truss structure for a double deck bridge. I have created the trusses, following a 3D alignment curve, but most likely in an ineffective way. My last issue now is creating the fillets between the diagonals, and between the diagonals and the top & bottom decks. I’ll attach a screen shot of a reference elevation, tho the exact dimensions and radii are not important.

truss_fillet.gh (15.5 KB)

Posts: 1

Participants: 1

Read full topic

Ghenv ghpy compilation

$
0
0

@rdshan wrote:

Hi Giulio. Thank you for your excellent work! I have similar problem as RetroPost.LT @RetroPost.LT.
Here is the code:

from ghpythonlib.componentbase import executingcomponent as component
import Grasshopper, GhPython
import System
import Rhino
import rhinoscriptsyntax as rs

class MyComponent(component):
def RunScript(self, genetic):
author = “XXX”

    gh_env = ghenv

    gh_env.Component.Name = "Fitness Function"
    gh_env.Component.NickName = "Fitness Function"

    out_fitness = None

    if genetic[0] is None:
        in_genetic = None
    else:
        in_genetic = genetic

    # ==============================================================================
    # ============================= START ========================================
    sum_val = None
    if in_genetic is not None:
        sum_val = 0
        for g in in_genetic:
            sum_val += g

    out_fitness = sum_val
    return out_fitness

When I put this component into canvas and loaded input it get red and says:

  1. Solution exception:global name ‘ghenv’ is not defined

Do you know why?

Posts: 1

Participants: 1

Read full topic

Viewing all 3642 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>