1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 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 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
|
"""Module containing pyvista implementation of vtk.vtkLight."""
from __future__ import annotations
from enum import IntEnum
import numpy as np
# imports here rather than in _vtk to avoid circular imports
try:
from vtkmodules.vtkCommonMath import vtkMatrix4x4
from vtkmodules.vtkRenderingCore import vtkLight
from vtkmodules.vtkRenderingCore import vtkLightActor
except ImportError: # pragma: no cover
from vtk import vtkLight
from vtk import vtkLightActor
from vtk import vtkMatrix4x4
from typing import TYPE_CHECKING
from pyvista.core.utilities.arrays import vtkmatrix_from_array
from .colors import Color
if TYPE_CHECKING: # pragma: no cover
from ._typing import ColorLike
class LightType(IntEnum):
"""An enumeration for the light types."""
HEADLIGHT = 1
CAMERA_LIGHT = 2
SCENE_LIGHT = 3
def __str__(self):
"""Pretty name for a light type."""
return self.name.replace('_', ' ').title()
class Light(vtkLight):
"""Light class.
Parameters
----------
position : sequence[float], optional
The position of the light. The interpretation of the position
depends on the type of the light and whether the light has a
transformation matrix. See also the :py:attr:`position`
property.
focal_point : sequence[float], optional
The focal point of the light. The interpretation of the focal
point depends on the type of the light and whether the light
has a transformation matrix. See also the
:py:attr:`focal_point` property.
color : ColorLike, optional
The color of the light. The ambient, diffuse and specular
colors will all be set to this color on creation.
light_type : str | int, default: 'scene light'
The type of the light. If a string, one of ``'headlight'``,
``'camera light'`` or ``'scene light'``. If an int, one of 1,
2 or 3, respectively. The class constants ``Light.HEADLIGHT``,
``Light.CAMERA_LIGHT`` and ``Light.SCENE_LIGHT`` are also
available, respectively.
- A headlight is attached to the camera, looking at its
focal point along the axis of the camera.
- A camera light also moves with the camera, but it can
occupy a general position with respect to it.
- A scene light is stationary with respect to the scene,
as it does not follow the camera. This is the default.
intensity : float, optional
The brightness of the light (between 0 and 1).
positional : bool, optional
Set if the light is positional.
The default is a directional light, i.e. an infinitely distant
point source. A positional light with a cone angle of at least
90 degrees acts like a spherical point source. A positional
light with a cone angle that is less than 90 degrees is known
as a spotlight.
cone_angle : float, optional
Cone angle of a positional light in degrees.
show_actor : bool, default: False
Show an actor for a spotlight that depicts the geometry of the
beam.
exponent : float, optional
The exponent of the cosine used for spotlights. See also the
:py:attr:`exponent` property.
shadow_attenuation : float, optional
The value of shadow attenuation.
By default a light will be completely blocked when in shadow.
By setting this value to less than 1.0 you can control how
much light is attenuated when in shadow. Note that changing
the :py:attr:`attenuation_values` of the light can make it pass
through objects even if its shadow attenuation is 1.
attenuation_values : sequence, optional
Quadratic attenuation constants.
The values are a 3-length sequence which specifies the constant,
linear and quadratic constants in this order. These parameters
only have an effect for positional lights.
Examples
--------
Create a light at (10, 10, 10) and set its diffuse color to red.
>>> import pyvista as pv
>>> light = pv.Light(position=(10, 10, 10))
>>> light.diffuse_color = 1.0, 0.0, 0.0
Create a positional light at (0, 0, 3) with a cone angle of
30, exponent of 20, and a visible actor.
>>> light = pv.Light(
... position=(0, 0, 3),
... show_actor=True,
... positional=True,
... cone_angle=30,
... exponent=20,
... )
"""
# pull in light type enum values as class constants
HEADLIGHT = LightType.HEADLIGHT
CAMERA_LIGHT = LightType.CAMERA_LIGHT
SCENE_LIGHT = LightType.SCENE_LIGHT
def __init__(
self,
position=None,
focal_point=None,
color=None,
light_type='scene light',
intensity=None,
positional=None,
cone_angle=None,
show_actor=False,
exponent=None,
shadow_attenuation=None,
attenuation_values=None,
):
"""Initialize the light."""
super().__init__()
self._renderers = []
self.actor = None
if position is not None:
self.position = position
if focal_point is not None:
self.focal_point = focal_point
if color is not None:
self.ambient_color = color
self.diffuse_color = color
self.specular_color = color
if isinstance(light_type, str):
# be forgiving: ignore spaces and case
light_type_orig = light_type
type_normalized = light_type.replace(' ', '').lower()
mapping = {
'headlight': LightType.HEADLIGHT,
'cameralight': LightType.CAMERA_LIGHT,
'scenelight': LightType.SCENE_LIGHT,
}
try:
light_type = mapping[type_normalized]
except KeyError:
light_keys = ', '.join(mapping)
msg = (
f'Invalid light_type "{light_type_orig}"\n'
f'Choose from one of the following: {light_keys}'
)
raise ValueError(msg) from None
elif not isinstance(light_type, int):
raise TypeError(
f'Parameter light_type must be int or str, not {type(light_type).__name__}.',
)
# LightType is an int subclass
self.light_type = light_type
if intensity is not None:
self.intensity = intensity
if cone_angle is not None:
self.cone_angle = cone_angle
if exponent is not None:
self.exponent = exponent
if positional is not None:
self.positional = positional
if shadow_attenuation is not None:
self.shadow_attenuation = shadow_attenuation
if attenuation_values is not None:
self.attenuation_values = attenuation_values
# Add the light actor
self.actor = vtkLightActor()
self.actor.SetLight(self)
self.actor.SetVisibility(show_actor)
def __repr__(self):
"""Print a repr specifying the id of the light and its light type."""
return f'<{self.__class__.__name__} ({self.light_type}) at {hex(id(self))}>'
def __eq__(self, other):
"""Compare whether the relevant attributes of two lights are equal."""
# attributes which are native python types and thus implement __eq__
native_attrs = [
'light_type',
'position',
'focal_point',
'ambient_color',
'diffuse_color',
'specular_color',
'intensity',
'on',
'positional',
'exponent',
'cone_angle',
'attenuation_values',
'shadow_attenuation',
]
for attr in native_attrs:
if getattr(self, attr) != getattr(other, attr):
return False
# check transformation matrix element by element (if it exists)
this_trans = self.transform_matrix
that_trans = other.transform_matrix
trans_count = sum(1 for trans in [this_trans, that_trans] if trans is not None)
if trans_count == 1:
# either but not both are None
return False
if trans_count == 2:
for i in range(4):
for j in range(4):
if this_trans.GetElement(i, j) != that_trans.GetElement(i, j):
return False
return True
def __del__(self):
"""Clean up when the light is being destroyed."""
self.actor = None
self._renderers.clear()
@property
def shadow_attenuation(self): # numpydoc ignore=RT01
"""Return or set the value of shadow attenuation.
By default a light will be completely blocked when in shadow.
By setting this value to less than 1.0 you can control how
much light is attenuated when in shadow. Note that changing
the :py:attr:`attenuation_values` of the light can make it pass
through objects even if its shadow attenuation is 1.
Examples
--------
Set the shadow attenuation to 0.5
>>> import pyvista as pv
>>> light = pv.Light()
>>> light.shadow_attenuation = 0.5
>>> light.shadow_attenuation
0.5
"""
return self.GetShadowAttenuation()
@shadow_attenuation.setter
def shadow_attenuation(self, value): # numpydoc ignore=GL08
self.SetShadowAttenuation(value)
@property
def ambient_color(self): # numpydoc ignore=RT01
"""Return or set the ambient color of the light.
When setting, the color must be a 3-length sequence or a string.
For example:
* ``color='white'``
* ``color='w'``
* ``color=[1.0, 1.0, 1.0]``
* ``color='#FFFFFF'``
Examples
--------
Create a light and set its ambient color to red.
>>> import pyvista as pv
>>> light = pv.Light()
>>> light.ambient_color = 'red'
>>> light.ambient_color
Color(name='red', hex='#ff0000ff', opacity=255)
"""
return Color(self.GetAmbientColor())
@ambient_color.setter
def ambient_color(self, color: ColorLike): # numpydoc ignore=GL08
self.SetAmbientColor(Color(color).float_rgb)
@property
def diffuse_color(self): # numpydoc ignore=RT01
"""Return or set the diffuse color of the light.
When setting, the color must be a 3-length sequence or a string.
For example:
* ``color='white'``
* ``color='w'``
* ``color=[1.0, 1.0, 1.0]``
* ``color='#FFFFFF'``
Examples
--------
Create a light and set its diffuse color to blue.
>>> import pyvista as pv
>>> light = pv.Light()
>>> light.diffuse_color = (0.0, 0.0, 1.0)
>>> light.diffuse_color
Color(name='blue', hex='#0000ffff', opacity=255)
"""
return Color(self.GetDiffuseColor())
@diffuse_color.setter
def diffuse_color(self, color: ColorLike): # numpydoc ignore=GL08
self.SetDiffuseColor(Color(color).float_rgb)
@property
def specular_color(self): # numpydoc ignore=RT01
"""Return or set the specular color of the light.
When setting, the color must be a 3-length sequence or a string.
For example:
* ``color='white'``
* ``color='w'``
* ``color=[1.0, 1.0, 1.0]``
* ``color='#FFFFFF'``
Examples
--------
Create a light and set its specular color to bright green.
>>> import pyvista as pv
>>> light = pv.Light()
>>> light.specular_color = '#00FF00'
>>> light.specular_color
Color(name='lime', hex='#00ff00ff', opacity=255)
"""
return Color(self.GetSpecularColor())
@specular_color.setter
def specular_color(self, color: ColorLike): # numpydoc ignore=GL08
self.SetSpecularColor(Color(color).float_rgb)
@property
def position(self): # numpydoc ignore=RT01
"""Return the position of the light.
Note: the position is defined in the coordinate space
indicated by the light's transformation matrix (if it
exists). To get the light's world space position, use the
(read-only) :py:attr:`world_position` property.
Examples
--------
Create a light positioned at ``(10, 10, 10)`` after
initialization, and note how the position is unaffected by a
non-trivial transform matrix.
>>> import numpy as np
>>> import pyvista as pv
>>> light = pv.Light()
>>> light.position = (10, 10, 10)
>>> # set a "random" transformation matrix
>>> light.transform_matrix = np.arange(4 * 4).reshape(4, 4)
>>> light.position
(10.0, 10.0, 10.0)
"""
return self.GetPosition()
@position.setter
def position(self, pos): # numpydoc ignore=GL08
self.SetPosition(pos)
@property
def world_position(self): # numpydoc ignore=RT01
"""Return the world space position of the light.
The world space position is the :py:attr:`position` property
transformed by the light's transform matrix if it exists. The
value of this read-only property corresponds to the
``vtk.vtkLight.GetTransformedPosition()`` method.
Examples
--------
Create a light with a transformation matrix that corresponds to a
90-degree rotation around the z-axis and a shift by (0, 0, -1), and
check that the light's position transforms as expected.
>>> import numpy as np
>>> import pyvista as pv
>>> light = pv.Light(position=(1, 0, 3))
>>> trans = np.zeros((4, 4))
>>> trans[:-1, :-1] = [[0, -1, 0], [1, 0, 0], [0, 0, 1]]
>>> trans[:-1, -1] = [0, 0, -1]
>>> light.transform_matrix = trans
>>> light.position
(1.0, 0.0, 3.0)
>>> light.world_position
(0.0, 1.0, 2.0)
"""
return self.GetTransformedPosition()
@property
def focal_point(self): # numpydoc ignore=RT01
"""Return the focal point of the light.
Note: the focal point is defined in the coordinate space
indicated by the light's transformation matrix (if it
exists). To get the light's world space focal point, use the
(read-only) :py:attr:`world_focal_point` property.
Examples
--------
Create a light at (10, 10, 10) shining at (0, 0, 1).
>>> import pyvista as pv
>>> light = pv.Light(position=(10, 10, 10))
>>> light.focal_point = (0, 0, 1)
"""
return self.GetFocalPoint()
@focal_point.setter
def focal_point(self, pos): # numpydoc ignore=GL08
self.SetFocalPoint(pos)
@property
def world_focal_point(self): # numpydoc ignore=RT01
"""Return the world space focal point of the light.
The world space focal point is the :py:attr:`focal_point`
property transformed by the light's transform matrix if it
exists. The value of this read-only property corresponds to
the ``vtk.vtkLight.GetTransformedFocalPoint()`` method.
Examples
--------
Create a light with a transformation matrix that corresponds
to a 90-degree rotation around the z-axis and a shift by (0,
0, -1), and check that the light's focal point transforms as
expected.
>>> import numpy as np
>>> import pyvista as pv
>>> light = pv.Light(focal_point=(1, 0, 3))
>>> trans = np.zeros((4, 4))
>>> trans[:-1, :-1] = [[0, -1, 0], [1, 0, 0], [0, 0, 1]]
>>> trans[:-1, -1] = [0, 0, -1]
>>> light.transform_matrix = trans
>>> light.focal_point
(1.0, 0.0, 3.0)
>>> light.world_focal_point
(0.0, 1.0, 2.0)
"""
return self.GetTransformedFocalPoint()
@property
def intensity(self): # numpydoc ignore=RT01
"""Return or set the brightness of the light (between 0 and 1).
Examples
--------
Light the two sides of a cube with lights of different
brightness.
>>> import pyvista as pv
>>> plotter = pv.Plotter(lighting='none')
>>> _ = plotter.add_mesh(pv.Cube(), color='cyan')
>>> light_bright = pv.Light(
... position=(3, 0, 0), light_type='scene light'
... )
>>> light_dim = pv.Light(
... position=(0, 3, 0), light_type='scene light'
... )
>>> light_dim.intensity = 0.5
>>> for light in light_bright, light_dim:
... light.positional = True
... plotter.add_light(light)
...
>>> plotter.show()
"""
return self.GetIntensity()
@intensity.setter
def intensity(self, intensity): # numpydoc ignore=GL08
self.SetIntensity(intensity)
@property
def on(self): # numpydoc ignore=RT01
"""Return or set whether the light is on.
This corresponds to the Switch state of the ``vtk.vtkLight`` class.
Examples
--------
Create a light, check if it's on by default, and turn it off.
>>> import pyvista as pv
>>> light = pv.Light()
>>> light.on
True
>>> light.on = False
"""
return bool(self.GetSwitch())
@on.setter
def on(self, state): # numpydoc ignore=GL08
self.SetSwitch(state)
@property
def positional(self): # numpydoc ignore=RT01
"""Return or set whether the light is positional.
The default is a directional light, i.e. an infinitely distant
point source. A positional light with a cone angle of at least
90 degrees acts like a spherical point source. A positional
light with a cone angle that is less than 90 degrees is known
as a spotlight.
Attenuation and cone angles are only used for positional
lights. The :py:attr:`exponent` property is only used for
spotlights. Positional lights with a cone angle of at least
90 degrees don't show angular dependence of their beams, but
they display attenuation.
If the light is changed to directional, its actor (if previously
shown) is automatically hidden.
Examples
--------
Create a spotlight shining on the origin.
>>> import pyvista as pv
>>> light = pv.Light(position=(1, 1, 1))
>>> light.positional = True
>>> light.cone_angle = 30
"""
return bool(self.GetPositional())
@positional.setter
def positional(self, state): # numpydoc ignore=GL08
if not state:
self.hide_actor()
self.SetPositional(state)
self._check_actor()
def _check_actor(self):
"""Check if the light actor should be added or removed from attached renderers.
This should be called whenever positional state or cone angle
are changed.
"""
if self.actor is None:
# only should occur on __init__
return
actor_state = self.cone_angle < 90 and self.positional
actor_name = self.actor.GetAddressAsString("")
# add or remove the actor from the renderer
for renderer in self._renderers:
if actor_state:
if actor_name not in renderer.actors:
renderer.add_actor(self.actor, render=False)
else:
if actor_name in renderer.actors:
renderer.remove_actor(self.actor, render=False)
@property
def exponent(self): # numpydoc ignore=RT01
"""Return or set the exponent of the cosine used for spotlights.
With a spotlight (a positional light with cone angle less than
90 degrees) the shape of the light beam within the light cone
varies with the angle from the light's axis, and the variation
of the intensity depends as the cosine of this angle raised to
an exponent, which is 1 by default. Increasing the exponent
makes the beam sharper (more focused around the axis),
decreasing it spreads the beam out.
Note that since the angular dependence defined by this
property and the truncation performed by the
:py:attr:`cone_angle` are independent, for spotlights with
narrow beams (small :py:attr:`cone_angle`) it is harder to see
the angular variation of the intensity, and a lot higher
exponent might be necessary to visibly impact the angular
distribution of the beam.
Examples
--------
Plot three planes lit by three spotlights with exponents of 1,
2 and 5. The one with the lowest exponent has the broadest
beam.
>>> import pyvista as pv
>>> plotter = pv.Plotter(lighting='none')
>>> for offset, exponent in zip([0, 1.5, 3], [1, 2, 5]):
... _ = plotter.add_mesh(
... pv.Plane((offset, 0, 0)), color='white'
... )
... light = pv.Light(
... position=(offset, 0, 0.1),
... focal_point=(offset, 0, 0),
... )
... light.exponent = exponent
... light.positional = True
... light.cone_angle = 80
... plotter.add_light(light)
...
>>> plotter.view_xy()
>>> plotter.show()
"""
return self.GetExponent()
@exponent.setter
def exponent(self, exp): # numpydoc ignore=GL08
self.SetExponent(exp)
@property
def cone_angle(self): # numpydoc ignore=RT01
"""Return or set the cone angle of a positional light.
The angle is in degrees and is measured between the axis of
the cone and an extremal ray of the cone. A value smaller than
90 has spot lighting effects, anything equal to and above 90
is just a positional light, i.e. a spherical point source.
Regarding the angular distribution of the light, the cone
angle merely truncates the beam, the shape of which is defined
by the :py:attr:`exponent`. If the cone angle is at least 90
degrees then there is no angular dependence.
If the light's cone angle is increased to 90 degrees or above,
its actor (if previously shown) is automatically hidden.
Examples
--------
Plot three planes lit by three spotlights with varying cone
angles. Use a large exponent to cause a visible angular
variation of the intensity of the beams.
>>> import pyvista as pv
>>> plotter = pv.Plotter(lighting='none')
>>> for offset, angle in zip([0, 1.5, 3], [70, 30, 20]):
... _ = plotter.add_mesh(
... pv.Plane((offset, 0, 0)), color='white'
... )
... light = pv.Light(
... position=(offset, 0, 1), focal_point=(offset, 0, 0)
... )
... light.exponent = 15
... light.positional = True
... light.cone_angle = angle
... plotter.add_light(light)
...
>>> plotter.view_xy()
>>> plotter.show()
"""
return self.GetConeAngle()
@cone_angle.setter
def cone_angle(self, angle): # numpydoc ignore=GL08
if angle >= 90:
self.hide_actor()
self.SetConeAngle(angle)
self._check_actor()
@property
def attenuation_values(self): # numpydoc ignore=RT01
"""Return or set the quadratic attenuation constants.
The values are 3-length sequences which specify the constant,
linear and quadratic constants in this order. These parameters
only have an effect for positional lights.
Attenuation refers to the dampening of a beam of light as it
gets further away from the point source. The three constants
describe three different profiles for dampening with
distance. A larger attenuation constant corresponds to more
rapid decay with distance.
Examples
--------
Plot three cubes lit by two lights with different attenuation
profiles. The blue light has slower linear attenuation, the
green one has quadratic attenuation that makes it decay
faster. Note that there are no shadow effects included so each
box gets lit by both lights.
>>> import pyvista as pv
>>> plotter = pv.Plotter(lighting='none')
>>> for offset in 1, 2.5, 4:
... _ = plotter.add_mesh(
... pv.Cube(center=(offset, offset, 0)), color='white'
... )
...
>>> colors = ['b', 'g']
>>> all_attenuations = [(0, 0.1, 0), (0, 0, 0.1)]
>>> centers = [(0, 1, 0), (1, 0, 0)]
>>> for color, attenuation_constants, center in zip(
... colors, all_attenuations, centers
... ):
... light = pv.Light(position=center, color=color)
... light.focal_point = (1 + center[0], 1 + center[1], 0)
... light.cone_angle = 90
... light.positional = True
... light.attenuation_values = attenuation_constants
... plotter.add_light(light)
>>> plotter.view_vector((-1, -1, 1))
>>> plotter.show()
"""
return self.GetAttenuationValues()
@attenuation_values.setter
def attenuation_values(self, values): # numpydoc ignore=GL08
self.SetAttenuationValues(values)
@property
def transform_matrix(self): # numpydoc ignore=RT01
"""Return (if any) or set the transformation matrix of the light.
The transformation matrix is ``None`` by default, and it is
stored as a ``vtk.vtkMatrix4x4`` object when set. If set, the
light's parameters (position and focal point) are transformed
by the matrix before being rendered. See also the
:py:attr:`world_position` and :py:attr:`world_focal_point`
read-only properties that can differ from :py:attr:`position`
and :py:attr:`focal_point`, respectively.
The 4-by-4 transformation matrix is a tool to encode a general
linear transformation and a translation (an affine
transform). The 3-by-3 principal submatrix (the top left
corner of the matrix) encodes a three-dimensional linear
transformation (e.g. some rotation around the origin). The top
three elements in the last column of the matrix encode a
three-dimensional translation. The last row of the matrix is
redundant.
Examples
--------
Create a light with a transformation matrix that corresponds
to a 90-degree rotation around the z-axis and a shift by (0,
0, -1), and check that the light's position transforms as
expected.
>>> import numpy as np
>>> import pyvista as pv
>>> light = pv.Light(position=(1, 0, 3))
>>> trans = np.zeros((4, 4))
>>> trans[:-1, :-1] = [[0, -1, 0], [1, 0, 0], [0, 0, 1]]
>>> trans[:-1, -1] = [0, 0, -1]
>>> light.transform_matrix = trans
>>> light.position
(1.0, 0.0, 3.0)
>>> light.world_position
(0.0, 1.0, 2.0)
"""
return self.GetTransformMatrix()
@transform_matrix.setter
def transform_matrix(self, matrix): # numpydoc ignore=GL08
if matrix is None or isinstance(matrix, vtkMatrix4x4):
trans = matrix
else:
try:
trans = vtkmatrix_from_array(matrix)
except ValueError:
raise ValueError(
'Transformation matrix must be a 4-by-4 matrix or array-like.',
) from None
self.SetTransformMatrix(trans)
@property
def light_type(self): # numpydoc ignore=RT01
"""Return or set the light type.
The default light type is a scene light which lives in world
coordinate space.
A headlight is attached to the camera and always points at the
camera's focal point.
A camera light also moves with the camera, but it can have an
arbitrary relative position to the camera. Camera lights are
defined in a coordinate space where the camera is located at
(0, 0, 1), looking towards (0, 0, 0) at a distance of 1, with
up being (0, 1, 0). Camera lights use the transform matrix to
establish this space, i.e. they have a fixed :py:attr:`position`
with respect to the camera, and moving the camera only
affects the :py:attr:`world_position` via changes in the
:py:attr:`transform_matrix` (and the same goes for the focal
point).
The property returns class constant values from an enum:
- ``Light.HEADLIGHT == 1``
- ``Light.CAMERA_LIGHT == 2``
- ``Light.SCENE_LIGHT == 3``
If setting the value, either an integer code or a class constant enum
value must be used.
Examples
--------
Check the type of lights for the first two lights of the default
light kit of plotters.
>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> lights = plotter.renderer.lights[:2]
>>> [light.light_type for light in lights]
[<LightType.HEADLIGHT: 1>, <LightType.CAMERA_LIGHT: 2>]
Change the light type of the default light kit's headlight to a scene light.
>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> lights = plotter.renderer.lights[:2]
>>> lights[0].light_type = pv.Light.SCENE_LIGHT
>>> [light.light_type for light in lights]
[<LightType.SCENE_LIGHT: 3>, <LightType.CAMERA_LIGHT: 2>]
"""
return LightType(self.GetLightType())
@light_type.setter
def light_type(self, ltype): # numpydoc ignore=GL08
if not isinstance(ltype, int):
# note that LightType is an int subclass
raise TypeError(
f'Light type must be an integer subclass instance, got {ltype} instead.',
)
self.SetLightType(ltype)
@property
def is_headlight(self): # numpydoc ignore=RT01
"""Return whether the light is a headlight.
Examples
--------
Verify that the first light of the default light kit is a headlight.
>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> lights = plotter.renderer.lights
>>> [light.is_headlight for light in lights]
[True, False, False, False, False]
"""
return bool(self.LightTypeIsHeadlight())
@property
def is_camera_light(self): # numpydoc ignore=RT01
"""Return whether the light is a camera light.
Examples
--------
Verify that four out of five lights of the default light kit
are camera lights.
>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> lights = plotter.renderer.lights
>>> [light.is_camera_light for light in lights]
[False, True, True, True, True]
"""
return bool(self.LightTypeIsCameraLight())
@property
def is_scene_light(self): # numpydoc ignore=RT01
"""Return whether the light is a scene light.
Examples
--------
Verify that none of the lights of the default light kit are
scene lights.
>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> lights = plotter.renderer.lights
>>> [light.is_scene_light for light in lights]
[False, False, False, False, False]
"""
return bool(self.LightTypeIsSceneLight())
def switch_on(self):
"""Switch on the light.
Examples
--------
Create a light, switch it off and switch it back on again.
>>> import pyvista as pv
>>> light = pv.Light()
>>> light.on = False
>>> light.switch_on()
"""
self.SwitchOn()
def switch_off(self):
"""Switch off the light.
Examples
--------
Create a light and switch it off.
>>> import pyvista as pv
>>> light = pv.Light()
>>> light.switch_off()
"""
self.SwitchOff()
def set_direction_angle(self, elev, azim):
"""Set the position and focal point of a directional light.
The light is switched to directional (non-positional). The
focal point is set to the origin. The position is defined in
terms of an elevation and an azimuthal angle, both in degrees.
Note that the equivalent ``vtk.vtkLight.SetDirectionAngle()`` method
uses a surprising coordinate system where the (x', y', z') axes of
the method correspond to the (z, x, y) axes of the renderer.
This method reimplements the functionality in a way that ``elev``
is the conventional elevation and ``azim`` is the conventional azimuth.
In particular:
* ``elev = 0``, ``azim = 0`` is the +x direction
* ``elev = 0``, ``azim = 90`` is the +y direction
* ``elev = 90``, ``azim = 0`` is the +z direction
Parameters
----------
elev : float
The elevation of the directional light.
azim : float
The azimuthal angle of the directional light.
Examples
--------
Create a light that shines on the origin from a 30-degree
elevation in the xz plane.
>>> import pyvista as pv
>>> light = pv.Light()
>>> light.set_direction_angle(30, 0)
"""
self.positional = False
self.focal_point = (0, 0, 0)
theta = np.radians(90 - elev)
phi = np.radians(azim)
self.position = (np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta))
def copy(self, deep=True):
"""Return a shallow or a deep copy of the light.
The only mutable attribute of :class:`pyvista.Light` is the
transformation matrix (if it exists). Thus asking for a
shallow copy merely implies that the returned light and the
original share the transformation matrix instance.
Parameters
----------
deep : bool, default: True
Whether to return a deep copy rather than a shallow
one.
Returns
-------
pyvista.Light
Copied light.
Examples
--------
Create a light and check that it shares a transformation
matrix with its shallow copy.
>>> import pyvista as pv
>>> light = pv.Light()
>>> light.transform_matrix = [
... [1, 0, 0, 0],
... [0, 1, 0, 0],
... [0, 0, 1, 0],
... [0, 0, 0, 1],
... ]
>>> shallow_copied = light.copy(deep=False)
>>> shallow_copied == light
True
>>> shallow_copied.transform_matrix is light.transform_matrix
True
"""
immutable_attrs = [
'light_type',
'position',
'focal_point',
'ambient_color',
'diffuse_color',
'specular_color',
'intensity',
'on',
'positional',
'exponent',
'cone_angle',
'attenuation_values',
'shadow_attenuation',
]
new_light = Light()
for attr in immutable_attrs:
value = getattr(self, attr)
setattr(new_light, attr, value)
if deep and self.transform_matrix is not None:
new_light.transform_matrix = vtkMatrix4x4()
new_light.transform_matrix.DeepCopy(self.transform_matrix)
else:
new_light.transform_matrix = self.transform_matrix
# light actors are private, always copy, but copy visibility state as well
new_light.actor.SetVisibility(self.actor.GetVisibility())
return new_light
def set_headlight(self):
"""Set the light to be a headlight.
Headlights are fixed to the camera and always point to the
focal point of the camera. Calling this method will reset the
light's transformation matrix.
Examples
--------
>>> import pyvista as pv
>>> light = pv.Light()
>>> light.set_headlight()
>>> light.light_type
<LightType.HEADLIGHT: 1>
"""
self.SetLightTypeToHeadlight()
def set_camera_light(self):
"""Set the light to be a camera light.
A camera light moves with the camera, but it can have an
arbitrary relative position to the camera. Camera lights are
defined in a coordinate space where the camera is located at
(0, 0, 1), looking towards (0, 0, 0) at a distance of 1, with
up being (0, 1, 0). Camera lights use the transformation
matrix to establish this space. Calling this method will
reset the light's transformation matrix.
Examples
--------
>>> import pyvista as pv
>>> light = pv.Light()
>>> light.set_camera_light()
>>> light.light_type
<LightType.CAMERA_LIGHT: 2>
"""
self.SetLightTypeToCameraLight()
def set_scene_light(self):
"""Set the light to be a scene light.
Scene lights are stationary with respect to the scene.
Calling this method will reset the light's transformation
matrix.
Examples
--------
>>> import pyvista as pv
>>> light = pv.Light()
>>> light.set_scene_light()
>>> light.light_type
<LightType.SCENE_LIGHT: 3>
"""
self.SetLightTypeToSceneLight()
@classmethod
def from_vtk(cls, vtk_light):
"""Create a light from a ``vtk.vtkLight``, resulting in a copy.
Parameters
----------
vtk_light : vtk.vtkLight
The ``vtk.vtkLight`` to be copied.
Returns
-------
pyvista.Light
Wrapped light.
"""
if not isinstance(vtk_light, vtkLight):
raise TypeError(
f'Expected vtk.vtkLight object, got {type(vtk_light).__name__} instead.',
)
light = cls()
light.light_type = vtk_light.GetLightType() # resets transformation matrix
light.position = vtk_light.GetPosition()
light.focal_point = vtk_light.GetFocalPoint()
light.ambient_color = vtk_light.GetAmbientColor()
light.diffuse_color = vtk_light.GetDiffuseColor()
light.specular_color = vtk_light.GetSpecularColor()
light.intensity = vtk_light.GetIntensity()
light.on = vtk_light.GetSwitch()
light.positional = vtk_light.GetPositional()
light.exponent = vtk_light.GetExponent()
light.cone_angle = vtk_light.GetConeAngle()
light.attenuation_values = vtk_light.GetAttenuationValues()
trans = vtk_light.GetTransformMatrix()
light.transform_matrix = trans
light.shadow_attenuation = vtk_light.GetShadowAttenuation()
return light
def show_actor(self):
"""Show an actor for a spotlight that depicts the geometry of the beam.
For a directional light or a positional light with
:py:attr:`cone_angle` of at least 90 degrees the method
doesn't do anything. If the light is changed so that it
becomes a spotlight, this method has to be called again for
the actor to show. To hide the actor see :func:`hide_actor`.
Examples
--------
Create a scene containing a cube lit with a cyan spotlight and
visualize the light using an actor.
>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(pv.Cube(), color='white')
>>> for light in plotter.renderer.lights:
... light.intensity /= 5
...
>>> spotlight = pv.Light(position=(-1, 1, 1), color='cyan')
>>> spotlight.positional = True
>>> spotlight.cone_angle = 20
>>> spotlight.intensity = 10
>>> spotlight.exponent = 40
>>> spotlight.show_actor()
>>> plotter.add_light(spotlight)
>>> plotter.show()
"""
if not self.positional or self.cone_angle >= 90:
return
self.actor.VisibilityOn()
def hide_actor(self):
"""Hide the actor for a positional light that depicts the geometry of the beam.
For a directional light the function doesn't do anything.
Examples
--------
>>> import pyvista as pv
>>> light = pv.Light()
>>> light.hide_actor()
"""
if not self.positional:
return
self.actor.VisibilityOff()
@property
def renderers(self): # numpydoc ignore=RT01
"""Return the renderers associated with this light."""
return self._renderers
def add_renderer(self, renderer):
"""Attach a renderer to this light.
Parameters
----------
renderer : vtk.vtkRenderer
Renderer.
"""
# quick check to avoid adding twice
if renderer not in self.renderers:
self.renderers.append(renderer)
# verify that the renderer has the light actor if applicable
self._check_actor()
|