Debian Codegraph @

pyvista/demos/logo.py

raw
1 """Generate the pyvista logo.
2
3 Logos generated with:
4 plot_logo(screenshot='pyvista_logo.png', window_size=(1920, 1080))
5 plot_logo(screenshot='pyvista_logo_sm.png', window_size=(960, 400), off_screen=True)
6
7 # different camera angle for square plot
8 cpos = [(-0.3654543687422538, 1.1098808905156292, 9.073223697728247),
9 (2.553950615449191, 0.34145688392081264, 0.06127122762851659),
10 (0.019308531920309947, 0.996708840795678, -0.07873161547192065)]
11
12 plot_logo(screenshot='pyvista_logo_sm_sq.png', window_size=(960, 960), cpos=cpos,
13 off_screen=True)
14
15 """
16
17 from __future__ import annotations
18
19 import os
20 from pathlib import Path
21
22 import numpy as np
23
24 import pyvista as pv
25 from pyvista import _vtk
26 from pyvista import examples
27 from pyvista._deprecate_positional_args import _deprecate_positional_args
28 from pyvista.core.utilities.features import _voxelize_legacy
29
30 THIS_PATH = str(Path(os.path.realpath(__file__)).parent)
31
32 LOGO_TITLE = 'PyVista'
33
34
35 def atomize(grid, shift_fac=0.1, scale=0.9):
36 """Break apart and shrink and/or scale the individual cells of a mesh.
37
38 Parameters
39 ----------
40 grid : pyvista.UnstructuredGrid
41 The input mesh to atomize.
42 shift_fac : float, default: 0.1
43 Factor by which to shift the individual cells apart.
44 scale : float, default: 0.9
45 Factor by which to scale the individual cells.
46
47 Returns
48 -------
49 pyvista.UnstructuredGrid
50 The atomized mesh with individually shifted and scaled cells.
51
52 """
53 cent = grid.center
54 cells = []
55 for i in range(grid.n_cells):
56 cell = grid.extract_cells(i)
57 ccent = np.array(cell.center)
58 cell.points[:] = (cell.points - ccent) * scale + ccent
59 cell.points += (ccent - np.array(cent)) * shift_fac
60 cells.append(cell)
61
62 return cells[0].merge(cells[1:])
63
64
65 def text_3d(string, depth=0.5):
66 """Create 3D text from a given string.
67
68 Parameters
69 ----------
70 string : str
71 The string of text to convert into 3D text.
72
73 depth : float, default: 0.5
74 The depth of the extrusion used to create the 3D text.
75
76 Returns
77 -------
78 pyvista.DataSet
79 The 3D text in the form of a PyVista DataSet.
80
81 See Also
82 --------
83 :ref:`create_pixel_art_example`
84
85 """
86 vec_text = _vtk.vtkVectorText()
87 vec_text.SetText(string)
88
89 extrude = _vtk.vtkLinearExtrusionFilter()
90 extrude.SetInputConnection(vec_text.GetOutputPort())
91 extrude.SetExtrusionTypeToNormalExtrusion()
92 extrude.SetVector(0, 0, 1)
93 extrude.SetScaleFactor(depth)
94
95 tri_filter = _vtk.vtkTriangleFilter()
96 tri_filter.SetInputConnection(extrude.GetOutputPort())
97 tri_filter.Update()
98 return pv.wrap(tri_filter.GetOutput())
99
100
101 @_deprecate_positional_args
102 def logo_letters(merge=False, depth=0.3): # noqa: FBT002
103 """Generate a mesh for each letter in "PyVista".
104
105 Parameters
106 ----------
107 merge : bool, optional
108 If ``True``, merge the meshes of the individual letters into a single
109 mesh. If ``False``, return a dictionary where the keys are the letters
110 and the values are the respective meshes.
111 depth : float, optional
112 The depth of the extrusion for each letter in the mesh.
113
114 Returns
115 -------
116 output : pyvista.PolyData or dict[str, pyvista.PolyData]
117 If merge is ``True``, returns a single merged mesh containing all the
118 letters in "PyVista". If merge is ``False``, returns a dictionary where
119 the keys are the letters and the values are the respective meshes.
120
121 """
122 mesh_letters = pv.PolyData() if merge else {}
123
124 # spacing between letters
125 space_factor = 0.9
126 width = 0
127 for letter in LOGO_TITLE:
128 mesh_letter = text_3d(letter, depth=depth)
129 this_letter_width = mesh_letter.points[:, 0].max()
130 mesh_letter.translate([width * space_factor, 0, 0.0], inplace=True)
131 width += this_letter_width
132 if merge:
133 mesh_letters += mesh_letter
134 else:
135 mesh_letters[letter] = mesh_letter # type: ignore[index]
136
137 return mesh_letters
138
139
140 def logo_voxel(density=0.03):
141 """Create a voxelized PyVista logo.
142
143 Parameters
144 ----------
145 density : float, default: 0.03
146 Density of the voxelization.
147
148 Returns
149 -------
150 pyvista.UnstructuredGrid
151 Voxelized PyVista logo as an unstructured grid.
152
153 """
154 return _voxelize_legacy(text_3d(LOGO_TITLE, depth=0.3), density=density)
155
156
157 def logo_basic():
158 """Create a basic pyvista logo.
159
160 Returns
161 -------
162 pyvista.UnstructuredGrid
163 Grid containing the pyvista letters.
164
165 Examples
166 --------
167 Plot the basic pyvista logo.
168
169 >>> from pyvista import demos
170 >>> logo = demos.logo_basic()
171 >>> cpos = logo.plot(smooth_shading=True)
172
173 Add scalars and plot the logo.
174
175 >>> logo['x_coord'] = logo.points[:, 0]
176 >>> cpos = logo.plot(
177 ... scalars='x_coord',
178 ... cmap='Spectral',
179 ... smooth_shading=True,
180 ... cpos='xy',
181 ... )
182
183 """
184 return logo_letters(merge=True).compute_normals(split_vertices=True)
185
186
187 @_deprecate_positional_args
188 def plot_logo( # noqa: PLR0917
189 window_size=None,
190 off_screen=None,
191 screenshot=None,
192 cpos=None,
193 just_return_plotter=False, # noqa: FBT002
194 show_note=False, # noqa: FBT002
195 **kwargs,
196 ):
197 """Plot the stylized PyVista logo.
198
199 Parameters
200 ----------
201 window_size : sequence[int], optional
202 Size of the window in the format ``[width, height]``.
203 off_screen : bool, optional
204 Renders off screen when ``True``.
205 screenshot : str, optional
206 Save screenshot to path when specified.
207 cpos : list or str, optional
208 Camera position to use.
209 just_return_plotter : bool, default: False
210 Return the plotter instance without rendering.
211 show_note : bool, default: False
212 Show a text in the plot when ``True``.
213 **kwargs : dict, optional
214 Additional keyword arguments.
215
216 Returns
217 -------
218 output : Plotter or camera position
219 Returns the plotter instance if ``just_return_plotter`` is ``True``,
220 otherwise returns the camera position if ``screenshot`` is specified,
221 otherwise shows the plot.
222
223 Examples
224 --------
225 >>> from pyvista import demos
226 >>> cpos = demos.plot_logo()
227
228 """
229 # initialize plotter
230 if window_size is None:
231 window_size = [960, 400]
232 pl = pv.Plotter(window_size=window_size, off_screen=off_screen)
233
234 mesh_letters = logo_letters()
235
236 # letter 'P'
237 p_mesh = mesh_letters['P'].compute_normals(split_vertices=True)
238 pl.add_mesh(p_mesh, color='#376fa0', smooth_shading=True)
239
240 # letter 'y'
241 y_mesh = mesh_letters['y'].compute_normals(split_vertices=True)
242 pl.add_mesh(y_mesh, color='#ffd040', smooth_shading=True)
243
244 # letter 'V'
245 v_grid = _voxelize_legacy(mesh_letters['V'], density=0.08)
246 v_grid_atom = atomize(v_grid)
247 v_grid_atom['scalars'] = v_grid_atom.points[:, 0]
248 v_grid_atom_surf = v_grid_atom.extract_surface(algorithm=None)
249 faces = v_grid_atom_surf.faces.reshape(-1, 5).copy()
250 faces[:, 1:] = faces[:, 1:][:, ::-1]
251 v_grid_atom_surf.faces = faces
252 pl.add_mesh(
253 v_grid_atom_surf,
254 scalars='scalars',
255 show_edges=True,
256 cmap='winter',
257 show_scalar_bar=False,
258 )
259
260 # letter 'i'
261 i_grid = _voxelize_legacy(mesh_letters['i'], density=0.1)
262
263 pl.add_mesh(
264 i_grid.extract_surface(algorithm=None),
265 style='points',
266 color='r',
267 render_points_as_spheres=True,
268 point_size=14,
269 )
270 pl.add_mesh(i_grid, style='wireframe', color='k', line_width=4)
271
272 # letter 's'
273 mesh = mesh_letters['s']
274 mesh['scalars'] = mesh.points[:, 0]
275 pl.add_mesh(
276 mesh,
277 scalars='scalars',
278 style='wireframe',
279 line_width=2,
280 cmap='gist_heat',
281 backface_culling=True,
282 render_lines_as_tubes=True,
283 show_scalar_bar=False,
284 )
285
286 # letter 't'
287 mesh = mesh_letters['t'].clean().compute_normals()
288 scalars = mesh.points[:, 0]
289 pl.add_mesh(mesh, scalars=scalars, show_edges=True, cmap='autumn', show_scalar_bar=False)
290
291 # letter 'a'
292 grid = examples.download_letter_a()
293 grid.points[:, 0] += mesh_letters['a'].center[0] - grid.center[0]
294
295 # select some cells from grid
296 cells = grid.cells.reshape(-1, 5)
297 mask = grid.points[cells[:, 1:], 2] < 0.2
298 mask = mask.all(1)
299
300 a_part = grid.extract_cells(mask)
301
302 cells = a_part.cells.reshape(-1, 5)
303 scalars = grid.points[cells[:, 1], 1]
304 pl.add_mesh(a_part, scalars=scalars, show_edges=True, cmap='Greens', show_scalar_bar=False)
305
306 if show_note:
307 text = text_3d('You can move me!', depth=0.1)
308 text.points *= 0.1
309 text.translate([4.0, -0.3, 0], inplace=True)
310 pl.add_mesh(text, color='black')
311
312 # finalize plot and show it
313 pl.set_background(kwargs.pop('background', 'white'))
314 pl.camera_position = 'xy'
315 if 'zoom' in kwargs:
316 pl.camera.zoom(kwargs.pop('zoom'))
317
318 # pl.remove_scalar_bar()
319 pl.enable_anti_aliasing()
320
321 if just_return_plotter:
322 return pl
323
324 if screenshot: # pragma: no cover
325 pl.show(cpos=cpos, auto_close=False)
326 pl.screenshot(screenshot, True)
327 cpos_final = pl.camera_position
328 pl.close()
329 return cpos_final
330 else:
331 return pl.show(cpos=cpos, **kwargs)
332
333
334 def logo_atomized(density=0.05, scale=0.6, depth=0.05):
335 """Generate a voxelized pyvista logo with intra-cell spacing.
336
337 Parameters
338 ----------
339 density : float, default: 0.05
340 The spacing between voxels in the generated PyVista logo.
341 scale : float, default: 0.6
342 The scaling factor for the generated PyVista logo.
343 depth : float, default: 0.05
344 The depth of the generated PyVista logo.
345
346 Returns
347 -------
348 pyvista.UnstructuredGrid
349 A merged UnstructuredGrid representing the voxelized PyVista logo.
350
351 """
352 mesh_letters = logo_letters(depth=depth)
353 grids = []
354 for letter in mesh_letters.values():
355 grid = _voxelize_legacy(letter, density=density)
356 grids.append(atomize(grid, scale=scale))
357
358 return grids[0].merge(grids[1:])