Exemplo n.º 1
0
    def build_keyboard(self):
        
        if self.verbose: print('Building Keyboard..')
        nts = ("C","D","E","F","G","A","B")
        tol = 0.12
        keybsize = 16.5 # in cm, span of one octave
        wb = keybsize/7
        nr_octaves = 7
        span = nr_octaves*wb*7
    
        self.vp = Plotter(title='PianoPlayer '+__version__, axes=0, size=(1400,700), bg='lb', verbose=0)

        #wooden top and base
        self.vp.box(pos=(span/2+keybsize, 6,  1), length=span+1, height=3, width= 5, texture='wood5') #top
        self.vp.box(pos=(span/2+keybsize, 0, -1), length=span+1, height=1, width=17, texture='wood5')
        self.vp.text('PianoPlayer '+__version__, pos=(18, 5.5, 2), depth=.7)
        self.vp.text('https://github.com/marcomusy/pianoplayer', pos=(105,4.8,2), depth=.7, s=.8)
        leggio = self.vp.box(pos=(span/1.55,8,10), length=span/2, height=span/8, width=0.08, c=(1,1,0.9))
        leggio.rotateX(-20)
        self.vp.text('Playing\n\n'+self.songname, s=1.2).rotateX(70).pos([49,11,9])

        for ioct in range(nr_octaves):
            for ik in range(7):              #white keys
                x  = ik * wb + (ioct+1)*keybsize +wb/2
                tb = self.vp.box(pos=(x,-2,0), length=wb-tol, height=1, width=12, c='white')
                self.KB.update({nts[ik]+str(ioct+1) : tb})
                if not nts[ik] in ("E","B"): #black keys
                    tn=self.vp.box(pos=(x+wb/2,0,1), length=wb*.6, height=1, width=8, c='black')
                    self.KB.update({nts[ik]+"#"+str(ioct+1) : tn})
        self.vp.show(interactive=0)
        self.vp.camera.Azimuth(4)
        self.vp.camera.Elevation(-30)
Exemplo n.º 2
0
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        self.setupUi(self)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        self.vtkLayout.addWidget(self.vtkWidget)

        self.plt = Plotter(qtWidget=self.vtkWidget, axes=1, bg='white')

        self.plt += load(datadir + 'shark.ply').c('cyan')

        self.plt.show()
Exemplo n.º 3
0
	def render(self):
		""" """

		self.apply_render_style()

		# Create camera and plotter
		if brainrender.WHOLE_SCREEN: 
			sz = "full"
		else: 
			sz = "auto"
		
		if brainrender.SHOW_AXES:
			axes = 4
		else:
			axes = 0

		mv = Plotter(N=2, axes=axes, size=sz, pos=brainrender.WINDOW_POS, bg=brainrender.BACKGROUND_COLOR, sharecam=True)

		actors = []
		for scene in self.scenes:
			scene_actors = scene.get_actors()
			actors.append(scene_actors)
			mv.add(scene_actors)

		mv.show(actors[0], at=0, zoom=1.15, axes=axes, roll=180,  interactive=False)    
		mv.show(actors[1], at=1,  interactive=False)
		interactive()
Exemplo n.º 4
0
    def __init__(self, parent=None):

        Qt.QMainWindow.__init__(self, parent)
        self.frame = Qt.QFrame()
        self.vl = Qt.QVBoxLayout()
        self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
        self.vl.addWidget(self.vtkWidget)

        vp = Plotter(qtWidget=self.vtkWidget, axes=4, bg='white')

        vp += Cone()
        vp.show()      # create renderer and add the actors

        # set-up the rest of the Qt window
        self.frame.setLayout(self.vl)
        self.setCentralWidget(self.frame)

        self.show()    # <--- show the Qt Window
Exemplo n.º 5
0
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        self.setupUi(self)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        self.vtkLayout.addWidget(self.vtkWidget)

        self.plt = Plotter(qtWidget=self.vtkWidget, axes=1, bg='white')

        self.plt += load(datadir + 'shark.ply').c('cyan')

        self.plt.show()

    def onClose(self):
        print(
            "Disable the interactor before closing to prevent it from trying to act on a already deleted items"
        )
        self.vtkWidget.close()
def plot_stl_faces_segmentation(struct_seg1,
                                num_segments1,
                                surface_seg1,
                                vertices,
                                title,
                                noize=None):
    """Функция для прорисовки фасет stl объекта, основанных на цвете по кривизне для каждой фасеты.
       Исключается шум, заданный пользователем
       """
    struct_seg = np.array([])
    num_segments = np.array([])
    surface_seg = []
    if noize is None:
        # Если noize не задано - не надо улалять шум, оставляем структуру как есть
        struct_seg = copy.deepcopy(struct_seg1).astype('int')
        num_segments = copy.deepcopy(num_segments1)
        surface_seg = copy.deepcopy(surface_seg1)
    else:
        idx = np.where(num_segments1 > noize)
        if len(idx[0]) > 0:
            for j in range(len(idx[0])):
                surface_seg.append([])
                t = surface_seg1[idx[0][j]]
                surface_seg[j] = copy.deepcopy(t)
                num_segments = np.append(num_segments,
                                         num_segments1[idx[0][j]])
            struct_seg = np.append(struct_seg, len(idx[0])).astype('int')
        else:
            print('Все участки меньше допуска, рисуем все')
            struct_seg = copy.deepcopy(struct_seg1).astype('int')
            num_segments = copy.deepcopy(num_segments1[0, :])
            surface_seg = copy.deepcopy(surface_seg1)
    vp = Plotter(title=title, interactive=0, axes=0)
    # работа с палитрой
    lab = parula(struct_seg[0])
    for num in range(0, struct_seg[0]):
        mesh = trimesh.Trimesh(vertices=vertices,
                               faces=surface_seg[num],
                               process=False)
        mesh.visual.face_colors = lab[num, :]
        vp += mesh
    vp.show()
Exemplo n.º 7
0
def importWindow(fileinput):
    """Import a whole scene from a Numpy file."""
    import numpy as np
    from vtkplotter import Plotter

    data = np.load(fileinput, allow_pickle=True)[0]

    settings.renderPointsAsSpheres = data['renderPointsAsSpheres']
    settings.renderLinesAsTubes = data['renderLinesAsTubes']
    settings.hiddenLineRemoval = data['hiddenLineRemoval']
    settings.visibleGridEdges = data['visibleGridEdges']
    settings.interactorStyle = data['interactorStyle']

    vp = Plotter(pos=data['position'],
                 size=data['size'],
                 axes=data['axes'],
                 title=data['title'],
                 bg=data['backgrcol'],
                 infinity=data['infinity'],
                 depthpeeling=data['depthpeeling'],
    )
    vp.xtitle = data['xtitle']
    vp.ytitle = data['ytitle']
    vp.ztitle = data['ztitle']
    vp.actors = loadNumpy(data['objects'])
    return vp
Exemplo n.º 8
0
def importWindow(fileinput):
    """Import a whole scene from a Numpy file.
    Return ``Plotter`` instance."""
    from vtkplotter import Plotter

    data = np.load(fileinput, allow_pickle=True,
                   encoding="latin1").flatten()[0]

    if 'renderPointsAsSpheres' in data.keys():
        settings.renderPointsAsSpheres = data['renderPointsAsSpheres']
    if 'renderLinesAsTubes' in data.keys():
        settings.renderLinesAsTubes = data['renderLinesAsTubes']
    if 'hiddenLineRemoval' in data.keys():
        settings.hiddenLineRemoval = data['hiddenLineRemoval']
    if 'visibleGridEdges' in data.keys():
        settings.visibleGridEdges = data['visibleGridEdges']
    if 'interactorStyle' in data.keys():
        settings.interactorStyle = data['interactorStyle']
    if 'useParallelProjection' in data.keys():
        settings.useParallelProjection = data['useParallelProjection']

    axes = data.pop('axes', 4)
    title = data.pop('title', '')
    backgrcol = data.pop('backgrcol', "blackboard")

    vp = Plotter(  #size=data['size'], # not necessarily a good idea to set it
        #shape=data['shape'],
        axes=axes,
        title=title,
        bg=backgrcol,
    )
    vp.xtitle = data.pop('xtitle', 'x')
    vp.ytitle = data.pop('ytitle', 'y')
    vp.ztitle = data.pop('ztitle', 'z')

    if 'objects' in data.keys():
        objs = loadNumpy(data['objects'])
        if not utils.isSequence(objs):
            objs = [objs]
    else:
        colors.printc("Trying to import a that was not exported.", c=1)
        colors.printc(" -> try to load a single object with load().", c=1)
        return loadNumpy(fileinput)
    vp.actors = objs

    #    if vp.shape==(1,1):
    #        vp.actors = loadNumpy(data['objects'])
    #    else:
    #        print(objs, )
    #        for a in objs:
    #            for ar in a.renderedAt:
    #                print(vp.shape, [a], ar )
    #                vp.show(a, at=ar)
    return vp
Exemplo n.º 9
0
def importWindow(fileinput):
    """Import a whole scene from a Numpy file.
    Return ``Plotter`` instance."""
    import numpy as np
    from vtkplotter import Plotter

    data = np.load(fileinput, allow_pickle=True)[0]

    if 'renderPointsAsSpheres' in data.keys():
        settings.renderPointsAsSpheres = data['renderPointsAsSpheres']
    if 'renderLinesAsTubes' in data.keys():
        settings.renderLinesAsTubes = data['renderLinesAsTubes']
    if 'hiddenLineRemoval' in data.keys():
        settings.hiddenLineRemoval = data['hiddenLineRemoval']
    if 'visibleGridEdges' in data.keys():
        settings.visibleGridEdges = data['visibleGridEdges']
    if 'interactorStyle' in data.keys():
        settings.interactorStyle = data['interactorStyle']
    if 'useParallelProjection' in data.keys():
        settings.useParallelProjection = data['useParallelProjection']

    pos = data.pop('position', (0, 0))
    axes = data.pop('axes', 4)
    title = data.pop('title', '')
    backgrcol = data.pop('backgrcol', "blackboard")

    vp = Plotter(
        pos=pos,
        #size=data['size'], # not necessarily a good idea to set it
        #shape=data['shape'],
        axes=axes,
        title=title,
        bg=backgrcol,
    )
    vp.xtitle = data.pop('xtitle', 'x')
    vp.ytitle = data.pop('ytitle', 'y')
    vp.ztitle = data.pop('ztitle', 'z')

    objs = loadNumpy(data['objects'])
    if not utils.isSequence(objs):
        objs = [objs]
    vp.actors = objs

    #    if vp.shape==(1,1):
    #        vp.actors = loadNumpy(data['objects'])
    #    else:
    #        print(objs, )
    #        for a in objs:
    #            for ar in a.renderedAt:
    #                print(vp.shape, [a], ar )
    #                vp.show(a, at=ar)
    return vp
Exemplo n.º 10
0
def demo3d_hanoi(**kwargs):
    nr_disks = kwargs.get("nr_disks", 5)
    interactive = kwargs.get("interactive", 1)

    hanoi = Hanoi(nr_disks)
    tower_states = list([hanoi.towers])
    for _ in hanoi.moves():
        tower_states.append(hanoi.towers)

    vp = Plotter(axes=0, interactive=0, bg="w", size=(800, 600))
    vp.camera.SetPosition([18.5, -20.7, 7.93])
    vp.camera.SetFocalPoint([3.0, 0.0, 2.5])
    vp.camera.SetViewUp([-0.1, +0.17, 0.977])

    cols = makePalette("red", "blue", hanoi.nr_disks + 1, hsv=True)
    disks = {
        hanoi.nr_disks - i: Cylinder(pos=[0, 0, 0],
                                     r=0.2 * (hanoi.nr_disks - i + 1),
                                     c=cols[i])
        for i in range(hanoi.nr_disks)
    }
    for k in disks:
        vp += disks[k]
    vp += Box(pos=(3.0, 0, -.5), length=12.0, width=4.0, height=0.1)
    vp.show(zoom=1.2)

    printc("\n Press q to continue, Esc to exit. ", c="y", invert=1)
    pb = ProgressBar(0, len(tower_states), 1, c="b", ETA=False)
    for t in pb.range():
        pb.print()
        state = tower_states[t]
        for tower_nr in range(3):
            for i, disk in enumerate(state[tower_nr]):
                disks[disk].pos([3 * tower_nr, 0, i + 0.5])
        vp.show(resetcam=0, interactive=interactive, rate=10)
    vp.show(resetcam=0, interactive=1)
Exemplo n.º 11
0
    def __init__(self, parent=None):

        Qt.QMainWindow.__init__(self, parent)
        self.frame = Qt.QFrame()
        self.vl = Qt.QVBoxLayout()
        self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
        self.vl.addWidget(self.vtkWidget)

        vp = Plotter(offscreen=1, interactive=0, axes=2, N=2)

        cn = Cone()
        cc = Cube().pos(1, 1, 1).color("pink")
        ss = Torus()
        vp.show(cn, cc, at=0)
        vp.show(ss, at=1, viewup="z")

        self.start(vp)
Exemplo n.º 12
0
	def export_for_web(self, filepath='brexport.html'):
		"""
			This function is used to export a brainrender scene
			for hosting it online. It saves an html file that can
			be opened in a web browser to show an interactive brainrender scene
		"""
		if not filepath.endswith('.html'):
			raise ValueError("Filepath should point to a .html file")

		# prepare settings
		settings.notebookBackend = 'k3d'
		self.jupyter=True
		self.render()

		# Create new plotter and save to file
		plt = Plotter()
		plt.add(self.get_actors())
		plt = plt.show(interactive=False)

		plt.camera[-2] = -1

		print('Ready for exporting. Exporting scenes with many actors might require a few minutes')
		try:
			with open(filepath,'w') as fp:
				fp.write(plt.get_snapshot())
		except:
			raise ValueError("Failed to export scene for web.\n"+
						"Try updating k3d and msgpack: \ "+
						"pip install -U k3d\n"+
						"pip install -U msgpack")

		print(f"The brainrender scene has been exported for web. The results are saved at {filepath}")
		
		# Reset settings
		settings.notebookBackend = None
		self.jupyter = False
Exemplo n.º 13
0
	def render(self, _interactive=True,  **kwargs):
		"""

		:param _interactive:  (Default value = True)
		:param **kwargs:

		"""
		camera = kwargs.pop("camera", None)

		for scene in self.scenes:
			scene.apply_render_style()
		
			if camera is None: 
				if scene.atlas.default_camera is None:
					scene_camera = brainrender.CAMERA
				else:
					scene_camera = scene.atlas.default_camera
			else:
				if camera:
					scene_camera = camera
				else:
					scene_camera = None
			if scene_camera is not None:
				set_camera(scene, scene_camera)

		if self.N > 4:
			print("Rendering {} scenes. Might take a few minutes.".format(self.N))
		mv = Plotter(N=self.N, axes=4, size="auto", sharecam=True, bg=brainrender.BACKGROUND_COLOR)

		actors = []
		for i, scene in enumerate(self.scenes):
			scene_actors = scene.get_actors()
			actors.append(scene_actors)
			mv.add(scene_actors)

		for i, scene_actors in enumerate(actors):
			mv.show(scene_actors, at=i,  interactive=False)

		print("Rendering complete")
		if _interactive:
			interactive()
Exemplo n.º 14
0
        if vp:
            self.vtk_actor = vp.add(Sphere(
                pos, r=radius, c=color))  # Sphere representing the particle
            # vp.addTrail(alpha=0.4, maxlength=1, n=50)
            # Add a trail behind the particle
            self.vtk_actor.addTrail(alpha=0.4, maxlength=1, n=50)


#####################################################################################################
if __name__ == "__main__":

    # An example simulation of N particles scattering on a charged target.
    # See e.g. https://en.wikipedia.org/wiki/Rutherford_scattering

    vp = Plotter(title="Particle Simulator",
                 bg="black",
                 axes=0,
                 interactive=False)
    vp.camera.Elevation(20)  # Initial camera position
    vp.camera.Azimuth(40)

    vp.add(Cube(c="white").wire(1))  # a wireframe cube

    sim = ParticleSim(dt=5e-6, iterations=200)
    sim.add_particle((-0.4, 0, 0),
                     color="w",
                     charge=3e-6,
                     radius=0.01,
                     fixed=True)  # the target

    positions = np.random.randn(500,
                                3) / 60  # generate a beam of 500 particles
Exemplo n.º 15
0
 to add a sphere and some info is printed.
"""
from vtkplotter import Plotter, printc, Sphere, Text, datadir


##############################################################################
def myfnc(key):
    if not vp.clickedActor or key != "c":
        printc("click an actor and press c.", c="r")
        return
    printc("clicked actor   :", vp.clickedActor.legend(), c=4)
    printc("clicked 3D point:", vp.picked3d, c=4)
    printc("clicked renderer:", [vp.renderer], c=2)

    vp.add(Sphere(pos=vp.picked3d, r=0.005, c="v"))
    vp.show()


##############################################################################

vp = Plotter(verbose=0)

vp.keyPressFunction = myfnc  # make it known to Plotter class

vp.load(datadir + "bunny.obj")

vp.add(Text(__doc__))

printc("\nPress c to execute myfnc()", c=1)
vp.show()
Exemplo n.º 16
0
"""
Example of boolean operations with actors or polydata
"""
print(__doc__)

from vtkplotter import Plotter, booleanOperation, Sphere


# declare the instance of the class
vp = Plotter(shape=(2, 2), interactive=0, axes=3)

# build to sphere actors
s1 = Sphere(pos=[-0.7, 0, 0], c="r", alpha=0.5)
s2 = Sphere(pos=[0.7, 0, 0], c="g", alpha=0.5)

# make 3 different possible operations:
b1 = booleanOperation(s1, "intersect", s2).c('m').legend("intersect")
b2 = booleanOperation(s1, "plus", s2).c("b").wireframe(True).legend("plus")
b3 = booleanOperation(s1, "minus", s2).legend("minus").addScalarBar(c='w')

# show the result in 4 different subwindows 0->3
vp.show(s1, s2, at=0)
vp.show(b1, at=1)
vp.show(b2, at=2)
vp.show(b3, at=3)
vp.show(interactive=1)
Exemplo n.º 17
0
'''
Example usage of align() method:
 generate two random sets of points as 2 actors 
 and align them using the Iterative Closest Point algorithm.
'''
from __future__ import division
from random import uniform as u
from vtkplotter import Plotter, align, Arrow, Text, Points

vp = Plotter(shape=[1, 2], verbose=0, axes=2, bg='w')

N1 = 15  # number of points of first set
N2 = 15  # number of points of second set
x = 1.  # add some randomness

pts1 = [(u(0, x), u(0, x), u(0, x) + i) for i in range(N1)]
pts2 = [(u(0, x) + 3, u(0, x) + i / 2 + 2, u(0, x) + i + 1) for i in range(N2)]

act1 = Points(pts1, r=8, c='b').legend('source')
act2 = Points(pts2, r=8, c='r').legend('target')

vp.show([act1, act2], at=0)

# find best alignment between the 2 sets of Points, e.i. find
# how to move act1 to best match act2
alpts1 = align(act1, act2).coordinates()
vp.add(Points(alpts1, r=8, c='b'))

for i in range(N1):  # draw arrows to see where points end up
    vp.add(Arrow(pts1[i], alpts1[i], c='k', s=0.007, alpha=.1))
Exemplo n.º 18
0
# Extract the mesh region that has the largest connected surface
#
from vtkplotter.analysis import extractLargestRegion
from vtkplotter.utils import area
from vtkplotter import Plotter, printc

vp = Plotter(shape=(2,1))

act1 = vp.load('data/embryo.slc', c='y')
printc('area1 =', area(act1), c='y')

act2 = extractLargestRegion(act1).color('b')
printc('area2 =', area(act2), c='b')

vp.show(act1, at=0)
vp.show(act2, at=1, zoom=1.2, interactive=1)
Exemplo n.º 19
0
Natoms = 400        # change this to have more or fewer atoms
Nsteps = 350        # nr of steps in the simulation
Matom = 4E-3/6E23   # helium mass
Ratom = 0.025       # wildly exaggerated size of helium atom
RingThickness=0.3   # thickness of the toroid
RingRadius=1
k = 1.4E-23         # Boltzmann constant
T = 300             # room temperature
dt = 1E-5
#############################################################

def reflection(p, pos):
    n = norm(pos)
    return np.dot(np.identity(3)-2*n*n[:,np.newaxis], p)

vp = Plotter(title='gas in toroid', verbose=0, axes=0)

vp.add(torus(c='g', r=RingRadius, thickness=RingThickness, alpha=.1, wire=1)) ### <--

Atoms = []
poslist = []
plist, mlist, rlist = [],[],[]
mass = Matom*Ratom**3/Ratom**3
pavg = np.sqrt(2.*mass*1.5*k*T) # average kinetic energy p**2/(2mass) = (3/2)kT

for i in range(Natoms):
    alpha = 2*np.pi*random()
    x = RingRadius*np.cos(alpha)*.9
    y = RingRadius*np.sin(alpha)*.9
    z = 0
    Atoms = Atoms + [vp.add(sphere(pos=(x,y,z), r=Ratom, c=i))]              ### <--
Exemplo n.º 20
0
"""Normal jpg/png pictures can be loaded,
cropped, rotated and positioned in 3D
"""
from vtkplotter import Plotter, datadir

vp = Plotter(axes=3)

for i in range(5):
    p = vp.load(datadir + "images/dog.jpg")  # returns Picture
    p.crop(bottom=0.2)  # crop 20%
    p.scale(1 - i / 10.0).alpha(0.8)  # picture can be scaled in size
    p.rotateX(20 * i).pos(0, 0, 30 * i)  # (can concatenate methods)

vp += __doc__
vp.show()
from vtkplotter import Plotter, Sphere
from vtkplotter.analysis import surfaceIntersection

vp = Plotter()

car = vp.load('data/shapes/porsche.ply', c='gold').alpha(0.1)

s = Sphere(r=4, c='v', alpha=0.1).wire(True)  # color is violet

# Intersect car with Sphere, c=black, lw=line width
contour = surfaceIntersection(car, s, lw=4)

vp.show([car, contour, s], zoom=1.3)
Exemplo n.º 22
0
        if vp:
            self.vtk_actor = vp.add(Sphere(
                pos, r=radius, c=color))  # Sphere representing the particle
            # vp.addTrail(alpha=0.4, maxlength=1, n=50)
            # Add a trail behind the particle
            self.vtk_actor.addTrail(alpha=0.4, maxlength=1, n=50)


#####################################################################################################
if __name__ == "__main__":

    # An example simulation of N particles scattering on a charged target.
    # See e.g. https://en.wikipedia.org/wiki/Rutherford_scattering

    vp = Plotter(title="Particle Simulator",
                 bg="black",
                 axes=0,
                 interactive=False)

    vp += Cube(c="white").wireframe(1)  # a wireframe cube

    sim = ParticleSim(dt=5e-6, iterations=200)
    sim.add_particle((-0.4, 0, 0),
                     color="w",
                     charge=3e-6,
                     radius=0.01,
                     fixed=True)  # the target

    positions = np.random.randn(500,
                                3) / 60  # generate a beam of 500 particles
    for p in positions:
        p[0] = -0.5  # Fix x position. Their charge are small/negligible compared to target:
Exemplo n.º 23
0
Matom = 4E-3 / 6E23  # helium mass
Ratom = 0.025  # wildly exaggerated size of helium atom
RingThickness = 0.3  # thickness of the toroid
RingRadius = 1
k = 1.4E-23  # Boltzmann constant
T = 300  # room temperature
dt = 1.5E-5
#############################################################


def reflection(p, pos):
    n = norm(pos)
    return np.dot(np.identity(3) - 2 * n * n[:, np.newaxis], p)


vp = Plotter(title='gas in toroid', interactive=0, axes=0, bg='w')

vp.add(Text(__doc__))

vp.add(Torus(c='g', r=RingRadius, thickness=RingThickness,
             alpha=.1).wire(1))  ### <--

Atoms = []
poslist = []
plist, mlist, rlist = [], [], []
mass = Matom * Ratom**3 / Ratom**3
pavg = np.sqrt(2. * mass * 1.5 * k *
               T)  # average kinetic energy p**2/(2mass) = (3/2)kT

for i in range(Natoms):
    alpha = 2 * np.pi * random()
Exemplo n.º 24
0
"""
Make a textured floor, a lamp post, and load a mesh of a car
make copies of the car, rotate and move them in a loop.
rate=10 limits the speed of the loop to maximum 10 fps
"""
from __future__ import division, print_function
from vtkplotter import Plotter, Plane, Text, datadir

vp = Plotter(interactive=0, axes=0)

vp.add(Plane(pos=(4, 0, -0.45), sx=12, texture="metalfloor1"))

# load and set its position (methods can be concatenated)
vp.load(datadir + "lamp.vtk").pos([1.7, -0.4, 2])

a = vp.load(datadir + "porsche.ply", c="r").rotateX(90)
a.normalize()  # set actor at origin and scale size to 1

for i in range(1, 10):
    b = a.clone().color("aqua").alpha(0.04 * i)
    b.rotateX(-20 * i).rotateY(-10 * i).pos([i, i / 2, i / 2])
    vp.add(b)  # add actor b
    vp.show(rate=10)  # maximum frame rate in hertz
    print(i, "time:", vp.clock, "s")

vp.add(Text(__doc__))

vp.show(interactive=1)
    grid_reco = clm.expand(lmax=lmax)  # cut "high frequency" components
    agrid_reco = grid_reco.to_array()
    pts = []
    for i, longs in enumerate(agrid_reco):
        ilat = grid_reco.lats()[i]
        for j, value in enumerate(longs):
            ilong = grid_reco.lons()[j]
            th = (90 - ilat) / 57.3
            ph = ilong / 57.3
            r = value + rbias
            p = np.array([sin(th) * cos(ph), sin(th) * sin(ph), cos(th)]) * r
            pts.append(p)
    return pts


vp = Plotter(shape=[2, 2], verbose=0, axes=3, interactive=0)

shape1 = Sphere(alpha=0.2)
shape2 = vp.load('data/shapes/icosahedron.vtk').normalize().lineWidth(1)

agrid1, actorpts1 = makeGrid(shape1, N)
vp.show(at=0, actors=[shape1, actorpts1])

agrid2, actorpts2 = makeGrid(shape2, N)
vp.show(at=1, actors=[shape2, actorpts2])
vp.camera.Zoom(1.2)
vp.interactive = False

clm1 = pyshtools.SHGrid.from_array(agrid1).expand()
clm2 = pyshtools.SHGrid.from_array(agrid2).expand()
# clm1.plot_spectrum2d() # plot the value of the sph harm. coefficients
Exemplo n.º 26
0
# Add a square button with N possible internal states
# to a rendering window that calls an external function.
#
# Available fonts: arial, courier, times
#
from vtkplotter import Plotter, printc

vp = Plotter(shape=(2, 1), axes=4)

act = vp.load('data/shapes/magnolia.vtk', c='v')

vp.show(act, at=0)
vp.show(act, at=1)


# add a button to the current renderer (e.i. nr1)
def buttonfunc():
    act.alpha(1 - act.alpha())  # toggle mesh transparency
    bu.switch()  # change to next status
    printc(bu.status(), box='_', dim=True)


bu = vp.addButton(
    buttonfunc,
    pos=(350, 20),  # x,y pixels from bottom left corner
    states=['press to hide', 'press to show'],
    c=['w', 'w'],
    bc=['dg', 'dv'],  # colors of states
    font='courier',
    size=18,
    bold=True,
Exemplo n.º 27
0
from __future__ import division, print_function
from vtkplotter import Plotter, ProgressBar, vector

vp = Plotter(title='Spring in viscous medium', verbose=0, axes=3)

l_rest = 0.1  # spring x position at rest
x0 = 0.85  # initial x-coordinate of the block
k = 25  # spring constant
m = 20  # block mass
b = 0.5  # viscosity friction (proportional to velocity)
dt = 0.1  # time step

#initial conditions
v = vector(0, 0, 0.2)
x = vector(x0, 0, 0)
xr = vector(l_rest, 0, 0)
sx0 = vector(-0.8, 0, 0)
offx = vector(0, 0.3, 0)

vp.box(pos=(0, -0.1, 0), length=2.0, width=0.02, height=0.5)  #surface
vp.box(pos=(-.82, .15, 0), length=.04, width=0.50, height=0.3)  #wall
block = vp.cube(pos=x, length=0.2, c='t')
spring = vp.helix(sx0, x, r=.06, thickness=.01, texture='metal1')

pb = ProgressBar(0, 500, c='r')
for i in pb.range():
    F = -k * (x - xr) - b * v  # Force and friction
    a = F / m  # acceleration
    v = v + a * dt  # velocity
    x = x + v * dt + 1 / 2 * a * dt**2  # position
Exemplo n.º 28
0
'''
In this example we fit spheres to a region of a surface defined by
N points that are closest to a given point of the surface.
For some of these point we show the fitting sphere.
Red lines join the center of the sphere to the surface point.
Blue points are the N points used for fitting.
Green histogram is the distribution of residuals from the fitting.
Red histogram is the distribution of the curvatures (1/r**2).
Fitted radius can be accessed from actor.info['radius'].
'''
from __future__ import division, print_function
from vtkplotter import Plotter, fitSphere, histogram, Points, Line, Text

vp = Plotter(verbose=0, axes=0)

# load mesh and increase by a lot (N=2) the nr of surface vertices
s = vp.load('data/shapes/cow.vtk').alpha(0.3).subdivide(N=2)

reds, invr = [], []
for i, p in enumerate(s.coordinates()):
    if i%1000: continue           # skip most points
    pts = s.closestPoint(p, N=16) # find the N closest points to p
    sph = fitSphere(pts).alpha(0.05) # find the fitting sphere
    if sph is None: 
    	continue # may fail if all points sit on a plane
    vp.add(sph)
    vp.add(Points(pts))
    vp.add(Line(sph.info['center'], p, lw=2))
    reds.append(sph.info['residue'])
    invr.append(1/sph.info['radius']**2)
Exemplo n.º 29
0
"""
Example of drawing objects on different windows
and/or subwindows within the same window.
We split the main window in a 25 subwindows and draw something
in specific windows numbers.
Then open an independent window and draw a shape on it.
"""
print(__doc__)

from vtkplotter import Plotter, Text, datadir

# this is one instance of the class Plotter with 5 raws and 5 columns
vp1 = Plotter(shape=(5, 5), axes=0, bg="white")
# having set shape=(n,m), script execution after the show() is not held

# set a different background color for a specific subwindow (the last one)
vp1.renderers[24].SetBackground(0.8, 0.9,
                                0.9)  # use vtk method SetBackground()

# load the actors and give them a name
a = vp1.load(datadir + "airboat.vtk").legend("some legend")
b = vp1.load(datadir + "cessna.vtk", c="red")
c = vp1.load(datadir + "atc.ply")

# show a text in each renderer
for i in range(25):
    txt = Text("renderer\nnr." + str(i), c='k', s=0.5, font='arial')
    vp1.show(txt, at=i, interactive=0)

vp1.show(a, at=22)
vp1.show(b, at=23)
Exemplo n.º 30
0
from __future__ import division, print_function
from vtkplotter import Plotter, mag
import numpy as np

scene = Plotter(title='Lorenz attractor', axes=2, verbose = 0)

dt = 0.001
y = [25, -10, -7] # Starting point (initial condition)
pts, cols = [], []
scene.point(y, r=20, c='g', alpha=0.3)

for t in np.linspace(0,20, int(20/dt)):
  # Integrate a funny differential equation
  dydt = np.array([-8/3*y[0]+ y[1]*y[2], -10*(y[1]-y[2]), -y[1]*y[0]+28*y[1]-y[2]])
  y = y + dydt * dt

  c = np.clip( [mag(dydt) * 0.005], 0, 1)[0] # color by speed
  pts.append(y)
  cols.append([c,0, 1-c])

scene.points(pts, cols, r=2)
scene.show()