Quantcast
Channel: Scripting - McNeel Forum
Viewing all 4125 articles
Browse latest View live

Flatten list of list in Grasshopper Python


Hatch list in Ghpython

$
0
0

@seghierkhaled wrote:

Hello, i create a script to add hatch but the problem it can’t detect list hatch automatically unless i open options and select hatch than click ok.
This happen also with other hatch components from other plugins

Posts: 5

Participants: 2

Read full topic

Rhino Window Size and Position

$
0
0

@eric.bunn wrote:

Hi,

Is there a way to set the size and position of the Rhino Window using Rhinoscript or the Rhino API? I want to set the size to 50% with the left of the window at the screens center.

Thanks,

Eric

Posts: 1

Participants: 1

Read full topic

Using some letters on a text

$
0
0

@kadirsyk wrote:

Hi All,

I have a question about texts on rhino.
ı gave some various names to parts like “CONST 20MM YELLOW” or “CONST 15MM BLACK” by construction script.
I just want to get thickness information on given names automatically. 20MM, 15MM etc.
How can ı do it by rhino script? ı cant find proper method.

Thanks.

Posts: 1

Participants: 1

Read full topic

Example of using a Class in RhinoPython

$
0
0

@Willem wrote:

Hi All,

I’ve been wanting to post an example of using classes in RhinoPython for a long time.
Inspired by the recent contamination simulations I found a good example of using a class.

At least I hope so, as understanding classes takes some time and maybe these examples are already too complex. Let me know if you have any questions or add comments to help others.

The first script is a simple random population “walking around”
contamination_simulation_01.py (4.3 KB)
image

Building on that first script I made a random person contaminated and let all walk around.
If someone comes too close to a contaminated person the contamination extends to them.
contamination_simulation_02.py (5.6 KB)
image

In the last version I added avoidance: everyone that is contaminated tries to avoid proximity to others by adjusting their course.
contamination_simulation_03.py (7.2 KB)
image

-Willem

Below the full code of the last version (contamination_simulation_03.py)

import rhinoscriptsyntax as rs
import scriptcontext as sc
import Rhino
import random

import System
# script by willemderks march 2020
# the script is an attempt to visualize the spread of a virus in a community
# based on the behaviour of the individuals in that community
# goal is to give an example of how classes can be used in RhinoPython



class Person(object):
    """
     this defines a class object that represents a person inside the simulation
     
     this object will have spatial properties
        a position  (.point)
        a direction (.vector)
        a speed     (.speed)
     
     this object will have virus related properties
        contaminated    True/False
        symptomatic     True/False
        immune          True/False
        
        
     there are additional properties that influence the behaviour
        carelessness  0.0 ~ 1.0
        
    """
    
    #these are some class global variables
    #changing these will affect all class instances
    
    
    color_dict = {}  #dictionary with colors for states
    color_dict['healty']       =  System.Drawing.Color.FromArgb(80,120,80)
    color_dict['contaminated'] =  System.Drawing.Color.FromArgb(140,50,50)
    color_dict['immune']       =  System.Drawing.Color.FromArgb(190,220,190)
    
    
    infection_distance = 10  #distance for contamination
    
    infection_duration = 150 #frames it takes to fight infection and become immune
    
        
    def __init__(self, point, vector, speed):
        #this method is called when creating the instance
        #the self variable represents the instance itself
        self.point  = point
        self.vector = vector
        self.speed  = speed
        
        self.state = 'healty'  #by default all persons are healty
        
        self.prepared_point = None
        self.color = self.color_dict[self.state]
        
        self.others = []
        
        self.contaminated_frames = 0
    
    
    
    
    
    def add_others(self, others):
        #add others exclusing self
        self.others = [other for other in others if not other == self]
    
    def distance_to(self,other):
        #calculate the distance to another person
        return self.point.DistanceTo(other.point)
    
    def future_position(self):
        return  self.point + (self.vector*self.speed)
    
    def do_contamination(self):
        #check if others in proximity and pass contamination
        if self.state == 'contaminated' :
            for other in self.others:
                if other.state == 'healty':
                    if self.distance_to(other) <= self.infection_distance:
                        other.state = 'contaminated'
    
    def adjust_course(self):
        #predict the position of others for the next frame
        #if they are contaminated and too close adjust direction
        
        if self.state != 'contaminated': return
        
        my_future_position = self.future_position()
        
        avoidance_vectors = []
        
        for other in self.others:
            if other.state == 'contaminated': continue
            #test if the next frame I'm too close
            other_future_position = other.future_position()
            other_future_distance = my_future_position.DistanceTo(other_future_position)
            if other_future_distance  <= self.infection_distance:
                #create vector away from future position
                away_vec = Rhino.Geometry.Vector3d(my_future_position-other_future_position)
                away_vec.Unitize()
                #set the length of the vector little over the safe distance
                away_vec = away_vec * 1.1 * (self.infection_distance*other_future_distance)
                avoidance_vectors.append(away_vec)
            
        if not avoidance_vectors : return
        
        #get the mean vector of all avoidances
        all_vec = Rhino.Geometry.Vector3d(0,0,0)
        for vec in avoidance_vectors: all_vec =  all_vec + vec
        mean_vec = all_vec/len(avoidance_vectors)
        
        mean_vec.Unitize()
        self.vector = mean_vec
    
    def prepare_frame(self):
        
        #if infected, contaminate all that are close
        self.do_contamination()
        
        if self.state == 'contaminated':
            self.contaminated_frames += 1
        if self.contaminated_frames > self.infection_duration:
            self.state = 'immune'
        
        
        self.adjust_course()
        
        self.prepared_point  = self.future_position()
        
        #simple bounce at limits when out of bounds
        self.vector = do_bounce_vector(self.prepared_point, self.vector)
        
    def set_frame(self):
        self.point = Rhino.Geometry.Point3d(self.prepared_point)
        self.color = self.color_dict[self.state]

# utilities
def get_random_point():
    x = -100 + random.random()*200
    y = -100 + random.random()*200
    return Rhino.Geometry.Point3d(x,y,0)
    
def get_random_vector():
    x = (-0.5+random.random())
    y = (-0.5+random.random())
    vector = Rhino.Geometry.Vector3d(x,y,0)
    vector.Unitize()
    return vector
    
def get_random_speed():
    base_speed = 2
    speed_factor = 5
    random_speed = random.random()
    return (base_speed + random_speed)/speed_factor

def do_bounce_vector(point,vector):
    
    if not -100 < point.X < 100 :
        vector.X = -vector.X
    if not -100 < point.Y < 100 :
        vector.Y = -vector.Y
        
    return vector




#runner
def do_run():
    
    rs.EnableRedraw(False)
    
    
    people = []
    total = 100
    for i in range(total):
        pt  = get_random_point()
        vec = get_random_vector()
        spd = get_random_speed()
        new_person = Person(pt,vec,spd)
        people.append(new_person)
        
    
    # we add the population to each individual
    # this allows for each individual to 'see' the others
    for person in people:
        person.add_others(people)
        
    
    # we now have 100 random people
    # we infect 1 of them
    people[0].state = 'contaminated'
    
    #lets make them move for 300 frames
    
    
    #a colorized pointcloud to visualize them
    point_cloud = Rhino.Geometry.PointCloud()
    _ = [point_cloud.Add(person.point,person.color) for person in people]
    cloud_id = sc.doc.Objects.AddPointCloud(point_cloud)
    
    frames = 1500
    for i in range(frames):
        #use a generator to let all people caluculate their next frame  
        _ = [person.prepare_frame() for person in people]
        
        #use a generator to set the prepared state as the new state
        _ = [person.set_frame() for person in people]
        
        #use a generator to fill the new pointcloud
        point_cloud = Rhino.Geometry.PointCloud()
        _ = [point_cloud.Add(person.point,person.color) for person in people]
        
        #replace the old pountcloud geometry with the new one
        sc.doc.Objects.Replace(cloud_id, point_cloud)
        
        #update the viewports
        rs.Redraw()
    
    
    rs.DeleteObject(cloud_id)
    
    rs.EnableRedraw(True)

if( __name__ == '__main__' ):
    
    do_run()

Posts: 3

Participants: 2

Read full topic

Eto forms resolution

$
0
0

@onlyforpeace wrote:

Hi,
I made an eto form to fill the DocumentUserText,
but now I want to finalize it at home, but my workstation at the factory has a resolution of 2560 x 1600 or something like that, but at home, I have a small YOGA lenovo, with a resolution of 1360 x 760 … so when I run the script, the form doesn’t fit on my screen, so I don’t see the Validate button …
how can i return the screen resolution ( i found rs.screensize()), and if it’s not enough, how can i put a cursor on my form?

Posts: 1

Participants: 1

Read full topic

Python add IsSubD

Extract the axis of extrusion of the profiles (I-beam,C-beam..)

$
0
0

@msgatrong wrote:

Hello,
fiding_axe_extrusion.3dm (1.2 MB)
I am looking for a script which allows to extract the axis of extrusion of the column or beam as profiles (I beam, H beam, C beam …) or the cross-section center line/curve of the objects given in the attached file.

In fact I have a 3D model with a lot of beam and column as profile, I have to build a simple EF model which constitutes only the cross-section center line/curve of these profiles.

How can ı do it by rhino script?

Thanks

Posts: 3

Participants: 2

Read full topic


Get Volume Centroid without creating the point

$
0
0

@eric.bunn wrote:

Hi,

I’m trying to pull the volume centroid of polysurface using the code below and I get the following error: “Message: getset_descriptor is not callable”. Can anyone explain what I am doing wrong. I only want the coordinates and not the physical point (the Rhino Command creates a physical point). Yes I know I can get the bounding box and calculate it myself. If I can do it in less code that would be better for me.

Thanks,

Eric

import Rhino
import rhinoscriptsyntax as rs

obj = rs.GetObject(“Select”,0)
pt = Rhino.Geometry.VolumeMassProperties.Centroid(obj)
print(pt)

Posts: 4

Participants: 3

Read full topic

Copy nested blocks in place -- python

$
0
0

@Rickson wrote:

i’m trying to copy out the nested blocks but having trouble getting them back in their instance locations, they go back to 0. Do i need to create a plane at their instance origin and do plane to plane transformation? It seems to hold some sort of relation to the Top Level Block.

My attempts so far.

import rhinoscriptsyntax as rs
import Rhino


#Select Block
#Get all instances of block
#Explode and get 1st level nested blocks
#place instance of said block at its locations

selBlks = rs.GetObjects("Select Blocks", 4096)
blkcpy = []

for blk in selBlks:
    name = rs.BlockInstanceName(blk)
    allBlks = rs.BlockInstances(name)
    for bk in allBlks:
        blkObjs = rs.BlockObjects(rs.BlockInstanceName(allBlks[0]))
        for blkblk in blkObjs:
            if rs.IsBlockInstance(blkblk):
                blkcpy.append(blkblk)

rs.CopyObjects(blkcpy)
print blkcpy

import rhinoscriptsyntax as rs
import Rhino


#Select Block
#Get all instances of block
#Explode and get 1st level nested blocks
#place instance of said block at its locations

selBlks = rs.GetObjects("Select Blocks", 4096)

for blk in selBlks:
    name = rs.BlockInstanceName(blk)
    allBlks = rs.BlockInstances(name)
    for bk in allBlks:
        blkObjs = rs.BlockObjects(rs.BlockInstanceName(allBlks[0]))
        bkx = rs.BlockInstanceXform(bk)
        for blkblk in blkObjs:
            if rs.IsBlockInstance(blkblk):
                xform = rs.BlockInstanceXform(blkblk)
                bname = rs.BlockInstanceName(blkblk)
                #needs transformation of bkx to xform
                #insrtbk = rs.InsertBlock2(bname, bkx)
            

Posts: 3

Participants: 2

Read full topic

VectorAngle() returns 0 instead of 90

AddSweep1: closed option don't work

$
0
0

@seghierkhaled wrote:

Hello, i try this code but closed option don’t work

Help on function AddSweep1 in module rhinoscript.surface:

 |  AddSweep1(rail, shapes, closed=False) |      Adds a surface created through profile curves that define the surface
 |          shape and one curve that defines a surface edge.
 |          Parameters:
 |            rail (guid): identifier of the rail curve
 |            shapes ([guid, ...]): one or more cross section shape curves
 |            closed (bool, optional): If True, then create a closed surface

Posts: 3

Participants: 2

Read full topic

Cannot call geometry properties in object variables in Rhino Python

$
0
0

@raylee14 wrote:

Hi everyone,

I have created some class objects with some geometries property insides
However, when I pass those objects to other python components, I found that the geometries cannot be called (but other properties like numbers are fine)

The following is the error message:
Runtime error (NullReferenceException): Object reference not set to an instance of an object.

Traceback (most recent call last):
SystemError: Object reference not set to an instance of an object.

Posts: 1

Participants: 1

Read full topic

Why call main() with this conditional?

$
0
0

@gwil wrote:

So here is a snippet of code:

def main():

counter = 0
#collect data
GUIDs = rs.GetObjects(‘select objects’)
#call my system class
obj01 = MySystemClass(GUIDs, counter)

if (name == “main”):
main()

Does anyone know why I would use the second from last line conditional to call the main() function? Does this have something to do with me setting up my own code as a module and potentially having to call it to run from outside itself?

Thanks!!

g.

Posts: 2

Participants: 2

Read full topic

Is it possible to write a Python script to realize the function of path mapper? for exampe {a} -> {a + 66}

$
0
0

@w.wu wrote:

Hi everyone,

The path mapper is a powerful function to change the data tree path, however, if I want to realize it using a Python script, how should I do?

Thanks!
Capture

Posts: 1

Participants: 1

Read full topic


Work around for DetailNames - NOT IMPLEMENTED IN PYTHON YET

$
0
0

@eric.bunn wrote:

Is there another way to accomplish this using Python other than DetailNames. Not in 5 or 6 that I can find for Python.

Eric

Posts: 1

Participants: 1

Read full topic

GetDetailViews

Calculating area moments of inertia in Rhinoscript (now with files)

$
0
0

@pim_meester wrote:

Hi!

I’m not getting the same calculation results on my script that uses Rhino.SurfaceAreaMoments and Analyze > Mass Properties > Area Moments. I need the moments of inertia about the centroid coordinate axes. I’ve calculated the moments of inertia by hand and I’m sure that my code result is wrong haha. Does anyone see what I’m missing?

My code looks like this:

surfaces = Rhino.SelectedObjects

If IsArray(surfaces) Then
			For Each surface In surfaces
					inertias = Rhino.SurfaceAreaMoments(surface)

					If IsArray(inertias) Then
						Rhino.Print	Rhino.Pt2Str(inertias(10), 0)
				
		End If
	Next
	
End If

I’ve attached a Rhino file with the surfaces and a pdf with my calculation. The text is in Dutch but the numbers and calculations are clear.

Thanks in advance!

Rhino Testmodel 0 meting.3dm (119.8 KB) Calculation moments of inertia about centrooid axes.pdf (252.5 KB)

Posts: 5

Participants: 2

Read full topic

Time zone : How?

Close Detail View after Activating

Viewing all 4125 articles
Browse latest View live