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

Get plane-aligned flatbox of a triangular mesh face in GHPython?

$
0
0

Hi,

I’m purposfully trying to get the plane-aligned flatbox (bounding box of no volume) of a triangular mesh face. This turned out to be far more challenging than expected! :slight_smile:

import Rhino.Geometry as rg

def get_face_edges(face_vertices):
    """Returns edges as lines for a list of face vertices."""
    edges = []
    for i in range(len(face_vertices) - 2):
        edges.append(rg.Line(face_vertices[i], face_vertices[i + 1]))
    edges.append(rg.Line(face_vertices[-1], face_vertices[0]))
    return edges


if __name__ == "__main__": 
    # Mesh and fIndex are GHPython component inputs
    face = Mesh.Faces[fIndex]  # triangular face
    vertices = [rg.Point3d(v.X, v.Y, v.Z) for v in Mesh.Faces.GetFaceVertices(fIndex)[1:]]

    edge = get_face_edges(vertices)[0] 
    normal = Mesh.FaceNormals[fIndex]

    yaxis = edge.UnitTangent
    xaxis = rg.Vector3d.CrossProduct(yaxis, normal)
    plane = rg.Plane(edge.From, xaxis, yaxis)
    
    fmesh = rg.Mesh()
    for i in range(len(vertices)):
        fmesh.Vertices.Add(vertices[i])
    fmesh.Faces.AddFace(0, 1, 2) 
    
    xform = rg.Transform.ChangeBasis(rg.Plane.WorldXY, plane)
    bbox = fmesh.GetBoundingBox(xform)
    plane_to_world = rg.Transform.ChangeBasis(plane, rg.Plane.WorldXY)
    bbox.Transform(plane_to_world) # inflates the previously flatbox to a 3D bounding box ?
   
    # Output
    a = bbox 

In the WorldXY-plane, the correct flat bounding box appears at the world origin, however when I try to transform it back to the plane of the face, it gets inflated to 3D?

Why is the Transform() method of Rhino.Geometry.BoundingBox different from that of other geometry?

Merry christmas everybody! :santa:

example.gh (9.3 KB)

3 posts - 2 participants

Read full topic


CreateBooleanUnion returns a boolean difference?

$
0
0

Hi All
I’m new to c# and rhinocommon and am working my way through some of the functions to get some practice.
I’m having a problem with one particular case of Brep.CreateBooleanUnion- it seems to return a difference rather than a union.
I have included a file with two examples. One uses geometry generated from GH components and works well, the other uses geometry entirely from a short script and is the one that returns a difference.
I’m quite certain that the parts I am trying to join are closed and clean, with normals pointing the correct direction, and that they are organized within the list properly.
What am I missing here? I’ve spent some time digging through the forums but can’t seem to find a matching problem.

Thanks in advance,

Lucas
201224_unionproblem.gh (9.2 KB)

1 post - 1 participant

Read full topic

Quickly select the outline of objects?

RunScript and MRU

$
0
0

Hi,
I want a script to execute a command and show it in the mru popup menu.
For the moment RunScript seems to be invisible to mru.
When I run :

import Rhino
Rhino.RhinoApp.RunScript(‘ze’, ‘mru_string’, False) #or True

‘mru_string’ does not appear in the “most-recent-used command popup”.

Is it misbehaving or I dont understand the purpose of that option ?
Is there a way to push a command in the mru with a script ?

Regards

1 post - 1 participant

Read full topic

Writing a Rhino Script / Modelling help

$
0
0

Hello,

I work as a kitchen designer and create a lot of kitchen cabinets in Rhino.

we often use the same design of unit in different measurements so I have been using Solidpt to stretch the unit to the correct dimension without malforming it.

The problem comes with the intricate sweep detail which don’t transform very well.

I’m looking into grasshopper as a way of adding intricate sweep details at the end once the right size has been determined.

Please could someone advise me if this would be the best way?

Additionally, I’m looking into learning RhinoScript as a way to quickly model each cabinet as it can get fairly repetitive and I hope a script would save considerable time.

Would really appreciate anyone’s thought or opinions!

All the best.

2 posts - 2 participants

Read full topic

Collatz Conjecture Python Script

$
0
0

Hi all

I am trying to learn Python and decided to try making a script to visualise the Collatz Conjecture as a study exercise. I somewhat succeeded in generating the branching lines I was going for, but as I am still learning, this left me with lots of questions.

  1. In order to get the multiple threads, and multiple Collatz sequences, I simply input a range rather than a unique integer to my x input. I am pretty happy with the way the output is organised, but I was wondering if there would be any advantage in making this input a single value (total number of threads) and integrating a for loop in the code to get the sequence for each individual thread? And how would you go about writing it?

  2. The way I am visualising it here, all the lines overlap as they converge down to the base point. I was wondering if there would be a way to avoid this? Maybe by adding a new function that would clean the sequences of duplicate numbers after a minimum duplicate is met? But that would leave me lost on how to create the starting lines for each new branch.

  3. I would like to control the length of the new lines by applying a multiplier to them depending on the iteration (ie. to make them progressively get shorter or longer with each iteration). Should I simply use rs.VectorScale and use i * scalefactor?
    Edit: This turned out to be much easier than I expected, I simply added rs.VectorScale at the beginning of my for loop after the creating the vector.

  4. And finally I would love to try and make this grow in 3 dimensions, but I am not sure what sort of rule could be set up for Z axis transformation, while maintaining the common values of each sequence aligned. Ideally I’d want to rotate the vector along x or y axis at each branching intersection, but I’m not sure how to go about doing that. Or maybe create the rotation depending on the value of the number in the sequence? That way common values would always rotate the same way? Would there be some way of avoiding branches from colliding?

And of course, if you have any suggestions on cleaning up the script making it more efficient in any way, I would also really appreciate it. I am still very much a beginner so writing everything out and making the code as explicit as possible helps me a lot, but all suggestions are welcome.

Thanks!

201229 - Collatz Conjecture.gh (13.0 KB)

import rhinoscriptsyntax as rs

#create collatz sequence
def collatzSeq(i):
    seqList.append(i)
    while i > 1:
        if i % 2 == 0:
            i = i // 2
        else:
            i = ((3*i) + 1) // 2
        seqList.append(i)
        
    seqList.reverse()

#create list to store sequence numbers
seqList = []

collatzSeq(x)

def collatzViz(sequence, startLine, evenRot, oddRot):
    newLines.append(startLine)
    for i in sequence:
        #find the start and end points of the input line
        endpt = rs.CurveEndPoint(newLines[-1])
        stpt = rs.CurveStartPoint(newLines[-1])
        #create a vector from end points
        vect = rs.VectorCreate(endpt, stpt)
        if i % 2 == 0:
            #define an even value for rotation
            #evenRot = -20
            vect = rs.VectorRotate(vect, evenRot, (0,0,1))
        else:
            #define an odd value for rotation
            #oddRot = 20
            vect = rs.VectorRotate(vect, oddRot, (0,0,1))

        ptadd = rs.PointAdd(endpt, vect)
        #create line and add to main list
        newLines.append(rs.AddLine(endpt,ptadd))
        #call recursive function

#create list to store resulting lines
newLines = []

collatzViz(seqList, startLine, evenRot, oddRot)

#output
a = seqList
b = newLines

2 posts - 2 participants

Read full topic

Dots from object name

Typo in the documentation

$
0
0

I don’t know enough about coding to know if this will cause a problem for someone or not, but I came across the following, in which ‘local’ gets some characters reversed:

Rhino.Geometry.Curve.LcoalClosestPoint

3 posts - 3 participants

Read full topic


Como juntar dois ou mais Scripts

$
0
0

Olá pessoal, gostaria de saber como eu poderia juntar dois ou mais scipts para que rodassem um após o outro, sendo que entre cada intervalo eu adicionaria uma informação.

2 posts - 2 participants

Read full topic

For loop works, but not if inside another for loop

$
0
0

I am new to Python, and I feel like I am missing something basic. Forgive me if that is true, but please point me toward something that explains the concept because I have been trying to work around this for a while and I am out of ideas.

I have some surfaces and I want to use them to split each other. I am using the SplitBreps method. It seems to work, generally. The code below splits a brep: segSurfs contains two surfaces. I ignore the first and keep the second as my remainder.

Inside the for loop, I split the remainder in two, and keep the first in TTops and keep the second as my remainder for the next loop.

But when I attempt this, it will not let me get at the elements inside segSurfs. I have tried the for loop below- for i in segSurfs- and I have tried segSurfs[0], segSurfs[1]. These work fine outside the ‘for i in range(TFaces.Count):’ loop, but not inside it.

It keeps telling me segSurfs is not subscriptable or that it is “iteration over non-sequence type None Type”

The things that show up as squares below are empty square brackets

segSurfs =
TBreps =
TVBreps = rs.coercebrep(TVSurf[0])
TTops =
tTop =
TBreps.Add(rs.coercebrep(TFaces[0]))
segSurfs = rs.SplitBrep(TVBreps,TBreps[0],False)
for i in segSurfs:
if i == 0:
continue
else:
remainder = i
for i in range(TFaces.Count):
if i == 0: #skip the first iteration
continue
TBreps.Add(rs.coercebrep(TFaces[i]))
segSurfs = rs.SplitBrep(remainder,TBreps[i],False)
for i in segSurfs:
if i == 0:
TTops.Add(i)
else:
remainder = i

Thanks for any help

1 post - 1 participant

Read full topic

Equality Bug Grasshopper and C#?

$
0
0

EqualityBug.gh (17.6 KB)

Hello Rhinoceros Forum!

I do not understand the behavior of equality in this script:

if (two vectors are perpendicular to each other) { the dot Product is equal to 0 and the cos of the angle is equal to the dot Product }
So Why the expression :
dotProduct == Math.Cos(angle) output False?
and why if I connect the outputs to a panel or to a Number component the output is correct as True?
Is this a Bug of the Equality in Grasshopper an in C#?

Thanks for any explanation!

3 posts - 2 participants

Read full topic

Where are named selections stored? Access via RhinoCommon?

$
0
0

In the API docs, in Rhino.DocObjects.Tables, I see these guys:

image

but no NamedSelectionTable Class. A search for NamedSelection or even just named or selection does not reveal anything having to do with named selection sets… maybe I missed something though.

It appears to be part of an object’s attributes, when an object is included in a named selection set, I see this in Properties>Details:

image

And I find this if I dive down into the object’s attributes (rhobj>Attributes>UserData)

But I don’t see how to access any of this data from the info in the API docs…

3 posts - 3 participants

Read full topic

Rotate multiple text objects

$
0
0

Hello,
I am using Rhino 6 to prepare nesting files to cut Aluminium sheets of 6x2 meters and we are able to print text on these plates, but only 0-90-180-270 degrees. A typical sheet has +/- 100 texts in all different orientations.
I would like to be able to rotate all these text objects with different angles to 0-90-180-270 degrees , which ever is the nearest (so max. 45°), around the centre of each text object.

Is there a way to do this with a command or maybe a Macro?
Thanks in advance for helping out.

Gr. Willem-Jan

4 posts - 3 participants

Read full topic

Rhinopython report error

$
0
0

Hi guys, I am a beginner of rhino python.
I tried to use python to generate a polygon, but the script didn’t work well and report the following error.I have no idea which part of my script wrong. Could someone tell me how to solve the problem?


Runtime error (ValueErrorException): Could not convert a9ae2f78-a453-43f8-866f-8fb7621657c2 to a list of points

Here is my file:fenxing.py (542 Bytes)

6 posts - 4 participants

Read full topic

Rhino 7.0 Plug in compiler

$
0
0

In Rhino V7 how do you create a Rhino installation file for a plug in ? in previous versions of the compiler we used to get asked if we wanted an installation file but no choice in V7.

I have compiled my scripts and created a RUI file but now want to add some INI files with data but I dont have an installation file from which I can change the file extension to ZIP and add my files into as we used and suggested in Rhino documentation. I do have a YAK file but not sure what that does any assistance appreciated.

1 post - 1 participant

Read full topic


Determine the size of a detail view

$
0
0

Hi and Happy New Year,

Is there a way to determine the actual size of a detail view in a layout. The size of the view as if you were to measure it.

Thanks in advance,

Eric

2 posts - 2 participants

Read full topic

Rhino Command Script

$
0
0

Hello, I just started writing scripts and I thought it would be good to see the scripts of rhino commands to learn better. Is there a way to view the script for these commands?
Thanks in advance

1 post - 1 participant

Read full topic

Python not able to find existing file?

$
0
0

Hello all,

I have a whole load of files where a particular layer has to be deleted and placed into a new folder as a DXF. The odd thing is I had it working perfectly earlier however when I went back to run it I noticed the command line was full of errors saying the file could not be found, but stranger than that, a copy of all my files were made in the destination folder and the desired files with the removed layers were left in the origin folder.

So the code I used was:

import os
import rhinoscriptsyntax as rs
import Rhino

path = rs.BrowseForFolder()
saveloc = rs.BrowseForFolder()
layer = "Layer 01"
extension = ".dxf"

# Create file list
files = [f for f in os.listdir(path)]
#print(files)


for each in files:
    #path = each;
    rs.DocumentModified(False)
    rs.Command('_-Open {} _Enter'.format(each))
    if layer: rs.PurgeLayer(layer)
    file = '"' + saveloc + "\\" + each +'"'
    #rs.Command('_SelAll -Export {} _Enter'.format(path))
    rs.Command("_SelAll _-Export {} _Enter".format(file))

So it seems to me the file path is identical to the location of the file - am I missing something here?

Thanks in advance,

Sash

7 posts - 3 participants

Read full topic

Create Surface from Points in Rhino Python, Message: expected IEnumerable[Point3d], got list

$
0
0

I am trying to create a surface in rhino from points (x,y,z) usually from 3 or 4 for a surface from a citygml file. After a lot of research I found AddPlanarSrf() method does this job from curves, but not all the surfaces of buildings in citygml are planar. some of the curves created from these points are non planar, So I got some null surfaces. I researched for another method to do the same task. But this time, I used AddSrfControlPtGrid() but it gives me errors like
image

Can someone please guide me with this? how to create surfaces from points in general using rhino python

4 posts - 2 participants

Read full topic

Append text to end of selected layer

$
0
0

I want to create a button that will add some text to the end of whichever layer is highlighted.

Keyshot lets you apply materials by layer using an automated tool based on layer name. So I figured that would help speed up how layers are named.
Select the layer, click my “chrome” button and it adds “_chrome” to the end of that layer. Select next layer and click my “chrome rough” button and it adds “_chromeRough” to the end of that layer.
Just a couple examples. I’d make a Bunch of buttons to apply common names.

I’m not sure where to start with that.

1 post - 1 participant

Read full topic

Viewing all 5797 articles
Browse latest View live