222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518 | def start_k3d(actors2show):
"""Start a k3d display in the notebook"""
try:
# https://github.com/K3D-tools/K3D-jupyter
import k3d
except ModuleNotFoundError:
print("\nCannot find k3d, install with: pip install k3d")
return None
plt = vedo.current_plotter()
if not plt:
vedo.logger.error("No active Plotter found for the k3d backend.")
return None
def _setup_scalar_metadata(polydata, mapper):
"""Build scalar metadata for k3d color mapping."""
vtkdata = polydata.GetPointData()
vtkscals = vtkdata.GetScalars()
if vtkscals is None:
vtkdata = polydata.GetCellData()
vtkscals = vtkdata.GetScalars()
if vtkscals is not None:
c2p = vtki.new("CellDataToPointData")
c2p.SetInputData(polydata)
c2p.Update()
polydata = c2p.GetOutput()
vtkdata = polydata.GetPointData()
vtkscals = vtkdata.GetScalars()
if vtkscals is None:
return polydata, None, None, None, None
if not vtkscals.GetName():
vtkscals.SetName("scalars")
scals_min, scals_max = mapper.GetScalarRange()
color_attribute = (vtkscals.GetName(), scals_min, scals_max)
lut = mapper.GetLookupTable()
if lut is None:
return polydata, vtkscals, color_attribute, None, (scals_min, scals_max)
lut.Build()
kcmap = []
nlut = lut.GetNumberOfTableValues()
if nlut <= 0:
return polydata, vtkscals, color_attribute, None, (scals_min, scals_max)
lut_scale = max(nlut - 1, 1)
for i in range(nlut):
r, g, b, _ = lut.GetTableValue(i)
kcmap += [i / lut_scale, r, g, b]
return polydata, vtkscals, color_attribute, kcmap, (scals_min, scals_max)
already_has_axes = False
actors2show2 = []
for ia in actors2show:
if not ia:
continue
try:
if ia.name == "Axes":
already_has_axes = True
except AttributeError:
pass
if isinstance(ia, vedo.Assembly): # unpack assemblies
actors2show2 += ia.recursive_unpack()
else:
actors2show2.append(ia)
nbplot = k3d.plot(
axes=["x", "y", "z"],
menu_visibility=settings.k3d_menu_visibility,
height=settings.k3d_plot_height,
antialias=settings.k3d_antialias,
background_color=_rgb2int(vedo.get_color(plt.backgrcol)),
camera_fov=30.0, # deg (this is the vtk default)
lighting=settings.k3d_lighting,
grid_color=_rgb2int(vedo.get_color(settings.k3d_axes_color)),
label_color=_rgb2int(vedo.get_color(settings.k3d_axes_color)),
axes_helper=settings.k3d_axes_helper,
)
# set k3d camera
vedo.set_current_notebook_plotter(nbplot)
nbplot.camera_auto_fit = settings.k3d_camera_autofit
nbplot.axes_helper = settings.k3d_axes_helper
nbplot.grid_auto_fit = settings.k3d_grid_autofit
if already_has_axes:
nbplot.grid_visible = False
if settings.k3d_grid_visible is not None: # override if set
nbplot.grid_visible = settings.k3d_grid_visible
if plt.camera:
nbplot.camera = utils.vtkCameraToK3D(plt.camera)
for ia in actors2show2:
if isinstance(ia, (vtki.vtkAssembly, vtki.vtkActor2D)):
continue
if hasattr(ia, "actor") and isinstance(
ia.actor, (vtki.vtkAssembly, vtki.vtkActor2D)
):
continue
iacloned = ia
kobj = None
kcmap = None
color_attribute = None
vtkscals = None
name = None
if hasattr(ia, "filename"):
if ia.filename:
name = os.path.basename(ia.filename)
if hasattr(ia, "name") and ia.name:
name = os.path.basename(ia.name)
################################################################## scalars
# work out scalars first, Points Lines are also Mesh objs
if isinstance(ia, Points):
# print('scalars', ia.name, ia.npoints)
iap = ia.properties
if ia.dataset.GetNumberOfPolys():
iacloned = ia.clone()
iapoly = iacloned.clean().triangulate().compute_normals().dataset
else:
iapoly = ia.dataset
if ia.mapper.GetScalarVisibility() and ia.mapper.GetColorMode() > 0:
iapoly, vtkscals, color_attribute, kcmap, scal_range = (
_setup_scalar_metadata(iapoly, ia.mapper)
)
if scal_range is not None:
scals_min, scals_max = scal_range
else:
color_attribute = ia.color()
#####################################################################Volume
if isinstance(ia, Volume):
# print('Volume', ia.name, ia.dimensions())
kx, ky, _ = ia.dimensions()
arr = ia.pointdata[0]
kimage = arr.reshape(-1, ky, kx)
color_transfer_function = ia.properties.GetRGBTransferFunction()
kcmap = []
for i in range(128):
r, g, b = color_transfer_function.GetColor(i / 127)
kcmap += [i / 127, r, g, b]
kbounds = np.array(ia.dataset.GetBounds()) + np.repeat(
np.array(ia.dataset.GetSpacing()) / 2.0, 2
) * np.array([-1, 1] * 3)
kobj = k3d.volume(
kimage.astype(np.float32),
color_map=kcmap,
# color_range=ia.dataset.GetScalarRange(),
alpha_coef=10,
bounds=kbounds,
name=name,
)
nbplot += kobj
################################################################ Text2D
elif isinstance(ia, vedo.Text2D):
# print('Text2D', ia.GetPosition())
pos = (ia.GetPosition()[0], 1.0 - ia.GetPosition()[1])
kobj = k3d.text2d(
ia.text(),
position=pos,
color=_rgb2int(vedo.get_color(ia.c())),
is_html=True,
size=ia.properties.GetFontSize() / 22.5 * 1.5,
label_box=bool(ia.properties.GetFrame()),
# reference_point='bl',
)
nbplot += kobj
################################################################# Lines
elif (
hasattr(ia, "lines")
and ia.dataset.GetNumberOfLines()
and ia.dataset.GetNumberOfPolys() == 0
):
for i, ln_idx in enumerate(ia.lines):
if i >= 200:
vedo.logger.warning("in k3d, nr. of lines is limited to 200.")
break
pts = ia.coordinates[ln_idx]
aves = ia.diagonal_size() * iap.GetLineWidth() / 100
kobj = k3d.line(
pts.astype(np.float32),
color=_rgb2int(iap.GetColor()),
opacity=iap.GetOpacity(),
shader=settings.k3d_line_shader,
width=aves.astype(float),
name=name,
)
nbplot += kobj
################################################################## Mesh
elif isinstance(ia, Mesh) and ia.npoints and ia.dataset.GetNumberOfPolys():
# print('Mesh', ia.name, ia.npoints, len(ia.cells))
if not vtkscals:
color_attribute = None
cols = []
if ia.mapper.GetColorMode() == 2: # direct RGB colors
vcols = ia.dataset.GetPointData().GetScalars()
if not vcols:
iacloned = ia.clone()
iacloned.map_cells_to_points()
vcols = iacloned.dataset.GetPointData().GetScalars()
if vcols and vcols.GetNumberOfComponents() in (3, 4):
# vedo.logger.info("found RGB direct colors in Mesh")
cols = utils.vtk2numpy(vcols).astype(np.uint32)
cols = 65536 * cols[:, 0] + 256 * cols[:, 1] + cols[:, 2]
kobj = k3d.mesh(
iacloned.coordinates,
iacloned.cells,
colors=cols,
name=name,
opacity=iap.GetOpacity(),
side="double",
wireframe=(iap.GetRepresentation() == 1),
)
else:
vedo.logger.warning("could not find RGB direct colors in Mesh")
kobj = k3d.mesh(
iacloned.coordinates,
iacloned.cells,
color=_rgb2int(iap.GetColor()),
name=name,
opacity=iap.GetOpacity(),
side="double",
wireframe=(iap.GetRepresentation() == 1),
)
else:
kobj = k3d.vtk_poly_data(
iapoly,
name=name,
color=_rgb2int(iap.GetColor()),
color_attribute=color_attribute,
color_map=kcmap,
opacity=iap.GetOpacity(),
side="double",
wireframe=(iap.GetRepresentation() == 1),
)
if iap.GetInterpolation() == 0:
kobj.flat_shading = True
nbplot += kobj
#####################################################################Points
elif isinstance(ia, Points):
# print('Points', ia.name, ia.npoints)
kcols = []
if kcmap is not None and vtkscals:
scals = utils.vtk2numpy(vtkscals)
kcols = k3d.helpers.map_colors(
scals, kcmap, [scals_min, scals_max]
).astype(np.uint32)
aves = ia.average_size() * iap.GetPointSize() / 200
kobj = k3d.points(
ia.coordinates.astype(np.float32),
color=_rgb2int(iap.GetColor()),
colors=kcols,
opacity=iap.GetOpacity(),
shader=settings.k3d_point_shader,
point_size=aves.astype(float),
name=name,
)
nbplot += kobj
#####################################################################
elif isinstance(ia, vedo.Image):
vedo.logger.error("Sorry Image objects are not supported in k3d.")
if plt and settings.backend_autoclose:
plt.close()
return nbplot
|