def AlignedLines(): """Aligned Lines This is a classic optical illusion. Straight lines can appear to be shifted when only a tilted part is visible. """ resetview() a = 60. lines = Formex('l:1').scale([20, 1, 0]).rotate(a).translate( [-20. * cos(a * pi / 180.), 0, 0]).replic(32, 1) lines = lines.cutWithPlane([-1, 0, 0], [1, 0, 0], side='+').cutWithPlane([22, 0, 0], [1, 0, 0], side='-') mask = Formex('4:0123').scale([1, 20. * sin(a * pi / 180.), 1]).replic(11, 2) mask.setProp(6) savedelay = pf.GUI.drawwait draw(mask, color=random.rand(3)) delay(2) draw(lines, linewidth=2) for i in range(3): wait() renderMode('wireframe') wait() renderMode('flat') delay(savedelay)
def Cussion(): """Cussion This is a powerful illusion, though again some color combinations might not work as well as others. The smaller squares on this 'chessboard' tend to give a distortion. Again, all horizontal and vertical lines are perfectly parallel and straight! """ resetview() b, h = 17, 17 if b % 2 == 0: b += 1 if h % 2 == 0: h += 1 chess = Formex('4:0123').replic2(b, h, 1, 1).translate( [-b / 2 + 0.5, -h / 2 + 0.5, 0]) col = [random.rand(3), random.rand(3)] sq1 = Formex('4:0123').scale([0.25, 0.25, 1]).translate([-0.45, 0.2, 0]) sq2 = Formex('4:0123').scale([0.25, 0.25, 1]).translate([0.2, -0.45, 0]) F = sq1.translate([1, 0, 0]).replic(int(b / 2) - 1, 1) + sq2.translate( [0, 1, 0]).replic(int(h / 2) - 1, 1, dir=1) sq = sq1 + sq2 for i in range(int(b / 2)): for j in range(int(h / 2)): if i + j < (int(b / 2) + int(b / 2)) / 2 - 1: F += sq.translate([i + 1, j + 1, 0]) colors = ndarray([0, 0]) for i in F: if (int(i[0, 0]) + int(i[0, 1]) - 1) % 2 == 0: colors = append(colors, col[1]) else: colors = append(colors, col[0]) colors = colors.reshape(-1, 3) F = F.rosette(4, 90) draw(F, color=colors.reshape(-1, 3)) draw(chess, color=col)
def RunningInCircles(): """Running In Circles If you don't look directly at the rectangles, both rectangles will appear to 'overtake' each other constantly, although they are moving at equal and constant speed. """ resetview() box = [[-8, -8, -8], [8, 8, 8]] N = 72 R = 10 C = circle(a1=360. / N).points() O = [0, 0, 0] F = Formex([[C[i], C[i + 1], O] for i in arange(0, 2 * N, 2)]).scale([R, R, 0]) F.setProp([0, 7]) p = circle(a1=360. / N).points() centre = Formex([add(p[0:len(p):2], p[-1])]).translate([-1, 0, 0]) centre.setProp(1) draw(centre, bbox=box) draw(F, bbox=box) b1 = Formex('4:0123').scale([1.5, 0.8, 0]).translate([0, 8.5, 0.1]) b1.setProp(3) b2 = Formex('4:0123').scale([1.5, 0.8, 0]).translate([0, 7, 0.1]) b2.setProp(6) b = b1 + b2 col = [random.rand(3) / 3, [1, 1, 1] - random.rand(3) / 8] for i in range(4 * N): b = b.rotate(360. / N / 4) dr = draw(b, bbox=box, color=col) if i > 0: undraw(DR) DR = dr
def ShadesOfGrey(): """Shades Of Grey Our perception of brightness is relative. Therefore, the figure on the left looks a little darker than the one right. The effect can be somewhat subtle though. """ resetview([0.8, 0.8, 0.8]) sc = 2 box = [[-2, 0, -2], [2, 8, 2]] back = Formex('4:0123').scale([8, 8, 1]) back += back.translate([-8, 0, 0]) back.setProp([0, 7]) C = circle(a1=11.25).rotate(-90, 2).points() F = Formex([[C[i], C[i + 1], 2 * C[i + 1], 2 * C[i]] for i in range(0, 32, 2)]).translate([2, 4, 0]) n = 40 for i in range(n): F = F.translate([-2. / n, 0, 0]) G = F.reflect(0) dr1 = draw(F + G, color=[0.6, 0.6, 0.6], bbox=box) dr2 = draw(back, bbox=box) if i > 0: undraw(DR2) undraw(DR1) else: sleep(2) DR1 = dr1 DR2 = dr2
def create(): """Create a closed surface and a set of points.""" nx, ny, nz = npts # Create surface if surface == 'file': S = TriSurface.read(filename).centered() elif surface == 'sphere': S = simple.sphere(ndiv=grade) if refine > S.nedges(): S = S.refine(refine) draw(S, color='red') if not S.isClosedManifold(): warning("This is not a closed manifold surface. Try another.") return None, None # Create points if points == 'grid': P = simple.regularGrid([-1., -1., -1.], [1., 1., 1.], [nx-1, ny-1, nz-1]) else: P = random.rand(nx*ny*nz*3) sc = array(scale) siz = array(S.sizes()) tr = array(trl) P = Formex(P.reshape(-1, 3)).resized(sc*siz).centered().translate(tr*siz) draw(P, marksize=1, color='black') zoomAll() return S, P
def RotatingCircle(): """Rotating Circle When staring at the cross in the middle, the disappearing magenta circles create the illusion of a green rotating circle. If you keep concentrating your gaze on the centre, the green circle wil seem to devour the magenta circle, up to a point where you no longer see the magenta circles. Blinking or changing your focus will immediately undo the effect. """ resetview([0.8, 0.8, 0.8]) ask = askItems([('Number of circles', 12), ('Radius of circles', 1.2), ('Radius of the figure', 12), ('Number of rotations', 16), ('color of circles', [1.0, 0.40, 1.0]), ('Sleep time', 0.03), ('Zoom', 14.)]) if not ask: return N = ask['Number of circles'] r = ask['Radius of circles'] R = ask['Radius of the figure'] n = ask['Number of rotations'] col = ask['color of circles'] sl = ask['Sleep time'] sc = ask['Zoom'] box = [[-sc, -sc, -sc], [sc, sc, sc]] draw(shape('plus'), bbox=box) F = sector(r, 360., 1, 16).trl(0, R).rosette(N - 1, 360. / N) delay(sl) for i in range(n * N): F = F.rotate(-360. / N) dr = draw(F, color=col, bbox=box) if i > 0: undraw(DR) DR = dr
def run(): clear() flat() reset() examples = { 'Square': square_example, 'Rectangle': rectangle_example, 'Circle': circle_example, 'CloseLoop': close_loop_example, } res = askItems([ _I('example', text='Select an example', choices=examples.keys()), ]) if res: F = examples[res['example']]() if F is None: return draw(F) S = sectionChar(F) S.update(extendedSectionChar(S)) print(mydict.CDict(S)) G = Formex([[[S['xG'], S['yG']]]]) draw(G, bbox='last') showaxes([S['xG'], S['yG'], 0.], S['alpha'], F.dsize(), 'red')
def run(): items = [ widgets.simpleInputItem(n, globals()[n]) for n in ['r0', 'r1', 'h', 't', 'nr', 'nt'] ] + [ widgets.simpleInputItem( 'diag', diag, itemtype='radio', choices=['', 'u', 'd']) ] dialog = widgets.InputDialog(items) while not dialog.result() == widgets.TIMEOUT: res = dialog.getResults() if not res: break globals().update(res) F = cone(r0, r1, h, t, nr, nt, diag) G = cone1(r0, r1, h, t, nr, nt, diag).swapAxes(1, 2).trl(0, 2 * max(r0, r1)) G.setProp(1) H = F + G clear() smoothwire() draw(H) return
def run(): global barrel reset() wireframe() res = askItems([ dict(name='m', value=10, text='number of modules in axial direction'), dict(name='n', value=8, text='number of modules in tangential direction'), dict(name='r', value=10., text='barrel radius'), dict(name='a', value=180., text='barrel opening angle'), dict(name='l', value=30., text='barrel length'), ]) if not res: return globals().update(res) # Diagonals d = Formex('l:5', 1).rosette(4, 90).translate([1, 1, 0]).replic2(m, n, 2, 2) # Longitudinals h = Formex('l:1', 3).replic2(2*m, 2*n+1, 1, 1) # End bars e = Formex('l:2', 0).replic2(2, 2*n, 2*m, 1) # Create barrel barrel = (d+h+e).rotate(90, 1).translate(0, r).scale([1., a/(2*n), l/(2*m)]).cylindrical() draw(barrel)
def series(): view='iso' for n in [3, 4, 6, 8, 12]: for m in [3, 4, 6, 12, 36]: clear() draw(torus(m, n), view) view=None
def run(): reset() smoothwire() res = askItems([ dict(name='m', value=12, text='number of modules in axial direction'), dict(name='n', value=8, text='number of modules in tangential direction'), dict(name='r', value=10., text='barrel radius'), dict(name='a', value=180., text='barrel opening angle'), dict(name='l', value=30., text='barrel length'), dict(name='eltype', value='quad8', text='element type', itemtype='radio', choices=['tri3', 'quad4', 'quad8', 'quad9']), ]) if not res: return globals().update(res) # Grid g = Formex('4:0123').replic2(m, n).toMesh().convert(eltype) # Create barrel barrel = g.rotate(90, 1).translate(0, r).scale([1., a/n, l/m]).cylindrical() draw(barrel, color=red, bkcolor=blue) export({'Barrel':barrel})
def sliceBranch(S, cp, s0, s1, cl, nslices): """Slice a single branch of the bifurcation - `S`: the bifurcation surface, oriented parallel to xy. - `cp` : the center of the bifurcation. - `s0`, `s1`: the control polylines along the branch. - `cl`: the centerline of the branch. - `nslices`: the number of slices used to approximate the branch surface. """ visual = drawOption('visual') cl = cl.approx(nseg=nslices) s0 = s0.approx(nseg=nslices) s1 = s1.approx(nseg=nslices) h0 = slicer(S, s0, cl, cutat=-1, visual=visual) if visual: clear() draw(h0, color='black') h1 = slicer(S, cl, s1, cutat=-1, visual=visual) # if visual: # draw(h0,color='red') # draw(h1,color='blue') return [h0, h1]
def run(): reset() clear() smooth() transparent() bgcolor(white) view('right') # Create some geometrical objects objects = createGeometry() # make them available in the GUI export([(obj.attrib.name, obj) for obj in objects]) # draw the objects draw(objects) zoomAll() # export to WebGL camera = pf.canvas.camera print("Camera focus: %s; eye: %s" % (camera.focus, camera.eye)) fn = exportWebGL('Scene1', title='Two spheres and a cone', jsheader='// Created by pyFormex WebGL example', cleanup=True) if fn and ack("Show the model in your browser?"): showHTML(fn)
def run(): global dialog, F, G clear() smooth() view('iso') F = cylinder(L=8., D=2., nt=36, nl=20, diag='u').centered() F = TriSurface(F).setProp(3).close( method='planar').fixNormals().fuse().compact() G = F.rotate(90., 0).trl(0, 1.).setProp(1) export({'F': F, 'G': G}) draw([F, G]) _items =\ [ _I('op', text='Operation', choices=[ '+ (Union)', '- (Difference)', '* Intersection', 'Intersection Curve', ]), _I('split', False, text='Split along intersection'), _I('verbose', False, text='Show stats'), ] _enablers = [ ('op', '+ (Union)', 'split'), ('op', '- (Difference)', 'split'), ('op', '* Intersection', 'split'), ] dialog = Dialog(items=_items, enablers=_enablers, actions=[('Close', close), ('Show', show)], default='Show') dialog.timeout = timeOut dialog.show()
def run(): m = 36 # number of cells along torus big circle n = 36 # number of cells along torus small circle print("Create a triangle with three colored members") F = Formex('l:164', [1, 2, 3]) clear() draw(F) pause() print("Replicate it into a rectangular pattern") F = F.replic2(m, n, 1, 1) clear() draw(F) pause() print("Fold the rectangle into a tube") G = F.translate(2, 1).cylindrical([2, 1, 0], [1., 360. / n, 1.]) clear() draw(G, view='right') pause() print("Bend the tube into a torus with mean radius 5") H = G.translate(0, 5).cylindrical([0, 2, 1], [1., 360. / m, 1.]) clear() draw(H, view='iso') pause() print("Cut a part from the torus") K = H.cutWithPlane([0., 2., 0.], [1., 1., 1.], side='-') clear() draw(K)
def run(): reset() smooth() lights(True) S = TriSurface.read(getcfg('datadir')+'/horse.off') SA = draw(S) res = askItems([ ('direction', [1., 0., 0.]), ('number of sections', 20), ('color', 'red'), ('ontop', False), ('remove surface', False), ]) if not res: return d = res['direction'] n = res['number of sections'] c = res['color'] slices = S.slice(dir=d, nplanes=n) linewidth(2) draw(slices, color=c, view=None, bbox='last', nolight=True, ontop=res['ontop']) export({'_HorseSlice_slices':slices}) if res['remove surface']: undraw(SA) zoomAll()
def testInside(S, P, method, nproc, atol): """Test which of the points P are inside surface S""" print("Testing %s points against %s faces" % (P.nelems(), S.nelems())) bb = bboxIntersection(S, P) drawBbox(bb, color=array(red), linewidth=2) P = Coords(P).points() t = timer.Timer() if method == 'vtk' and not utils.hasModule('vtk'): warning("You need to install python-vtk!") return if nproc == 1: ind = inside(S, P, method, atol) else: datablocks = splitar(P, nproc) datalen = [0] + [d.shape[0] for d in datablocks] shift = array(datalen[:-1]).cumsum() #print("METH %s" % method) tasks = [(inside, (S, d, method, atol)) for d in datablocks] ind = multitask(tasks, nproc) ind = concatenate([ i+s for i, s in zip(ind, shift)]) print("%sinside: %s points / %s faces: found %s inside points in %s seconds" % (method, P.shape[0], S.nelems(), len(ind), t.seconds())) if len(ind) > 0: draw(P[ind], color=green, marksize=3, ontop=True, nolight=True, bbox='last')
def query_point2D(color=0): """2D point coordinates based on current camera It prints the horizontal and vertical positions from the global origin along the horizontal and vertical directions of the camera. The horizontal direction of the camera is the cross product of camera axis (focus-eye) and camera upvector. The vertical direction of the camera is the upvector. Push on ESC to terminate, otherwise it repeats. """ D = [] while True: col = mycolor(color) drawopt = dict(color=col,bbox='last', view=None) P = create_point() if isNoneOrEmpty(P): undraw(D) break p, CS = toCameraCS(P) b, c, d = p[0]*CS.u, p[0]*CS.u + p[1]*CS.v, p[1]*CS.v s = "*** Point 2D report ***\n" s += 'H %f V %f'%(p[0], p[1]) cprint (s, color=col) # print in color on pyFormex message board D+=[ draw(P, **drawopt), draw(Formex([[CS.o, b], [b, c], [c, d], [d, CS.o]]), **drawopt), drawMarks([b*0.5, d*0.5], ['%.2e'%p[0], '%.2e'%p[1]], size=20, mode='smooth',**drawopt) # smooth is needed for drawMarks ] color+=1
def showDeformation(): clear() linewidth(1) draw(F, color=black) linewidth(3) deformed_plot(optimscale) view('last', True)
def run(): # multiple viewports is currently broken #layout(2) wireframe() # draw in viewport 0 #viewport(0) view('front') clear() rtri = Formex('3:016932').scale([1.5, 1, 0]) F = rtri + rtri.shear(0, 1, -0.5).trl(0, -4.0) + rtri.shear( 0, 1, 0.75).trl(0, 3.0) draw(F) drawCircles(F, triangleCircumCircle, color=red) zoomAll() drawCircles(F, triangleInCircle, color=blue) drawCircles(F, triangleBoundingCircle, color=black) zoomAll() # draw in viewport 1 #viewport(1) pause() view('iso') clear() F = cube_tri() draw(F) drawCircles(F, triangleInCircle) zoomAll()
def drawCSys(ax=Formex([[[1., 0., 0.]], [[0., 1., 0.]], [[0., 0., 1.]], [[0., 0., 0.]]]), color='black'): """it draws the coordinate system with origin in ax[0] and directions determined by the 3 points in ax[1:4]""" assex=array([ax[3], ax[0]]) assey=array([ax[3], ax[1]]) assez=array([ax[3], ax[2]]) for asse in [assex, assey, assez]:draw(Formex(asse.reshape(1, 2, 3)), color=color) drawNumbers(Formex([assex[1], assey[1], assez[1] ]))#
def createScene(text=None,caged=True,color=None,move=0): """Create a scene of the story. The scene draws the horse (H), with the specified color number (0..7), caged or not, with the local axes (CS), and possibly a text. If move > 0, the horse moves before the scene is drawn. The horse and cage actors are returned. """ global line, H, C, CS if move: H, C, CS = [ i.rotate(30, 1).rotate(-10., 2).translate([0., -move*0.1, 0.]) for i in [H, C, CS] ] if caged: cage = draw(C, mode='wireframe', wait=False,) else: cage = None if color is None: color = 1 + random.randint(6) H.setProp(color) horse = draw(H) if text: drawText(text, (20, line), size=20) line += line_inc * len(text.split('\n')) drawAxes(CS, size=0.5, psize=0.0) zoomAll() zoom(0.5) return horse, cage
def drawCrossSplines(): sp = getData('cross_splines') if drawOption('fill_cross'): [draw(Formex([si.coords for si in s]), color='black', flat=True, alpha=1) for s in sp] else: [draw(s, color=c, flat=True, alpha=1) for s, c in zip(sp, color_half_branch)] if drawOption('numbers'): [[drawNumbers(si.coords) for si in s] for s in sp]
def drawTransform(transform): print("Transforming grid") trf = transforms[transform] G = trf(F) clear() print("Drawing Colored grid") draw(G, color=color, colormap=colortable) drawText('Created with pyFormex', (20, 20), size=24)
def icon_wirenone(): view('front') F = rectangle(2, 2) draw(F, color=red) smooth() zoomAll() zoomIn() zoomIn()
def run(): clear() flat() palette = pf.canvas.settings.colormap ncolors = len(palette) F = Formex('4:0123').replic2(ncolors//2, 2).setProp(arange(ncolors)) G = Formex('4:0123').replic2(ncolors+1, ncolors-1).setProp(arange(ncolors)) draw(align([F, G], '|00', offset=[1., 0., 0.]))
def drawChanges(self): """Draws old and new version of a Formex with different colors. old and new can be a either Formex instances or names or lists thereof. old are drawn in yellow, new in the current color. """ self.draw() draw(self.values, color='yellow', bbox=None, clear=False, shrink=self.shrink, wait=False)
def showCube(base, color): if base == 'Triangle': cube = cube_tri else: cube = cube_quad cube = cube(color) draw(cube,clear=True) export({'cube':cube})
def icon_wireall(): view('front') F = rectangle(2, 2) draw(F, color=red, linewidth=2) smoothwire() zoomAll() zoomIn() zoomIn()
def run(): # Locate calpy and load interface from pyformex.plugins import calpy_itf try: Q = calpy_itf.QuadInterpolator except: print("NO CALPY: I'm out of here!") return # Now, let's create a grid of 'quad8' elements # size of the grid nx, ny = 4, 3 # plexitude nplex = 8 clear() flatwire() M = Formex('4:0123').replic2(nx, ny).toMesh().convert('quad%s' % nplex, fuse=True) #draw(M,color=yellow) # Create the Mesh interpolator gprule = (3, 1) # integration rule: minimum (1,1), maximum (5,5) Q = calpy_itf.QuadInterpolator(M.nelems(), M.nplex(), gprule) # Define some random data at the GP. # We use 3 data per GP, because we will use the data directly as colors ngp = prod(gprule) # number of datapoints per element data = random.rand(M.nelems(), ngp, 3) print("Number of data points per element: %s" % ngp) print("Original element data: %s" % str(data.shape)) # compute the data at the nodes, per element endata = Q.GP2Nodes(data) print("Element nodal data: %s" % str(endata.shape)) # compute nodal averages nodata = Q.NodalAvg(M.elems + 1, endata, M.nnodes()) print("Average nodal data: %s" % str(nodata.shape)) # extract the colors per element colors = nodata[M.elems] print("Color data: %s" % str(colors.shape)) layout(2) viewport(0) clear() smoothwire() lights(False) draw(M, color=endata) drawNumbers(M.coords) drawText("Per element interpolation", (20, 20)) viewport(1) clear() smoothwire() lights(False) draw(M, color=colors) drawNumbers(M.coords) drawText("Averaged nodal values", (20, 20))