plot_axes.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import pyglet.gl as pgl
  2. from pyglet import font
  3. from sympy.core import S
  4. from sympy.plotting.pygletplot.plot_object import PlotObject
  5. from sympy.plotting.pygletplot.util import billboard_matrix, dot_product, \
  6. get_direction_vectors, strided_range, vec_mag, vec_sub
  7. from sympy.utilities.iterables import is_sequence
  8. class PlotAxes(PlotObject):
  9. def __init__(self, *args,
  10. style='', none=None, frame=None, box=None, ordinate=None,
  11. stride=0.25,
  12. visible='', overlay='', colored='', label_axes='', label_ticks='',
  13. tick_length=0.1,
  14. font_face='Arial', font_size=28,
  15. **kwargs):
  16. # initialize style parameter
  17. style = style.lower()
  18. # allow alias kwargs to override style kwarg
  19. if none is not None:
  20. style = 'none'
  21. if frame is not None:
  22. style = 'frame'
  23. if box is not None:
  24. style = 'box'
  25. if ordinate is not None:
  26. style = 'ordinate'
  27. if style in ['', 'ordinate']:
  28. self._render_object = PlotAxesOrdinate(self)
  29. elif style in ['frame', 'box']:
  30. self._render_object = PlotAxesFrame(self)
  31. elif style in ['none']:
  32. self._render_object = None
  33. else:
  34. raise ValueError(("Unrecognized axes style %s.") % (style))
  35. # initialize stride parameter
  36. try:
  37. stride = eval(stride)
  38. except TypeError:
  39. pass
  40. if is_sequence(stride):
  41. if len(stride) != 3:
  42. raise ValueError("length should be equal to 3")
  43. self._stride = stride
  44. else:
  45. self._stride = [stride, stride, stride]
  46. self._tick_length = float(tick_length)
  47. # setup bounding box and ticks
  48. self._origin = [0, 0, 0]
  49. self.reset_bounding_box()
  50. def flexible_boolean(input, default):
  51. if input in [True, False]:
  52. return input
  53. if input in ('f', 'F', 'false', 'False'):
  54. return False
  55. if input in ('t', 'T', 'true', 'True'):
  56. return True
  57. return default
  58. # initialize remaining parameters
  59. self.visible = flexible_boolean(kwargs, True)
  60. self._overlay = flexible_boolean(overlay, True)
  61. self._colored = flexible_boolean(colored, False)
  62. self._label_axes = flexible_boolean(label_axes, False)
  63. self._label_ticks = flexible_boolean(label_ticks, True)
  64. # setup label font
  65. self.font_face = font_face
  66. self.font_size = font_size
  67. # this is also used to reinit the
  68. # font on window close/reopen
  69. self.reset_resources()
  70. def reset_resources(self):
  71. self.label_font = None
  72. def reset_bounding_box(self):
  73. self._bounding_box = [[None, None], [None, None], [None, None]]
  74. self._axis_ticks = [[], [], []]
  75. def draw(self):
  76. if self._render_object:
  77. pgl.glPushAttrib(pgl.GL_ENABLE_BIT | pgl.GL_POLYGON_BIT | pgl.GL_DEPTH_BUFFER_BIT)
  78. if self._overlay:
  79. pgl.glDisable(pgl.GL_DEPTH_TEST)
  80. self._render_object.draw()
  81. pgl.glPopAttrib()
  82. def adjust_bounds(self, child_bounds):
  83. b = self._bounding_box
  84. c = child_bounds
  85. for i in range(3):
  86. if abs(c[i][0]) is S.Infinity or abs(c[i][1]) is S.Infinity:
  87. continue
  88. b[i][0] = c[i][0] if b[i][0] is None else min([b[i][0], c[i][0]])
  89. b[i][1] = c[i][1] if b[i][1] is None else max([b[i][1], c[i][1]])
  90. self._bounding_box = b
  91. self._recalculate_axis_ticks(i)
  92. def _recalculate_axis_ticks(self, axis):
  93. b = self._bounding_box
  94. if b[axis][0] is None or b[axis][1] is None:
  95. self._axis_ticks[axis] = []
  96. else:
  97. self._axis_ticks[axis] = strided_range(b[axis][0], b[axis][1],
  98. self._stride[axis])
  99. def toggle_visible(self):
  100. self.visible = not self.visible
  101. def toggle_colors(self):
  102. self._colored = not self._colored
  103. class PlotAxesBase(PlotObject):
  104. def __init__(self, parent_axes):
  105. self._p = parent_axes
  106. def draw(self):
  107. color = [([0.2, 0.1, 0.3], [0.2, 0.1, 0.3], [0.2, 0.1, 0.3]),
  108. ([0.9, 0.3, 0.5], [0.5, 1.0, 0.5], [0.3, 0.3, 0.9])][self._p._colored]
  109. self.draw_background(color)
  110. self.draw_axis(2, color[2])
  111. self.draw_axis(1, color[1])
  112. self.draw_axis(0, color[0])
  113. def draw_background(self, color):
  114. pass # optional
  115. def draw_axis(self, axis, color):
  116. raise NotImplementedError()
  117. def draw_text(self, text, position, color, scale=1.0):
  118. if len(color) == 3:
  119. color = (color[0], color[1], color[2], 1.0)
  120. if self._p.label_font is None:
  121. self._p.label_font = font.load(self._p.font_face,
  122. self._p.font_size,
  123. bold=True, italic=False)
  124. label = font.Text(self._p.label_font, text,
  125. color=color,
  126. valign=font.Text.BASELINE,
  127. halign=font.Text.CENTER)
  128. pgl.glPushMatrix()
  129. pgl.glTranslatef(*position)
  130. billboard_matrix()
  131. scale_factor = 0.005 * scale
  132. pgl.glScalef(scale_factor, scale_factor, scale_factor)
  133. pgl.glColor4f(0, 0, 0, 0)
  134. label.draw()
  135. pgl.glPopMatrix()
  136. def draw_line(self, v, color):
  137. o = self._p._origin
  138. pgl.glBegin(pgl.GL_LINES)
  139. pgl.glColor3f(*color)
  140. pgl.glVertex3f(v[0][0] + o[0], v[0][1] + o[1], v[0][2] + o[2])
  141. pgl.glVertex3f(v[1][0] + o[0], v[1][1] + o[1], v[1][2] + o[2])
  142. pgl.glEnd()
  143. class PlotAxesOrdinate(PlotAxesBase):
  144. def __init__(self, parent_axes):
  145. super().__init__(parent_axes)
  146. def draw_axis(self, axis, color):
  147. ticks = self._p._axis_ticks[axis]
  148. radius = self._p._tick_length / 2.0
  149. if len(ticks) < 2:
  150. return
  151. # calculate the vector for this axis
  152. axis_lines = [[0, 0, 0], [0, 0, 0]]
  153. axis_lines[0][axis], axis_lines[1][axis] = ticks[0], ticks[-1]
  154. axis_vector = vec_sub(axis_lines[1], axis_lines[0])
  155. # calculate angle to the z direction vector
  156. pos_z = get_direction_vectors()[2]
  157. d = abs(dot_product(axis_vector, pos_z))
  158. d = d / vec_mag(axis_vector)
  159. # don't draw labels if we're looking down the axis
  160. labels_visible = abs(d - 1.0) > 0.02
  161. # draw the ticks and labels
  162. for tick in ticks:
  163. self.draw_tick_line(axis, color, radius, tick, labels_visible)
  164. # draw the axis line and labels
  165. self.draw_axis_line(axis, color, ticks[0], ticks[-1], labels_visible)
  166. def draw_axis_line(self, axis, color, a_min, a_max, labels_visible):
  167. axis_line = [[0, 0, 0], [0, 0, 0]]
  168. axis_line[0][axis], axis_line[1][axis] = a_min, a_max
  169. self.draw_line(axis_line, color)
  170. if labels_visible:
  171. self.draw_axis_line_labels(axis, color, axis_line)
  172. def draw_axis_line_labels(self, axis, color, axis_line):
  173. if not self._p._label_axes:
  174. return
  175. axis_labels = [axis_line[0][::], axis_line[1][::]]
  176. axis_labels[0][axis] -= 0.3
  177. axis_labels[1][axis] += 0.3
  178. a_str = ['X', 'Y', 'Z'][axis]
  179. self.draw_text("-" + a_str, axis_labels[0], color)
  180. self.draw_text("+" + a_str, axis_labels[1], color)
  181. def draw_tick_line(self, axis, color, radius, tick, labels_visible):
  182. tick_axis = {0: 1, 1: 0, 2: 1}[axis]
  183. tick_line = [[0, 0, 0], [0, 0, 0]]
  184. tick_line[0][axis] = tick_line[1][axis] = tick
  185. tick_line[0][tick_axis], tick_line[1][tick_axis] = -radius, radius
  186. self.draw_line(tick_line, color)
  187. if labels_visible:
  188. self.draw_tick_line_label(axis, color, radius, tick)
  189. def draw_tick_line_label(self, axis, color, radius, tick):
  190. if not self._p._label_axes:
  191. return
  192. tick_label_vector = [0, 0, 0]
  193. tick_label_vector[axis] = tick
  194. tick_label_vector[{0: 1, 1: 0, 2: 1}[axis]] = [-1, 1, 1][
  195. axis] * radius * 3.5
  196. self.draw_text(str(tick), tick_label_vector, color, scale=0.5)
  197. class PlotAxesFrame(PlotAxesBase):
  198. def __init__(self, parent_axes):
  199. super().__init__(parent_axes)
  200. def draw_background(self, color):
  201. pass
  202. def draw_axis(self, axis, color):
  203. raise NotImplementedError()