Skip to content

Instantly share code, notes, and snippets.

@bengolder
Created October 26, 2012 16:37
Show Gist options
  • Save bengolder/3959792 to your computer and use it in GitHub Desktop.
Save bengolder/3959792 to your computer and use it in GitHub Desktop.
Automating make2ds in rhino 5 using python
import random
import os
from rhinopythonscripts.LayerTools import *
from rhinopythonscripts.PickleTools import *
from rhinopythonscripts.IllustrationTools import *
from rhinopythonscripts.FileTools import *
from rhinopythonscripts.GeomTools import *
from scriptcontext import doc
layers = [
#'benchmeshes',
#'canopybreps',
#'benchsolids',
#'groundsurface',
#'groundchunk',
#'drainareamesh',
#'fullterrainmesh',
#'activebusstops',
#'siteoutline',
#'drainarrows',
#'billboards',
'drainareaoutlines',
#'hardscapeputlines',
#'parcels',
#'hardscapemesh'
#'accessedges',
#'pathsourcepins',
#'pathdestpin',
#'pathways',
#'weightedhardscapecircles',
#'hardgriddots',
#'benchlines',
#'benchradii',
#'bigcontours',
#'smallcontours',
#'draincurves',
#'plantgriddots',
#'weightedplantingcircles',
#'plantwindow1point5',
#'plantwindow3point0',
#'plantwindow4point5',
#'plantwindow6point0',
#'plantwindow7point5',
#'plantwindow8point0',
#'plantwindow9point5',
#'plantwindow12point0',
#'plantwindow15point0',
#'plantwindow18point0',
]
def crossMatch(iter1, iter2):
pairs = []
for n in iter1:
for m in iter2:
pair = (n, m)
pairs.append(pair)
return pairs
def frustumX():
view = doc.Views.ActiveView.ActiveViewport
near = view.GetNearRect()
far = view.GetFarRect()
pairs = crossMatch( near, far )
crvs = []
for pair in pairs:
crvs.append(Rhino.Geometry.Curve.CreateControlPointCurve(pair, 1))
return crvs
def pt(p):
return (p.X,p.Y,p.Z)
def tol(p0, p1, tol):
return p0.DistanceTo(p1) <= tol
def find_rectangles():
f = Rhino.DocObjects.ObjectEnumeratorSettings()
f.VisibleFilter = True
f.ObjectTypeFilter = Rhino.DocObjects.ObjectType.Curve
objs = doc.Objects.FindByFilter(f)
possibles = []
if objs:
for obj in objs:
g = obj.Geometry
if isinstance(g, Rhino.Geometry.NurbsCurve):
if g.IsPolyline():
if is_perfect_rectangle(g):
possibles.append(obj)
return possibles
def is_perfect_rectangle(geom, t=0.01):
print 'testing', geom
bbox = geom.GetBoundingBox(True)
pt0 = bbox.Min
pt1 = bbox.Max
pts = [geom.Points[i].Location for i in range(geom.Points.Count)]
has0 = False
has1 = False
for p in pts:
has0 = tol(p, pt0, t)
has1 = tol(p, pt1, t)
print 'has min:', has0
print 'has max:', has1
return has0 and has1
def rcmd(commandstring, echo=True, mask=True):
if mask:
premask = '-_%s '
try:
cmd = premask % commandstring
except:
print commandstring, 'failed to mask'
else:
cmd = commandstring
result = Rhino.RhinoApp.RunScript(cmd, echo)
if not result:
print 'The following command failed:'
print ' ',cmd
return result
def rcmds(commands, echo=True, mask=True):
for cmd in commands:
rcmd( cmd, echo, mask )
def formatCmd( tup ):
if tup[1]:
return tup[0] % tup[1]
else:
return tup[0]
def yn(boolean):
if boolean:
return 'Yes'
else:
return 'No'
def make2d(referenceLayer='ViewportFramework', hidden=False, viewRect=True,
maintainLayers=True):
frustumLines = frustumX()
att = LayerTools.layerAttributes(referenceLayer, System.Drawing.Color.Cyan )
bakeMany( frustumLines, att)
mask = 'Make2D DrawingLayout=CurrentView ShowTangentEdges=No CreateHiddenLines=%s ShowViewRectangle=%s MaintainSourceLayers=%s'
m2d = mask % (yn(hidden), yn(viewRect), yn(maintainLayers))
cmds = [
'SelAll',
'%s Enter' % m2d,
'Invert Delete SetView World Top',
'ZE',
'SelNone',
]
reflayers = [referenceLayer]
reflayers.append('Make2D::visible::lines::%s' % referenceLayer)
if hidden:
reflayers.append('Make2D::hidden::lines::%s' % referenceLayer)
for r in reflayers:
cmds.append('SelLayer %s' % r)
cmds.append('ZS')
rcmds( cmds, False )
return reflayers
def zoomToFirstMake2dLayer():
rcmd('SelNone')
# first try grabbing Default
obj = doc.Objects.FindByLayer('Default')
# if nothing is on Default ...
print obj
if not obj:
# look for the viewport rectangle
possible = find_rectangles()
print 'possible rectangle', possible
for pos in possible:
doc.Objects.Select(pos.Id, True)
pos.CommitChanges()
print 'selected?', pos.IsSelected(False)
# find the first make2d layer
i = 1
while not obj and i < 7:
bname = doc.Layers[i].Name
layer = 'Make2D::visible::lines::%s' % bname
newlay = doc.Layers[doc.Layers.FindByFullPath(layer, True)]
obj = doc.Objects.FindByLayer(newlay)
print i, bname,layer, obj
i+= 1
else:
layer = 'Default'
cmds = [
#'SelNone',
#'SelLayer %s' % layer,
'ZS',
]
rcmds(cmds, False)
def cleanUp():
# get everything that is selected
geoms = doc.Objects.GetSelectedObjects(False, False)
# make a bounding box for selected items
bbox = Rhino.Geometry.BoundingBox.Empty
for geom in geoms:
bbox = Rhino.Geometry.BoundingBox.Union(bbox, geom.Geometry.GetBoundingBox(False))
p = bbox.Min
#print p
orienter = Rhino.Geometry.Vector3d(-p.X,-p.Y,0.0)
# get everything outside the bounding box
visible = Rhino.DocObjects.ObjectEnumeratorSettings()
visible.VisibleFilter = True
allitems = doc.Objects.FindByFilter(visible)
guids = []
for item in allitems:
if not bbox.Contains(item.Geometry.GetBoundingBox(True).Center):
guids.append(item.Id)
#print 'deletable objects:', len(guids)
rcmd('SelNone', False)
doc.Objects.Delete(guids, True)
allitems = doc.Objects.FindByFilter(visible)
#print orienter
for thing in allitems:
thing.Geometry.Translate(orienter)
thing.CommitChanges()
rcmd('ZE', False)
if __name__=='__main__':
sample = [195,110,667,424,195,537,468,197,652,264,68,286,320,696,288]
ids = range(1,767)
random.shuffle(ids)
#for n in [123]:
for n in ids[:1]:
setView('/amigos/db/%sview' % n)
deleteAll()
rcmd('Purge Enter', False)
print 'running %s' % n
for layer in layers:
dbfile = '/amigos/db/%s%s' % (n, layer)
if layer == 'benchsolids':
vect = Rhino.Geometry.Vector3d(0.0,0.0,0.05)
elif 'contour' in layer:
vect = Rhino.Geometry.Vector3d(0.0,0.0,0.1)
else:
vect=None
bakePickle(dbfile, layerAttributes(layer), vect)
#exportMask = '/amigos/exports/%s%s.ai' % (n, 'drainoutline')
#reflayers = make2d()
#cleanUp()
#rcmd('SelAll', False)
#selecteds = list(doc.Objects.GetSelectedObjects(False, False))
#if len(selecteds):
#exportFile(exportMask)
#setView('/amigos/db/%sview' % n)
#exportLayers(layers, exportMask)
@ThreePointSquare
Copy link

ThreePointSquare commented Nov 17, 2021

Hello! I was starting to look at this code more in depth and noticed the rhinopythonscripts that this imports from doesn't have the IllustrationTools or Pickle Tools in it, any chance you can share those?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment