vispy 0.14.0__cp311-cp311-macosx_11_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of vispy might be problematic. Click here for more details.

Files changed (519) hide show
  1. vispy/__init__.py +33 -0
  2. vispy/app/__init__.py +15 -0
  3. vispy/app/_default_app.py +76 -0
  4. vispy/app/_detect_eventloop.py +148 -0
  5. vispy/app/application.py +263 -0
  6. vispy/app/backends/__init__.py +52 -0
  7. vispy/app/backends/_egl.py +264 -0
  8. vispy/app/backends/_glfw.py +513 -0
  9. vispy/app/backends/_jupyter_rfb.py +278 -0
  10. vispy/app/backends/_offscreen_util.py +121 -0
  11. vispy/app/backends/_osmesa.py +235 -0
  12. vispy/app/backends/_pyglet.py +451 -0
  13. vispy/app/backends/_pyqt4.py +36 -0
  14. vispy/app/backends/_pyqt5.py +36 -0
  15. vispy/app/backends/_pyqt6.py +40 -0
  16. vispy/app/backends/_pyside.py +37 -0
  17. vispy/app/backends/_pyside2.py +52 -0
  18. vispy/app/backends/_pyside6.py +53 -0
  19. vispy/app/backends/_qt.py +968 -0
  20. vispy/app/backends/_sdl2.py +444 -0
  21. vispy/app/backends/_template.py +244 -0
  22. vispy/app/backends/_test.py +8 -0
  23. vispy/app/backends/_tk.py +800 -0
  24. vispy/app/backends/_wx.py +476 -0
  25. vispy/app/backends/tests/__init__.py +0 -0
  26. vispy/app/backends/tests/test_offscreen_util.py +52 -0
  27. vispy/app/backends/tests/test_rfb.py +77 -0
  28. vispy/app/base.py +294 -0
  29. vispy/app/canvas.py +828 -0
  30. vispy/app/qt.py +92 -0
  31. vispy/app/tests/__init__.py +0 -0
  32. vispy/app/tests/qt-designer.ui +58 -0
  33. vispy/app/tests/test_app.py +442 -0
  34. vispy/app/tests/test_backends.py +164 -0
  35. vispy/app/tests/test_canvas.py +122 -0
  36. vispy/app/tests/test_context.py +92 -0
  37. vispy/app/tests/test_qt.py +47 -0
  38. vispy/app/tests/test_simultaneous.py +134 -0
  39. vispy/app/timer.py +174 -0
  40. vispy/color/__init__.py +17 -0
  41. vispy/color/_color_dict.py +193 -0
  42. vispy/color/color_array.py +447 -0
  43. vispy/color/color_space.py +181 -0
  44. vispy/color/colormap.py +1134 -0
  45. vispy/color/tests/__init__.py +0 -0
  46. vispy/color/tests/test_color.py +352 -0
  47. vispy/conftest.py +12 -0
  48. vispy/ext/__init__.py +0 -0
  49. vispy/ext/cocoapy.py +1542 -0
  50. vispy/ext/cubehelix.py +138 -0
  51. vispy/ext/egl.py +375 -0
  52. vispy/ext/fontconfig.py +118 -0
  53. vispy/ext/gdi32plus.py +206 -0
  54. vispy/ext/osmesa.py +105 -0
  55. vispy/geometry/__init__.py +23 -0
  56. vispy/geometry/_triangulation_debugger.py +171 -0
  57. vispy/geometry/calculations.py +134 -0
  58. vispy/geometry/curves.py +399 -0
  59. vispy/geometry/generation.py +643 -0
  60. vispy/geometry/isocurve.py +175 -0
  61. vispy/geometry/isosurface.py +465 -0
  62. vispy/geometry/meshdata.py +698 -0
  63. vispy/geometry/normals.py +78 -0
  64. vispy/geometry/parametric.py +56 -0
  65. vispy/geometry/polygon.py +137 -0
  66. vispy/geometry/rect.py +210 -0
  67. vispy/geometry/tests/__init__.py +0 -0
  68. vispy/geometry/tests/test_calculations.py +23 -0
  69. vispy/geometry/tests/test_generation.py +56 -0
  70. vispy/geometry/tests/test_meshdata.py +106 -0
  71. vispy/geometry/tests/test_triangulation.py +506 -0
  72. vispy/geometry/torusknot.py +142 -0
  73. vispy/geometry/triangulation.py +876 -0
  74. vispy/gloo/__init__.py +56 -0
  75. vispy/gloo/buffer.py +505 -0
  76. vispy/gloo/context.py +272 -0
  77. vispy/gloo/framebuffer.py +257 -0
  78. vispy/gloo/gl/__init__.py +234 -0
  79. vispy/gloo/gl/_constants.py +332 -0
  80. vispy/gloo/gl/_es2.py +986 -0
  81. vispy/gloo/gl/_gl2.py +1365 -0
  82. vispy/gloo/gl/_proxy.py +499 -0
  83. vispy/gloo/gl/_pyopengl2.py +362 -0
  84. vispy/gloo/gl/dummy.py +24 -0
  85. vispy/gloo/gl/es2.py +62 -0
  86. vispy/gloo/gl/gl2.py +98 -0
  87. vispy/gloo/gl/glplus.py +168 -0
  88. vispy/gloo/gl/pyopengl2.py +97 -0
  89. vispy/gloo/gl/tests/__init__.py +0 -0
  90. vispy/gloo/gl/tests/test_basics.py +282 -0
  91. vispy/gloo/gl/tests/test_functionality.py +566 -0
  92. vispy/gloo/gl/tests/test_names.py +246 -0
  93. vispy/gloo/gl/tests/test_use.py +71 -0
  94. vispy/gloo/glir.py +1816 -0
  95. vispy/gloo/globject.py +101 -0
  96. vispy/gloo/preprocessor.py +67 -0
  97. vispy/gloo/program.py +543 -0
  98. vispy/gloo/tests/__init__.py +0 -0
  99. vispy/gloo/tests/test_buffer.py +558 -0
  100. vispy/gloo/tests/test_context.py +119 -0
  101. vispy/gloo/tests/test_framebuffer.py +195 -0
  102. vispy/gloo/tests/test_glir.py +307 -0
  103. vispy/gloo/tests/test_globject.py +35 -0
  104. vispy/gloo/tests/test_program.py +302 -0
  105. vispy/gloo/tests/test_texture.py +732 -0
  106. vispy/gloo/tests/test_use_gloo.py +187 -0
  107. vispy/gloo/tests/test_util.py +60 -0
  108. vispy/gloo/tests/test_wrappers.py +261 -0
  109. vispy/gloo/texture.py +1045 -0
  110. vispy/gloo/util.py +129 -0
  111. vispy/gloo/wrappers.py +762 -0
  112. vispy/glsl/__init__.py +42 -0
  113. vispy/glsl/antialias/antialias.glsl +7 -0
  114. vispy/glsl/antialias/cap-butt.glsl +31 -0
  115. vispy/glsl/antialias/cap-round.glsl +29 -0
  116. vispy/glsl/antialias/cap-square.glsl +30 -0
  117. vispy/glsl/antialias/cap-triangle-in.glsl +30 -0
  118. vispy/glsl/antialias/cap-triangle-out.glsl +30 -0
  119. vispy/glsl/antialias/cap.glsl +67 -0
  120. vispy/glsl/antialias/caps.glsl +67 -0
  121. vispy/glsl/antialias/filled.glsl +50 -0
  122. vispy/glsl/antialias/outline.glsl +40 -0
  123. vispy/glsl/antialias/stroke.glsl +43 -0
  124. vispy/glsl/arrowheads/angle.glsl +99 -0
  125. vispy/glsl/arrowheads/arrowheads.frag +60 -0
  126. vispy/glsl/arrowheads/arrowheads.glsl +12 -0
  127. vispy/glsl/arrowheads/arrowheads.vert +83 -0
  128. vispy/glsl/arrowheads/curved.glsl +48 -0
  129. vispy/glsl/arrowheads/inhibitor.glsl +26 -0
  130. vispy/glsl/arrowheads/stealth.glsl +46 -0
  131. vispy/glsl/arrowheads/triangle.glsl +97 -0
  132. vispy/glsl/arrowheads/util.glsl +13 -0
  133. vispy/glsl/arrows/angle-30.glsl +12 -0
  134. vispy/glsl/arrows/angle-60.glsl +12 -0
  135. vispy/glsl/arrows/angle-90.glsl +12 -0
  136. vispy/glsl/arrows/arrow.frag +39 -0
  137. vispy/glsl/arrows/arrow.vert +49 -0
  138. vispy/glsl/arrows/arrows.glsl +17 -0
  139. vispy/glsl/arrows/common.glsl +187 -0
  140. vispy/glsl/arrows/curved.glsl +63 -0
  141. vispy/glsl/arrows/stealth.glsl +50 -0
  142. vispy/glsl/arrows/triangle-30.glsl +12 -0
  143. vispy/glsl/arrows/triangle-60.glsl +12 -0
  144. vispy/glsl/arrows/triangle-90.glsl +12 -0
  145. vispy/glsl/arrows/util.glsl +98 -0
  146. vispy/glsl/build_spatial_filters.py +660 -0
  147. vispy/glsl/collections/agg-fast-path.frag +20 -0
  148. vispy/glsl/collections/agg-fast-path.vert +78 -0
  149. vispy/glsl/collections/agg-glyph.frag +60 -0
  150. vispy/glsl/collections/agg-glyph.vert +33 -0
  151. vispy/glsl/collections/agg-marker.frag +35 -0
  152. vispy/glsl/collections/agg-marker.vert +48 -0
  153. vispy/glsl/collections/agg-path.frag +55 -0
  154. vispy/glsl/collections/agg-path.vert +166 -0
  155. vispy/glsl/collections/agg-point.frag +21 -0
  156. vispy/glsl/collections/agg-point.vert +35 -0
  157. vispy/glsl/collections/agg-segment.frag +32 -0
  158. vispy/glsl/collections/agg-segment.vert +75 -0
  159. vispy/glsl/collections/marker.frag +38 -0
  160. vispy/glsl/collections/marker.vert +48 -0
  161. vispy/glsl/collections/raw-path.frag +15 -0
  162. vispy/glsl/collections/raw-path.vert +24 -0
  163. vispy/glsl/collections/raw-point.frag +14 -0
  164. vispy/glsl/collections/raw-point.vert +31 -0
  165. vispy/glsl/collections/raw-segment.frag +18 -0
  166. vispy/glsl/collections/raw-segment.vert +26 -0
  167. vispy/glsl/collections/raw-triangle.frag +13 -0
  168. vispy/glsl/collections/raw-triangle.vert +26 -0
  169. vispy/glsl/collections/sdf-glyph-ticks.vert +69 -0
  170. vispy/glsl/collections/sdf-glyph.frag +80 -0
  171. vispy/glsl/collections/sdf-glyph.vert +59 -0
  172. vispy/glsl/collections/tick-labels.vert +71 -0
  173. vispy/glsl/colormaps/autumn.glsl +20 -0
  174. vispy/glsl/colormaps/blues.glsl +20 -0
  175. vispy/glsl/colormaps/color-space.glsl +17 -0
  176. vispy/glsl/colormaps/colormaps.glsl +24 -0
  177. vispy/glsl/colormaps/cool.glsl +20 -0
  178. vispy/glsl/colormaps/fire.glsl +21 -0
  179. vispy/glsl/colormaps/gray.glsl +20 -0
  180. vispy/glsl/colormaps/greens.glsl +20 -0
  181. vispy/glsl/colormaps/hot.glsl +22 -0
  182. vispy/glsl/colormaps/ice.glsl +20 -0
  183. vispy/glsl/colormaps/icefire.glsl +23 -0
  184. vispy/glsl/colormaps/parse.py +40 -0
  185. vispy/glsl/colormaps/reds.glsl +20 -0
  186. vispy/glsl/colormaps/spring.glsl +20 -0
  187. vispy/glsl/colormaps/summer.glsl +20 -0
  188. vispy/glsl/colormaps/user.glsl +22 -0
  189. vispy/glsl/colormaps/util.glsl +41 -0
  190. vispy/glsl/colormaps/wheel.glsl +21 -0
  191. vispy/glsl/colormaps/winter.glsl +20 -0
  192. vispy/glsl/lines/agg.frag +320 -0
  193. vispy/glsl/lines/agg.vert +241 -0
  194. vispy/glsl/markers/arrow.glsl +12 -0
  195. vispy/glsl/markers/asterisk.glsl +16 -0
  196. vispy/glsl/markers/chevron.glsl +14 -0
  197. vispy/glsl/markers/clover.glsl +20 -0
  198. vispy/glsl/markers/club.glsl +31 -0
  199. vispy/glsl/markers/cross.glsl +17 -0
  200. vispy/glsl/markers/diamond.glsl +12 -0
  201. vispy/glsl/markers/disc.glsl +9 -0
  202. vispy/glsl/markers/ellipse.glsl +67 -0
  203. vispy/glsl/markers/hbar.glsl +9 -0
  204. vispy/glsl/markers/heart.glsl +15 -0
  205. vispy/glsl/markers/infinity.glsl +15 -0
  206. vispy/glsl/markers/marker-sdf.frag +74 -0
  207. vispy/glsl/markers/marker-sdf.vert +41 -0
  208. vispy/glsl/markers/marker.frag +36 -0
  209. vispy/glsl/markers/marker.vert +46 -0
  210. vispy/glsl/markers/markers.glsl +24 -0
  211. vispy/glsl/markers/pin.glsl +18 -0
  212. vispy/glsl/markers/ring.glsl +11 -0
  213. vispy/glsl/markers/spade.glsl +28 -0
  214. vispy/glsl/markers/square.glsl +10 -0
  215. vispy/glsl/markers/tag.glsl +11 -0
  216. vispy/glsl/markers/triangle.glsl +14 -0
  217. vispy/glsl/markers/vbar.glsl +9 -0
  218. vispy/glsl/math/circle-through-2-points.glsl +30 -0
  219. vispy/glsl/math/constants.glsl +48 -0
  220. vispy/glsl/math/double.glsl +114 -0
  221. vispy/glsl/math/functions.glsl +20 -0
  222. vispy/glsl/math/point-to-line-distance.glsl +31 -0
  223. vispy/glsl/math/point-to-line-projection.glsl +29 -0
  224. vispy/glsl/math/signed-line-distance.glsl +27 -0
  225. vispy/glsl/math/signed-segment-distance.glsl +30 -0
  226. vispy/glsl/misc/regular-grid.frag +244 -0
  227. vispy/glsl/misc/spatial-filters.frag +1407 -0
  228. vispy/glsl/misc/viewport-NDC.glsl +20 -0
  229. vispy/glsl/transforms/azimuthal-equal-area.glsl +32 -0
  230. vispy/glsl/transforms/azimuthal-equidistant.glsl +38 -0
  231. vispy/glsl/transforms/hammer.glsl +44 -0
  232. vispy/glsl/transforms/identity.glsl +6 -0
  233. vispy/glsl/transforms/identity_forward.glsl +23 -0
  234. vispy/glsl/transforms/identity_inverse.glsl +23 -0
  235. vispy/glsl/transforms/linear-scale.glsl +127 -0
  236. vispy/glsl/transforms/log-scale.glsl +126 -0
  237. vispy/glsl/transforms/mercator-transverse-forward.glsl +40 -0
  238. vispy/glsl/transforms/mercator-transverse-inverse.glsl +40 -0
  239. vispy/glsl/transforms/panzoom.glsl +10 -0
  240. vispy/glsl/transforms/polar.glsl +41 -0
  241. vispy/glsl/transforms/position.glsl +44 -0
  242. vispy/glsl/transforms/power-scale.glsl +139 -0
  243. vispy/glsl/transforms/projection.glsl +7 -0
  244. vispy/glsl/transforms/pvm.glsl +13 -0
  245. vispy/glsl/transforms/rotate.glsl +45 -0
  246. vispy/glsl/transforms/trackball.glsl +15 -0
  247. vispy/glsl/transforms/translate.glsl +35 -0
  248. vispy/glsl/transforms/transverse_mercator.glsl +38 -0
  249. vispy/glsl/transforms/viewport-clipping.glsl +14 -0
  250. vispy/glsl/transforms/viewport-transform.glsl +16 -0
  251. vispy/glsl/transforms/viewport.glsl +50 -0
  252. vispy/glsl/transforms/x.glsl +24 -0
  253. vispy/glsl/transforms/y.glsl +19 -0
  254. vispy/glsl/transforms/z.glsl +14 -0
  255. vispy/io/__init__.py +20 -0
  256. vispy/io/_data/spatial-filters.npy +0 -0
  257. vispy/io/datasets.py +94 -0
  258. vispy/io/image.py +231 -0
  259. vispy/io/mesh.py +122 -0
  260. vispy/io/stl.py +167 -0
  261. vispy/io/tests/__init__.py +0 -0
  262. vispy/io/tests/test_image.py +47 -0
  263. vispy/io/tests/test_io.py +121 -0
  264. vispy/io/wavefront.py +350 -0
  265. vispy/plot/__init__.py +36 -0
  266. vispy/plot/fig.py +58 -0
  267. vispy/plot/plotwidget.py +522 -0
  268. vispy/plot/tests/__init__.py +0 -0
  269. vispy/plot/tests/test_plot.py +46 -0
  270. vispy/scene/__init__.py +43 -0
  271. vispy/scene/cameras/__init__.py +27 -0
  272. vispy/scene/cameras/_base.py +38 -0
  273. vispy/scene/cameras/arcball.py +106 -0
  274. vispy/scene/cameras/base_camera.py +538 -0
  275. vispy/scene/cameras/fly.py +474 -0
  276. vispy/scene/cameras/magnify.py +163 -0
  277. vispy/scene/cameras/panzoom.py +308 -0
  278. vispy/scene/cameras/perspective.py +333 -0
  279. vispy/scene/cameras/tests/__init__.py +0 -0
  280. vispy/scene/cameras/tests/test_cameras.py +27 -0
  281. vispy/scene/cameras/tests/test_link.py +53 -0
  282. vispy/scene/cameras/tests/test_perspective.py +122 -0
  283. vispy/scene/cameras/turntable.py +173 -0
  284. vispy/scene/canvas.py +639 -0
  285. vispy/scene/events.py +85 -0
  286. vispy/scene/node.py +644 -0
  287. vispy/scene/subscene.py +20 -0
  288. vispy/scene/tests/__init__.py +0 -0
  289. vispy/scene/tests/test_canvas.py +119 -0
  290. vispy/scene/tests/test_node.py +142 -0
  291. vispy/scene/tests/test_visuals.py +141 -0
  292. vispy/scene/visuals.py +276 -0
  293. vispy/scene/widgets/__init__.py +18 -0
  294. vispy/scene/widgets/anchor.py +25 -0
  295. vispy/scene/widgets/axis.py +88 -0
  296. vispy/scene/widgets/colorbar.py +176 -0
  297. vispy/scene/widgets/console.py +351 -0
  298. vispy/scene/widgets/grid.py +509 -0
  299. vispy/scene/widgets/label.py +50 -0
  300. vispy/scene/widgets/tests/__init__.py +0 -0
  301. vispy/scene/widgets/tests/test_colorbar.py +47 -0
  302. vispy/scene/widgets/viewbox.py +199 -0
  303. vispy/scene/widgets/widget.py +478 -0
  304. vispy/testing/__init__.py +51 -0
  305. vispy/testing/_runners.py +446 -0
  306. vispy/testing/_testing.py +416 -0
  307. vispy/testing/image_tester.py +473 -0
  308. vispy/testing/rendered_array_tester.py +85 -0
  309. vispy/testing/tests/__init__.py +0 -0
  310. vispy/testing/tests/test_testing.py +20 -0
  311. vispy/util/__init__.py +17 -0
  312. vispy/util/bunch.py +15 -0
  313. vispy/util/check_environment.py +57 -0
  314. vispy/util/config.py +490 -0
  315. vispy/util/dpi/__init__.py +19 -0
  316. vispy/util/dpi/_linux.py +69 -0
  317. vispy/util/dpi/_quartz.py +26 -0
  318. vispy/util/dpi/_win32.py +34 -0
  319. vispy/util/dpi/tests/__init__.py +0 -0
  320. vispy/util/dpi/tests/test_dpi.py +16 -0
  321. vispy/util/eq.py +41 -0
  322. vispy/util/event.py +774 -0
  323. vispy/util/fetching.py +276 -0
  324. vispy/util/filter.py +44 -0
  325. vispy/util/fonts/__init__.py +14 -0
  326. vispy/util/fonts/_freetype.py +73 -0
  327. vispy/util/fonts/_quartz.py +192 -0
  328. vispy/util/fonts/_triage.py +36 -0
  329. vispy/util/fonts/_vispy_fonts.py +20 -0
  330. vispy/util/fonts/_win32.py +105 -0
  331. vispy/util/fonts/data/OpenSans-Bold.ttf +0 -0
  332. vispy/util/fonts/data/OpenSans-BoldItalic.ttf +0 -0
  333. vispy/util/fonts/data/OpenSans-Italic.ttf +0 -0
  334. vispy/util/fonts/data/OpenSans-Regular.ttf +0 -0
  335. vispy/util/fonts/tests/__init__.py +0 -0
  336. vispy/util/fonts/tests/test_font.py +45 -0
  337. vispy/util/fourier.py +69 -0
  338. vispy/util/frozen.py +25 -0
  339. vispy/util/gallery_scraper.py +268 -0
  340. vispy/util/keys.py +91 -0
  341. vispy/util/logs.py +358 -0
  342. vispy/util/osmesa_gl.py +17 -0
  343. vispy/util/profiler.py +135 -0
  344. vispy/util/ptime.py +16 -0
  345. vispy/util/quaternion.py +229 -0
  346. vispy/util/svg/__init__.py +18 -0
  347. vispy/util/svg/base.py +20 -0
  348. vispy/util/svg/color.py +219 -0
  349. vispy/util/svg/element.py +51 -0
  350. vispy/util/svg/geometry.py +478 -0
  351. vispy/util/svg/group.py +66 -0
  352. vispy/util/svg/length.py +81 -0
  353. vispy/util/svg/number.py +25 -0
  354. vispy/util/svg/path.py +332 -0
  355. vispy/util/svg/shapes.py +57 -0
  356. vispy/util/svg/style.py +59 -0
  357. vispy/util/svg/svg.py +40 -0
  358. vispy/util/svg/transform.py +223 -0
  359. vispy/util/svg/transformable.py +28 -0
  360. vispy/util/svg/viewport.py +73 -0
  361. vispy/util/tests/__init__.py +0 -0
  362. vispy/util/tests/test_config.py +58 -0
  363. vispy/util/tests/test_docstring_parameters.py +123 -0
  364. vispy/util/tests/test_emitter_group.py +262 -0
  365. vispy/util/tests/test_event_emitter.py +743 -0
  366. vispy/util/tests/test_fourier.py +35 -0
  367. vispy/util/tests/test_gallery_scraper.py +112 -0
  368. vispy/util/tests/test_import.py +127 -0
  369. vispy/util/tests/test_key.py +22 -0
  370. vispy/util/tests/test_logging.py +45 -0
  371. vispy/util/tests/test_run.py +14 -0
  372. vispy/util/tests/test_transforms.py +42 -0
  373. vispy/util/tests/test_vispy.py +48 -0
  374. vispy/util/transforms.py +201 -0
  375. vispy/util/wrappers.py +155 -0
  376. vispy/version.py +4 -0
  377. vispy/visuals/__init__.py +50 -0
  378. vispy/visuals/_scalable_textures.py +485 -0
  379. vispy/visuals/axis.py +678 -0
  380. vispy/visuals/border.py +208 -0
  381. vispy/visuals/box.py +79 -0
  382. vispy/visuals/collections/__init__.py +30 -0
  383. vispy/visuals/collections/agg_fast_path_collection.py +219 -0
  384. vispy/visuals/collections/agg_path_collection.py +197 -0
  385. vispy/visuals/collections/agg_point_collection.py +52 -0
  386. vispy/visuals/collections/agg_segment_collection.py +142 -0
  387. vispy/visuals/collections/array_list.py +401 -0
  388. vispy/visuals/collections/base_collection.py +482 -0
  389. vispy/visuals/collections/collection.py +253 -0
  390. vispy/visuals/collections/path_collection.py +23 -0
  391. vispy/visuals/collections/point_collection.py +19 -0
  392. vispy/visuals/collections/polygon_collection.py +25 -0
  393. vispy/visuals/collections/raw_path_collection.py +119 -0
  394. vispy/visuals/collections/raw_point_collection.py +113 -0
  395. vispy/visuals/collections/raw_polygon_collection.py +77 -0
  396. vispy/visuals/collections/raw_segment_collection.py +112 -0
  397. vispy/visuals/collections/raw_triangle_collection.py +78 -0
  398. vispy/visuals/collections/segment_collection.py +19 -0
  399. vispy/visuals/collections/triangle_collection.py +16 -0
  400. vispy/visuals/collections/util.py +168 -0
  401. vispy/visuals/colorbar.py +699 -0
  402. vispy/visuals/cube.py +41 -0
  403. vispy/visuals/ellipse.py +163 -0
  404. vispy/visuals/filters/__init__.py +10 -0
  405. vispy/visuals/filters/base_filter.py +242 -0
  406. vispy/visuals/filters/clipper.py +60 -0
  407. vispy/visuals/filters/clipping_planes.py +122 -0
  408. vispy/visuals/filters/color.py +181 -0
  409. vispy/visuals/filters/markers.py +28 -0
  410. vispy/visuals/filters/mesh.py +796 -0
  411. vispy/visuals/filters/picking.py +60 -0
  412. vispy/visuals/filters/tests/__init__.py +3 -0
  413. vispy/visuals/filters/tests/test_primitive_picking_filters.py +70 -0
  414. vispy/visuals/filters/tests/test_wireframe_filter.py +16 -0
  415. vispy/visuals/glsl/__init__.py +1 -0
  416. vispy/visuals/glsl/antialiasing.py +133 -0
  417. vispy/visuals/glsl/color.py +63 -0
  418. vispy/visuals/graphs/__init__.py +1 -0
  419. vispy/visuals/graphs/graph.py +240 -0
  420. vispy/visuals/graphs/layouts/__init__.py +55 -0
  421. vispy/visuals/graphs/layouts/circular.py +49 -0
  422. vispy/visuals/graphs/layouts/force_directed.py +211 -0
  423. vispy/visuals/graphs/layouts/networkx_layout.py +87 -0
  424. vispy/visuals/graphs/layouts/random.py +52 -0
  425. vispy/visuals/graphs/tests/__init__.py +1 -0
  426. vispy/visuals/graphs/tests/test_layouts.py +139 -0
  427. vispy/visuals/graphs/tests/test_networkx_layout.py +47 -0
  428. vispy/visuals/graphs/util.py +120 -0
  429. vispy/visuals/gridlines.py +105 -0
  430. vispy/visuals/gridmesh.py +98 -0
  431. vispy/visuals/histogram.py +58 -0
  432. vispy/visuals/image.py +688 -0
  433. vispy/visuals/image_complex.py +130 -0
  434. vispy/visuals/infinite_line.py +199 -0
  435. vispy/visuals/instanced_mesh.py +152 -0
  436. vispy/visuals/isocurve.py +213 -0
  437. vispy/visuals/isoline.py +241 -0
  438. vispy/visuals/isosurface.py +113 -0
  439. vispy/visuals/line/__init__.py +6 -0
  440. vispy/visuals/line/arrow.py +289 -0
  441. vispy/visuals/line/dash_atlas.py +90 -0
  442. vispy/visuals/line/line.py +545 -0
  443. vispy/visuals/line_plot.py +135 -0
  444. vispy/visuals/linear_region.py +199 -0
  445. vispy/visuals/markers.py +810 -0
  446. vispy/visuals/mesh.py +373 -0
  447. vispy/visuals/mesh_normals.py +159 -0
  448. vispy/visuals/plane.py +54 -0
  449. vispy/visuals/polygon.py +145 -0
  450. vispy/visuals/rectangle.py +196 -0
  451. vispy/visuals/regular_polygon.py +56 -0
  452. vispy/visuals/scrolling_lines.py +197 -0
  453. vispy/visuals/shaders/__init__.py +17 -0
  454. vispy/visuals/shaders/compiler.py +206 -0
  455. vispy/visuals/shaders/expression.py +99 -0
  456. vispy/visuals/shaders/function.py +788 -0
  457. vispy/visuals/shaders/multiprogram.py +145 -0
  458. vispy/visuals/shaders/parsing.py +140 -0
  459. vispy/visuals/shaders/program.py +161 -0
  460. vispy/visuals/shaders/shader_object.py +162 -0
  461. vispy/visuals/shaders/tests/__init__.py +0 -0
  462. vispy/visuals/shaders/tests/test_function.py +486 -0
  463. vispy/visuals/shaders/tests/test_multiprogram.py +78 -0
  464. vispy/visuals/shaders/tests/test_parsing.py +57 -0
  465. vispy/visuals/shaders/variable.py +272 -0
  466. vispy/visuals/spectrogram.py +169 -0
  467. vispy/visuals/sphere.py +80 -0
  468. vispy/visuals/surface_plot.py +192 -0
  469. vispy/visuals/tests/__init__.py +0 -0
  470. vispy/visuals/tests/test_arrows.py +109 -0
  471. vispy/visuals/tests/test_axis.py +120 -0
  472. vispy/visuals/tests/test_collections.py +15 -0
  473. vispy/visuals/tests/test_colorbar.py +179 -0
  474. vispy/visuals/tests/test_colormap.py +97 -0
  475. vispy/visuals/tests/test_ellipse.py +122 -0
  476. vispy/visuals/tests/test_histogram.py +24 -0
  477. vispy/visuals/tests/test_image.py +390 -0
  478. vispy/visuals/tests/test_image_complex.py +36 -0
  479. vispy/visuals/tests/test_infinite_line.py +53 -0
  480. vispy/visuals/tests/test_instanced_mesh.py +50 -0
  481. vispy/visuals/tests/test_isosurface.py +22 -0
  482. vispy/visuals/tests/test_linear_region.py +152 -0
  483. vispy/visuals/tests/test_markers.py +54 -0
  484. vispy/visuals/tests/test_mesh.py +261 -0
  485. vispy/visuals/tests/test_mesh_normals.py +218 -0
  486. vispy/visuals/tests/test_polygon.py +112 -0
  487. vispy/visuals/tests/test_rectangle.py +163 -0
  488. vispy/visuals/tests/test_regular_polygon.py +111 -0
  489. vispy/visuals/tests/test_scalable_textures.py +180 -0
  490. vispy/visuals/tests/test_sdf.py +73 -0
  491. vispy/visuals/tests/test_spectrogram.py +42 -0
  492. vispy/visuals/tests/test_text.py +95 -0
  493. vispy/visuals/tests/test_volume.py +542 -0
  494. vispy/visuals/tests/test_windbarb.py +33 -0
  495. vispy/visuals/text/__init__.py +7 -0
  496. vispy/visuals/text/_sdf_cpu.cpython-311-darwin.so +0 -0
  497. vispy/visuals/text/_sdf_cpu.pyx +110 -0
  498. vispy/visuals/text/_sdf_gpu.py +316 -0
  499. vispy/visuals/text/text.py +675 -0
  500. vispy/visuals/transforms/__init__.py +34 -0
  501. vispy/visuals/transforms/_util.py +191 -0
  502. vispy/visuals/transforms/base_transform.py +233 -0
  503. vispy/visuals/transforms/chain.py +300 -0
  504. vispy/visuals/transforms/interactive.py +98 -0
  505. vispy/visuals/transforms/linear.py +564 -0
  506. vispy/visuals/transforms/nonlinear.py +398 -0
  507. vispy/visuals/transforms/tests/__init__.py +0 -0
  508. vispy/visuals/transforms/tests/test_transforms.py +243 -0
  509. vispy/visuals/transforms/transform_system.py +339 -0
  510. vispy/visuals/tube.py +173 -0
  511. vispy/visuals/visual.py +923 -0
  512. vispy/visuals/volume.py +1335 -0
  513. vispy/visuals/windbarb.py +291 -0
  514. vispy/visuals/xyz_axis.py +34 -0
  515. vispy-0.14.0.dist-info/LICENSE.txt +36 -0
  516. vispy-0.14.0.dist-info/METADATA +218 -0
  517. vispy-0.14.0.dist-info/RECORD +519 -0
  518. vispy-0.14.0.dist-info/WHEEL +5 -0
  519. vispy-0.14.0.dist-info/top_level.txt +1 -0
vispy/gloo/glir.py ADDED
@@ -0,0 +1,1816 @@
1
+ # -*- coding: utf-8 -*-
2
+ # -----------------------------------------------------------------------------
3
+ # Copyright (c) Vispy Development Team. All Rights Reserved.
4
+ # Distributed under the (new) BSD License. See LICENSE.txt for more info.
5
+ # -----------------------------------------------------------------------------
6
+
7
+ """GL Intermediate Representation Desktop Implementation
8
+ =====================================================
9
+
10
+ The glir module holds the desktop implementation of the GL Intermediate
11
+ Representation (GLIR). Parsing and handling of the GLIR for other platforms
12
+ can be found in external libraries.
13
+
14
+ We propose the specification of a simple intermediate representation for
15
+ OpenGL. It provides a means to serialize a visualization, so that the
16
+ high-level API and the part that does the GL commands can be separated,
17
+ and even be in separate processes.
18
+
19
+ GLIR is a high level representation that consists of commands without
20
+ return values. In effect, the commands can be streamed from one node to
21
+ another without having to wait for a reply. Only in the event of an
22
+ error information needs to go in the other direction, but this can be
23
+ done asynchronously.
24
+
25
+ The purpose for GLIR has been to allow the usage gloo (our high level object
26
+ oriented interface to OpenGL), while executing the visualization in the
27
+ browser (via JS/WebGL). The fact that the stream of commands is
28
+ one-directional is essential to realize reactive visualizations.
29
+
30
+ The separation between API and implementation also provides a nice
31
+ abstraction leading to cleaner code.
32
+
33
+ GLIR commands are represented as tuples. As such the overhead for
34
+ "parsing" the commands is minimal. The commands can, however, be
35
+ serialized so they can be send to another process. Further, a series of
36
+ GLIR commands can be stored in a file. This way we can store
37
+ visualizations to disk that can be displayed with any application that
38
+ can interpret GLIR.
39
+
40
+ The GLIR specification is tied to the version of the vispy python library
41
+ that supports it. The current specification described below was first
42
+ created for::
43
+
44
+ VisPy 0.6
45
+
46
+ The shape of a command
47
+ ~~~~~~~~~~~~~~~~~~~~~~
48
+
49
+ GLIR consists of a sequence of commands that are defined as tuples. Each
50
+ command has the following shape:
51
+
52
+ ::
53
+
54
+ (<command>, <ID>, [arg1, [arg2, [arg3]]])
55
+
56
+ - ``<command>`` is one of 15 commands: CURRENT, CREATE, DELETE,
57
+ UNIFORM, ATTRIBUTE, DRAW, SIZE, DATA, WRAPPING,
58
+ INTERPOLATION, ATTACH, FRAMEBUFFER, FUNC, SWAP, LINK.
59
+ - In all commands except SET, ``<ID>`` is an integer unique within the
60
+ current GL context that is used as a reference to a GL object. It is
61
+ the responsibility of the code that generates the command to keep
62
+ track of id's and to ensure that they are unique.
63
+ - The number of arguments and their type differs per command and are
64
+ explained further below.
65
+ - Some commands accept GL enums in the form of a string. In these cases
66
+ the enum can also be given as an int, but a string is recommended for
67
+ better debugging. The string is case insensitive.
68
+
69
+ CURRENT
70
+ ~~~~~~~
71
+
72
+ ::
73
+
74
+ ('CURRENT', 0)
75
+
76
+ Will be called when the context is made current. The GLIR implementation
77
+ can use this to reset some caches.
78
+
79
+ CREATE
80
+ ~~~~~~
81
+
82
+ ::
83
+
84
+ ('CREATE', <id>, <class:str>)
85
+ # Example:
86
+ ('CREATE', 4, 'VertexBuffer')
87
+
88
+ Applies to: All objects
89
+
90
+ The create command is used to create a new GL object. It has one string
91
+ argument that can be any of 10 classes: 'Program', 'VertexBuffer',
92
+ 'IndexBuffer', 'Texture2D', 'Texture3D', 'RenderBuffer', 'FrameBuffer',
93
+ 'VertexShader', 'FragmentShader', 'GeometryShader'
94
+
95
+ DELETE
96
+ ~~~~~~
97
+
98
+ ::
99
+
100
+ ('DELETE', <id>)
101
+ # Example:
102
+ ('DELETE', 4)
103
+
104
+ Applies to: All objects
105
+
106
+ The delete command is used to delete the GL object corresponding to the
107
+ given id. If the id does not exist, this command is ignored. This
108
+ command does not have arguments. When used with Shader objects, the
109
+ shader is freed from GPU memory.
110
+
111
+ UNIFORM
112
+ ~~~~~~~
113
+
114
+ ::
115
+
116
+ ('UNIFORM', <program_id>, <name:str>, <type:str>, <value>)
117
+ # Examples:
118
+ ('UNIFORM', 4, 'u_scale', 'vec3', <array 3>)
119
+
120
+ Applies to: Program
121
+
122
+ This command is used to set the uniform of a program object. A uniform
123
+ has a string name, a type, and a value.
124
+
125
+ The type can be 'float', 'vec2', 'vec3', 'vec4', 'int', 'ivec2',
126
+ 'ivec3', 'ivec4', 'bool', 'bvec2', 'bvec3', 'bvec4', 'mat2', 'mat3',
127
+ 'mat4'. The value must be tuple or array with number of elements that
128
+ matches with the type.
129
+
130
+ It is an error to provide this command before the shaders are set. After
131
+ resetting shaders, all uniforms and attributes have to be re-submitted.
132
+
133
+ Discussion: for the uniform and attribute commands, the type argument
134
+ should not strictly be necessary, but it makes the GLIR implementation
135
+ simpler. Plus in gloo we *have* this information.
136
+
137
+ TEXTURE
138
+ ~~~~~~~
139
+
140
+ ::
141
+
142
+ ('TEXTURE', <program_id>, <name:str>, <texture_id>)
143
+ # Examples:
144
+ ('TEXTURE', 4, 'u_texture1', 6)
145
+
146
+ Applies to: Program
147
+
148
+ This command is used to link a texture to a GLSL uniform sampler.
149
+
150
+ ATTRIBUTE
151
+ ~~~~~~~~~
152
+
153
+ ::
154
+
155
+ ('ATTRIBUTE', <program_id>, <name:str>, <type:str>, <vbo_id>, <stride:int>, <offset:int>)
156
+ # Example: Buffer id 5, stride 4, offset 0
157
+ ('ATTRIBUTE', 4, 'a_position', 'vec3', 5, 4, 0)
158
+
159
+ Applies to: Program
160
+
161
+ This command is used to set the attribute of a program object. An
162
+ attribute has a string name, a type, and a value.
163
+
164
+ The type can be 'float', 'vec2', 'vec3', 'vec4'. If the first value
165
+ element is zero, the remaining elements represent the data to pass to
166
+ ``glVertexAttribNf``.
167
+
168
+ It is an error to provide this command before the shaders are set. After
169
+ resetting shaders, all uniforms and attributes have to be re-submitted.
170
+
171
+ DRAW
172
+ ~~~~
173
+
174
+ ::
175
+
176
+ ('DRAW', <program_id>, <mode:str>, <selection:tuple>, <instances:int>)
177
+ # Example: Draw 100 lines with non-instanced rendering
178
+ ('DRAW', 4, 'lines', (0, 100), 1)
179
+ # Example: Draw 100 lines using index buffer with id 5
180
+ ('DRAW', 4, 'points', (5, 'unsigned_int', 100), 1)
181
+ # Example: Draw a mesh with 10 vertices 20 times using instanced rendering
182
+ ('DRAW', 2, 'mesh', (0, 10), 20)
183
+
184
+ Applies to: Program
185
+
186
+ This command is used to draw the program. It has a ``mode`` argument
187
+ which can be 'points', 'lines', 'line_strip', 'line_loop', 'lines_adjacency',
188
+ 'line_strip_adjacency', 'triangles', 'triangle_strip', or 'triangle_fan'
189
+ (case insensitive).
190
+
191
+ If the ``selection`` argument has two elements, it contains two integers
192
+ ``(start, count)``. If it has three elements, it contains
193
+ ``(<index-buffer-id>, gtype, count)``, where ``gtype`` is
194
+ 'unsigned_byte','unsigned_short', or 'unsigned_int'.
195
+
196
+ SIZE
197
+ ~~~~
198
+
199
+ ::
200
+
201
+ ('SIZE', <id>, <size>, [<format>], [<internalformat>])
202
+ # Example: resize a buffer
203
+ ('SIZE', 4, 500)
204
+ # Example: resize a 2D texture
205
+ ('SIZE', 4, (500, 300, 3), 'rgb', None)
206
+ ('SIZE', 4, (500, 300, 3), 'rgb', 'rgb16f')
207
+
208
+ Applies to: VertexBuffer, IndexBuffer, Texture2D, Texture3D,
209
+ RenderBuffer
210
+
211
+ This command is used to set the size of the buffer with the given id.
212
+ The GLIR implementation should be such that if the size/format
213
+ corresponds to the current size, it is ignored. The high level
214
+ implementation can use the SIZE command to discard previous DATA
215
+ commands.
216
+
217
+ For buffers: the size argument is an integer and the format argument is
218
+ not specified.
219
+
220
+ For textures and render buffer: the size argument is a shape tuple
221
+ (z,y,x). This tuple may contain the dimension for the color channels,
222
+ but this information is ignored. The format *should* be set to
223
+ 'luminance', 'alpha', 'luminance_alpha', 'rgb' or 'rgba'. The
224
+ internalformat is a hint for backends that can control the internal GL
225
+ storage format; a value of None is a hint to use the default storage
226
+ format. The internalformat, if specified, *should* be a base channel
227
+ configuration of 'r', 'rg', 'rgb', or 'rgba' with a precision qualifying
228
+ suffix of '8', '16', '16f', or '32f'.
229
+
230
+ For render buffers: the size argument is a shape tuple (z,y,x). This
231
+ tuple may contain the dimension for the color channels, but this
232
+ information is ignored. The format *should* be set to 'color', 'depth'
233
+ or 'stencil'.
234
+
235
+ DATA
236
+ ~~~~
237
+
238
+ ::
239
+
240
+ ('DATA', <id>, <offset>, <data:array>)
241
+ # Example:
242
+ ('DATA', 4, 100, <array 200x2>)
243
+
244
+ Applies to: VertexBuffer, IndexBuffer, Texture2D, Texture3D, VertexShader,
245
+ FragmentShader, GeometryShader
246
+
247
+ The data command is used to set the data of the object with the given
248
+ id. For VertexBuffer and IndexBuffer the offset is an integer. For
249
+ textures it is a tuple that matches with the dimension of the texture.
250
+ For shader objects it is always 0 and the data must be a ``str`` object.
251
+
252
+ WRAPPING
253
+ ~~~~~~~~
254
+
255
+ ::
256
+
257
+ ('WRAPPING', <texture_id>, <wrapping:tuple>)
258
+ # Example:
259
+ ('WRAPPING', 4, ('CLAMP_TO_EDGE', 'CLAMP_TO_EDGE'))
260
+
261
+ Applies to: Texture2D, Texture3D
262
+
263
+ Set the wrapping mode for each dimension of the texture. Each element
264
+ must be a string: 'repeat', 'clamp_to_edge' or 'mirrored_repeat'.
265
+
266
+ INTERPOLATION
267
+ ~~~~~~~~~~~~~
268
+
269
+ ::
270
+
271
+ ('INTERPOLATION', <texture_id>, <min:str>, <mag:str>)
272
+ # Example:
273
+ ('INTERPOLATION', 4, True, True)
274
+
275
+ Applies to: Texture2D, Texture3D
276
+
277
+ Set the interpolation mode of the texture for minification and
278
+ magnification. The min and mag argument can both be either 'nearest' or
279
+ 'linear'.
280
+
281
+ ATTACH
282
+ ~~~~~~
283
+
284
+ ::
285
+
286
+ ('ATTACH', <framebuffer_id>, <attachment:str>, <object>)
287
+ ('ATTACH', <program_id>, <shader_id>)
288
+ # Example:
289
+ ('ATTACH', 4, 'color', 5)
290
+ ('ATTACH', 1, 3)
291
+
292
+ Applies to: FrameBuffer, Program
293
+
294
+ Attach color, depth, or stencil buffer to the framebuffer. The
295
+ attachment argument can be 'color', 'depth' or 'stencil'. The object
296
+ argument must be the id for a RenderBuffer or Texture2D.
297
+ For Program this attaches an existing Shader object to the program.
298
+
299
+ FRAMEBUFFER
300
+ ~~~~~~~~~~~
301
+
302
+ ::
303
+
304
+ ('FRAMEBUFFER', <framebuffer_id>, <use:bool>)
305
+ # Example:
306
+ ('FRAMEBUFFER', 4, True)
307
+
308
+ Applies to: FrameBuffer
309
+
310
+ Turn the framebuffer on or off. When deactivating a frame buffer, the
311
+ GLIR implementation should activate any previously activated
312
+ framebuffer.
313
+
314
+ FUNC
315
+ ~~~~
316
+
317
+ ::
318
+
319
+ ('FUNC', <gl_function_name>, [arg1, [arg2, [arg3]]])
320
+
321
+ The ``FUNC`` command is a special command that can be applied to call a
322
+ variety of OpenGL calls. Use the documentation OpenGL for the required
323
+ arguments. Any args that are strings are converted to GL enums.
324
+
325
+ Supported functions are in principle all gl functions that do not have a
326
+ return value or covered by the above commands: glEnable, glDisable,
327
+ glClear, glClearColor, glClearDepth, glClearStencil, glViewport,
328
+ glDepthRange, glFrontFace, glCullFace, glPolygonOffset,
329
+ glBlendFuncSeparate, glBlendEquationSeparate, glBlendColor, glScissor,
330
+ glStencilFuncSeparate, glStencilMaskSeparate, glStencilOpSeparate,
331
+ glDepthFunc, glDepthMask, glColorMask, glSampleCoverage, glFlush,
332
+ glFinish, glHint.
333
+
334
+ SWAP
335
+ ~~~~
336
+
337
+ ::
338
+
339
+ ('SWAP',)
340
+
341
+ The ``SWAP`` command is a special synchronization command for remote
342
+ rendering. This command tells the renderer that it should swap drawing
343
+ buffers. This is especially important when rendering with WebGL where
344
+ drawing buffers are implicitly swapped.
345
+
346
+ LINK
347
+ ~~~~
348
+
349
+ ::
350
+
351
+ ('LINK', <program_id>)
352
+
353
+ Applies to: Program
354
+
355
+ Link the current program together (shaders, etc). Additionally this should
356
+ cause shaders to be detached and deleted. See the
357
+ `OpenGL documentation <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glLinkProgram.xhtml>`_
358
+ for details on program linking.
359
+
360
+ """
361
+
362
+ import os
363
+ import sys
364
+ import re
365
+ import json
366
+ import weakref
367
+ from packaging.version import Version
368
+
369
+ import numpy as np
370
+
371
+ from . import gl
372
+ from ..util import logger
373
+
374
+ # TODO: expose these via an extension space in .gl?
375
+ _internalformats = [
376
+ gl.Enum('GL_DEPTH_COMPONENT', 6402),
377
+ gl.Enum('GL_DEPTH_COMPONENT16', 33189),
378
+ gl.Enum('GL_DEPTH_COMPONENT32_OES', 33191),
379
+ gl.Enum('GL_RED', 6403),
380
+ gl.Enum('GL_R', 8194),
381
+ gl.Enum('GL_R8', 33321),
382
+ gl.Enum('GL_R16', 33322),
383
+ gl.Enum('GL_R16F', 33325),
384
+ gl.Enum('GL_R32F', 33326),
385
+ gl.Enum('GL_RG', 33319),
386
+ gl.Enum('GL_RG8', 333323),
387
+ gl.Enum('GL_RG16', 333324),
388
+ gl.Enum('GL_RG16F', 333327),
389
+ gl.Enum('GL_RG32F', 33328),
390
+ gl.Enum('GL_RGB', 6407),
391
+ gl.Enum('GL_RGB8', 32849),
392
+ gl.Enum('GL_RGB16', 32852),
393
+ gl.Enum('GL_RGB16F', 34843),
394
+ gl.Enum('GL_RGB32F', 34837),
395
+ gl.Enum('GL_RGBA', 6408),
396
+ gl.Enum('GL_RGBA8', 32856),
397
+ gl.Enum('GL_RGBA16', 32859),
398
+ gl.Enum('GL_RGBA16F', 34842),
399
+ gl.Enum('GL_RGBA32F', 34836),
400
+ # extended formats (not currently supported)
401
+ # gl.Enum('GL_R32I', 33333),
402
+ # gl.Enum('GL_RG32I', 33339),
403
+ # gl.Enum('GL_RGB32I', 36227),
404
+ # gl.Enum('GL_RGBA32I', 36226),
405
+ # gl.Enum('GL_R32UI', 33334),
406
+ # gl.Enum('GL_RG32UI', 33340),
407
+ # gl.Enum('GL_RGB32UI', 36209),
408
+ # gl.Enum('GL_RGBA32UI', 36208),
409
+ ]
410
+ _internalformats = dict([(enum.name, enum) for enum in _internalformats])
411
+
412
+ # Value to mark a glir object that was just deleted. So we can safely
413
+ # ignore it (and not raise an error that the object could not be found).
414
+ # This can happen e.g. if A is created, A is bound to B and then A gets
415
+ # deleted. The commands may get executed in order: A gets created, A
416
+ # gets deleted, A gets bound to B.
417
+ JUST_DELETED = 'JUST_DELETED'
418
+
419
+
420
+ def as_enum(enum):
421
+ """Turn a possibly string enum into an integer enum."""
422
+ if isinstance(enum, str):
423
+ try:
424
+ enum = getattr(gl, 'GL_' + enum.upper())
425
+ except AttributeError:
426
+ try:
427
+ enum = _internalformats['GL_' + enum.upper()]
428
+ except KeyError:
429
+ raise ValueError('Could not find int value for enum %r' % enum)
430
+ return enum
431
+
432
+
433
+ class _GlirQueueShare(object):
434
+ """This class contains the actual queues of GLIR commands that are
435
+ collected until a context becomes available to execute the commands.
436
+
437
+ Instances of this class are further wrapped by GlirQueue to allow the
438
+ underlying queues to be transparently merged when GL objects become
439
+ associated.
440
+
441
+ The motivation for this design is that it allows most glir commands to be
442
+ added directly to their final queue (the same one used by the context),
443
+ which reduces the effort required at draw time to determine the complete
444
+ set of GL commands to be issued.
445
+
446
+ At the same time, all GLObjects begin with their own local queue to allow
447
+ commands to be queued at any time, even if the GLObject has
448
+ not been associated yet. This works as expected even for complex topologies
449
+ of GL objects, when some queues may only be joined at the last possible
450
+ moment.
451
+ """
452
+
453
+ def __init__(self, queue):
454
+ self._commands = [] # local commands
455
+ self._verbose = False
456
+ # queues that have been merged with this one
457
+ self._associations = weakref.WeakKeyDictionary({queue: None})
458
+
459
+ def command(self, *args):
460
+ """Send a command. See the command spec at:
461
+ https://github.com/vispy/vispy/wiki/Spec.-Gloo-IR
462
+ """
463
+ self._commands.append(args)
464
+
465
+ def set_verbose(self, verbose):
466
+ """Set verbose or not. If True, the GLIR commands are printed right before they get parsed.
467
+ If a string is given, use it as a filter.
468
+ """
469
+ self._verbose = verbose
470
+
471
+ def show(self, filter=None):
472
+ """Print the list of commands currently in the queue. If filter is
473
+ given, print only commands that match the filter.
474
+ """
475
+ for command in self._commands:
476
+ if command[0] is None: # or command[1] in self._invalid_objects:
477
+ continue # Skip nill commands
478
+ if filter and command[0] != filter:
479
+ continue
480
+ t = []
481
+ for e in command:
482
+ if isinstance(e, np.ndarray):
483
+ t.append('array %s' % str(e.shape))
484
+ elif isinstance(e, str):
485
+ s = e.strip()
486
+ if len(s) > 20:
487
+ s = s[:18] + '... %i lines' % (e.count('\n')+1)
488
+ t.append(s)
489
+ else:
490
+ t.append(e)
491
+ print(tuple(t))
492
+
493
+ def clear(self):
494
+ """Pop the whole queue (and associated queues) and return a
495
+ list of commands.
496
+ """
497
+ commands = self._commands
498
+ self._commands = []
499
+ return commands
500
+
501
+ def flush(self, parser):
502
+ """Flush all current commands to the GLIR interpreter."""
503
+ if self._verbose:
504
+ show = self._verbose if isinstance(self._verbose, str) else None
505
+ self.show(show)
506
+ parser.parse(self._filter(self.clear(), parser))
507
+
508
+ def _filter(self, commands, parser):
509
+ """Filter DATA/SIZE commands that are overridden by a
510
+ SIZE command.
511
+ """
512
+ resized = set()
513
+ commands2 = []
514
+ for command in reversed(commands):
515
+ if command[1] in resized:
516
+ if command[0] in ('SIZE', 'DATA'):
517
+ continue # remove this command
518
+ elif command[0] == 'SIZE':
519
+ resized.add(command[1])
520
+ commands2.append(command)
521
+ return list(reversed(commands2))
522
+
523
+
524
+ class GlirQueue(object):
525
+ """Representation of a queue of GLIR commands
526
+
527
+ One instance of this class is attached to each context object, and
528
+ to each gloo object. Internally, commands are stored in a shared queue
529
+ object that may be swapped out and merged with other queues when
530
+ ``associate()`` is called.
531
+
532
+ Upon drawing (i.e. `Program.draw()`) and framebuffer switching, the
533
+ commands in the queue are pushed to a parser, which is stored at
534
+ context.shared. The parser can interpret the commands in Python,
535
+ send them to a browser, etc.
536
+ """
537
+
538
+ def __init__(self):
539
+ # We do not actually queue any commands here, but on a shared queue
540
+ # object that may be joined with others as queues are associated.
541
+ self._shared = _GlirQueueShare(self)
542
+
543
+ def command(self, *args):
544
+ """Send a command. See the command spec at:
545
+ https://github.com/vispy/vispy/wiki/Spec.-GLIR
546
+ """
547
+ self._shared.command(*args)
548
+
549
+ def set_verbose(self, verbose):
550
+ """Set verbose or not. If True, the GLIR commands are printed
551
+ right before they get parsed. If a string is given, use it as
552
+ a filter.
553
+ """
554
+ self._shared.set_verbose(verbose)
555
+
556
+ def clear(self):
557
+ """Pop the whole queue (and associated queues) and return a
558
+ list of commands.
559
+ """
560
+ return self._shared.clear()
561
+
562
+ def associate(self, queue):
563
+ """Merge this queue with another.
564
+
565
+ Both queues will use a shared command list and either one can be used
566
+ to fill or flush the shared queue.
567
+ """
568
+ assert isinstance(queue, GlirQueue)
569
+ if queue._shared is self._shared:
570
+ return
571
+
572
+ # merge commands
573
+ self._shared._commands.extend(queue.clear())
574
+ self._shared._verbose |= queue._shared._verbose
575
+ self._shared._associations[queue] = None
576
+ # update queue and all related queues to use the same _shared object
577
+ for ch in queue._shared._associations:
578
+ ch._shared = self._shared
579
+ self._shared._associations[ch] = None
580
+ queue._shared = self._shared
581
+
582
+ def flush(self, parser):
583
+ """Flush all current commands to the GLIR interpreter."""
584
+ self._shared.flush(parser)
585
+
586
+
587
+ def _convert_es2_shader(shader):
588
+ has_version = False
589
+ has_prec_float = False
590
+ has_prec_int = False
591
+ lines = []
592
+ extensions = []
593
+ # Iterate over lines
594
+ for line in shader.lstrip().splitlines():
595
+ line_strip = line.lstrip()
596
+ if line_strip.startswith('#version'):
597
+ # has_version = True
598
+ continue
599
+ if line_strip.startswith('#extension'):
600
+ extensions.append(line_strip)
601
+ line = ''
602
+ if line_strip.startswith('precision '):
603
+ has_prec_float = has_prec_float or 'float' in line
604
+ has_prec_int = has_prec_int or 'int' in line
605
+ lines.append(line.rstrip())
606
+ # Write
607
+ # BUG: fails on WebGL (Chrome)
608
+ # if True:
609
+ # lines.insert(has_version, '#line 0')
610
+ if not has_prec_float:
611
+ lines.insert(has_version, 'precision highp float;')
612
+ if not has_prec_int:
613
+ lines.insert(has_version, 'precision highp int;')
614
+ # Make sure extensions are at the top before precision
615
+ # but after version
616
+ if extensions:
617
+ for ext_line in extensions:
618
+ lines.insert(has_version, ext_line)
619
+ # BUG: fails on WebGL (Chrome)
620
+ # if not has_version:
621
+ # lines.insert(has_version, '#version 100')
622
+ return '\n'.join(lines)
623
+
624
+
625
+ def _convert_desktop_shader(shader):
626
+ has_version = False
627
+ lines = []
628
+ extensions = []
629
+ # Iterate over lines
630
+ for line in shader.lstrip().splitlines():
631
+ line_strip = line.lstrip()
632
+ has_version = has_version or line.startswith('#version')
633
+ if line_strip.startswith('precision '):
634
+ line = ''
635
+ if line_strip.startswith('#extension'):
636
+ extensions.append(line_strip)
637
+ line = ''
638
+ for prec in (' highp ', ' mediump ', ' lowp '):
639
+ line = line.replace(prec, ' ')
640
+ lines.append(line.rstrip())
641
+ # Write
642
+ # Make sure extensions are at the top, but after version
643
+ if extensions:
644
+ for ext_line in extensions:
645
+ lines.insert(has_version, ext_line)
646
+ if not has_version:
647
+ lines.insert(0, '#version 120\n')
648
+ return '\n'.join(lines)
649
+
650
+
651
+ def convert_shader(backend_type, shader):
652
+ """Modify shader code to be compatible with `backend_type` backend."""
653
+ if backend_type == 'es2':
654
+ return _convert_es2_shader(shader)
655
+ elif backend_type == 'desktop':
656
+ return _convert_desktop_shader(shader)
657
+ else:
658
+ raise ValueError('Cannot backend_type shaders to %r.' % backend_type)
659
+
660
+
661
+ def as_es2_command(command):
662
+ """Modify a desktop command so it works on es2."""
663
+ if command[0] == 'FUNC':
664
+ return (command[0], re.sub(r'^gl([A-Z])',
665
+ lambda m: m.group(1).lower(), command[1])) + command[2:]
666
+ elif command[0] == 'UNIFORM':
667
+ return command[:-1] + (command[-1].tolist(),)
668
+ return command
669
+
670
+
671
+ class BaseGlirParser(object):
672
+ """Base class for GLIR parsers that can be attached to a GLIR queue."""
673
+
674
+ def __init__(self):
675
+ self.capabilities = dict(
676
+ gl_version='Unknown',
677
+ max_texture_size=None,
678
+ )
679
+
680
+ def is_remote(self):
681
+ """Whether the code is executed remotely. i.e. gloo.gl cannot
682
+ be used.
683
+ """
684
+ raise NotImplementedError()
685
+
686
+ @property
687
+ def shader_compatibility(self):
688
+ """Whether to convert shading code. Valid values are 'es2' and
689
+ 'desktop'. If None, the shaders are not modified.
690
+ """
691
+ raise NotImplementedError()
692
+
693
+ def parse(self, commands):
694
+ """Parse the GLIR commands. Or sent them away."""
695
+ raise NotImplementedError()
696
+
697
+
698
+ class GlirParser(BaseGlirParser):
699
+ """A class for interpreting GLIR commands using gloo.gl
700
+
701
+ We make use of relatively light GLIR objects that are instantiated
702
+ on CREATE commands. These objects are stored by their id in a
703
+ dictionary so that commands like ACTIVATE and DATA can easily
704
+ be executed on the corresponding objects.
705
+ """
706
+
707
+ def __init__(self):
708
+ super(GlirParser, self).__init__()
709
+ self._objects = {}
710
+ self._invalid_objects = set()
711
+
712
+ self._classmap = {'VertexShader': GlirVertexShader,
713
+ 'FragmentShader': GlirFragmentShader,
714
+ 'GeometryShader': GlirGeometryShader,
715
+ 'Program': GlirProgram,
716
+ 'VertexBuffer': GlirVertexBuffer,
717
+ 'IndexBuffer': GlirIndexBuffer,
718
+ 'Texture1D': GlirTexture1D,
719
+ 'Texture2D': GlirTexture2D,
720
+ 'Texture3D': GlirTexture3D,
721
+ 'TextureCube': GlirTextureCube,
722
+ 'RenderBuffer': GlirRenderBuffer,
723
+ 'FrameBuffer': GlirFrameBuffer,
724
+ }
725
+
726
+ # We keep a dict that the GLIR objects use for storing
727
+ # per-context information. This dict is cleared each time
728
+ # that the context is made current. This seems necessary for
729
+ # when two Canvases share a context.
730
+ self.env = {}
731
+
732
+ @property
733
+ def shader_compatibility(self):
734
+ """Type of shader compatibility"""
735
+ if '.es' in gl.current_backend.__name__:
736
+ return 'es2'
737
+ else:
738
+ return 'desktop'
739
+
740
+ def is_remote(self):
741
+ return False
742
+
743
+ def _parse(self, command):
744
+ """Parse a single command."""
745
+ cmd, id_, args = command[0], command[1], command[2:]
746
+
747
+ if cmd == 'CURRENT':
748
+ # This context is made current
749
+ self.env.clear()
750
+ self._gl_initialize()
751
+ self.env['fbo'] = args[0]
752
+ gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, args[0])
753
+ elif cmd == 'FUNC':
754
+ # GL function call
755
+ args = [as_enum(a) for a in args]
756
+ try:
757
+ getattr(gl, id_)(*args)
758
+ except AttributeError:
759
+ logger.warning('Invalid gl command: %r' % id_)
760
+ elif cmd == 'CREATE':
761
+ # Creating an object
762
+ if args[0] is not None:
763
+ klass = self._classmap[args[0]]
764
+ self._objects[id_] = klass(self, id_)
765
+ else:
766
+ self._invalid_objects.add(id_)
767
+ elif cmd == 'DELETE':
768
+ # Deleting an object
769
+ ob = self._objects.get(id_, None)
770
+ if ob is not None:
771
+ self._objects[id_] = JUST_DELETED
772
+ ob.delete()
773
+ else:
774
+ # Doing somthing to an object
775
+ ob = self._objects.get(id_, None)
776
+ if ob == JUST_DELETED:
777
+ return
778
+ if ob is None:
779
+ if id_ not in self._invalid_objects:
780
+ raise RuntimeError('Cannot %s object %i because it '
781
+ 'does not exist' % (cmd, id_))
782
+ return
783
+ # Triage over command. Order of commands is set so most
784
+ # common ones occur first.
785
+ if cmd == 'DRAW': # Program
786
+ ob.draw(*args)
787
+ elif cmd == 'TEXTURE': # Program
788
+ ob.set_texture(*args)
789
+ elif cmd == 'UNIFORM': # Program
790
+ ob.set_uniform(*args)
791
+ elif cmd == 'ATTRIBUTE': # Program
792
+ ob.set_attribute(*args)
793
+ elif cmd == 'DATA': # VertexBuffer, IndexBuffer, Texture, Shader
794
+ ob.set_data(*args)
795
+ elif cmd == 'SIZE': # VertexBuffer, IndexBuffer,
796
+ ob.set_size(*args) # Texture[1D, 2D, 3D], RenderBuffer
797
+ elif cmd == 'ATTACH': # FrameBuffer, Program
798
+ ob.attach(*args)
799
+ elif cmd == 'FRAMEBUFFER': # FrameBuffer
800
+ ob.set_framebuffer(*args)
801
+ # elif cmd == 'SHADERS': # Program
802
+ # ob.set_shaders(*args)
803
+ elif cmd == 'LINK': # Program
804
+ ob.link_program(*args)
805
+ elif cmd == 'WRAPPING': # Texture1D, Texture2D, Texture3D
806
+ ob.set_wrapping(*args)
807
+ elif cmd == 'INTERPOLATION': # Texture1D, Texture2D, Texture3D
808
+ ob.set_interpolation(*args)
809
+ else:
810
+ logger.warning('Invalid GLIR command %r' % cmd)
811
+
812
+ def parse(self, commands):
813
+ """Parse a list of commands."""
814
+ # Get rid of dummy objects that represented deleted objects in
815
+ # the last parsing round.
816
+ to_delete = []
817
+ for id_, val in self._objects.items():
818
+ if val == JUST_DELETED:
819
+ to_delete.append(id_)
820
+ for id_ in to_delete:
821
+ self._objects.pop(id_)
822
+
823
+ for command in commands:
824
+ self._parse(command)
825
+
826
+ def get_object(self, id_):
827
+ """Get the object with the given id or None if it does not exist."""
828
+ return self._objects.get(id_, None)
829
+
830
+ def _gl_initialize(self):
831
+ """Deal with compatibility; desktop does not have sprites enabled by default. ES has."""
832
+ if '.es' in gl.current_backend.__name__:
833
+ pass # ES2: no action required
834
+ else:
835
+ # Desktop, enable sprites
836
+ GL_VERTEX_PROGRAM_POINT_SIZE = 34370
837
+ GL_POINT_SPRITE = 34913
838
+ gl.glEnable(GL_VERTEX_PROGRAM_POINT_SIZE)
839
+ gl.glEnable(GL_POINT_SPRITE)
840
+ if self.capabilities['max_texture_size'] is None: # only do once
841
+ self.capabilities['gl_version'] = gl.glGetParameter(gl.GL_VERSION)
842
+ self.capabilities['max_texture_size'] = \
843
+ gl.glGetParameter(gl.GL_MAX_TEXTURE_SIZE)
844
+ this_version = self.capabilities['gl_version'].split(' ')
845
+ if this_version[0] == "OpenGL":
846
+ # For OpenGL ES, the version string has the format:
847
+ # "OpenGL ES <version number> <vendor-specific information>"
848
+ this_version = this_version[2]
849
+ else:
850
+ this_version = this_version[0]
851
+
852
+ if not this_version:
853
+ logger.warning("OpenGL version could not be determined, which "
854
+ "might be a sign that OpenGL is not loaded correctly.")
855
+ elif Version(this_version) < Version('2.1'):
856
+ if os.getenv('VISPY_IGNORE_OLD_VERSION', '').lower() != 'true':
857
+ logger.warning('OpenGL version 2.1 or higher recommended, '
858
+ 'got %s. Some functionality may fail.'
859
+ % self.capabilities['gl_version'])
860
+
861
+
862
+ def glir_logger(parser_cls, file_or_filename):
863
+ from ..util.logs import NumPyJSONEncoder
864
+
865
+ class cls(parser_cls):
866
+ def __init__(self, *args, **kwargs):
867
+ parser_cls.__init__(self, *args, **kwargs)
868
+
869
+ if isinstance(file_or_filename, str):
870
+ self._file = open(file_or_filename, 'w')
871
+ else:
872
+ self._file = file_or_filename
873
+
874
+ self._file.write('[]')
875
+ self._empty = True
876
+
877
+ def _parse(self, command):
878
+ parser_cls._parse(self, command)
879
+
880
+ self._file.seek(self._file.tell() - 1)
881
+ if self._empty:
882
+ self._empty = False
883
+ else:
884
+ self._file.write(',\n')
885
+ json.dump(as_es2_command(command),
886
+ self._file, cls=NumPyJSONEncoder)
887
+ self._file.write(']')
888
+
889
+ return cls
890
+
891
+
892
+ # GLIR objects
893
+
894
+ class GlirObject(object):
895
+ def __init__(self, parser, id_):
896
+ self._parser = parser
897
+ self._id = id_
898
+ self._handle = -1 # Must be set by subclass in create()
899
+ self.create()
900
+
901
+ @property
902
+ def handle(self):
903
+ return self._handle
904
+
905
+ @property
906
+ def id(self):
907
+ return self._id
908
+
909
+ def __repr__(self):
910
+ return '<%s %i at 0x%x>' % (self.__class__.__name__, self.id, id(self))
911
+
912
+
913
+ class GlirShader(GlirObject):
914
+ _target = None
915
+
916
+ def create(self):
917
+ self._handle = gl.glCreateShader(self._target)
918
+
919
+ def set_data(self, offset, code):
920
+ # NOTE: offset will always be 0 to match other DATA commands
921
+
922
+ # convert shader to be compatible with backend
923
+ convert = self._parser.shader_compatibility
924
+ if convert:
925
+ code = convert_shader(convert, code)
926
+
927
+ gl.glShaderSource(self._handle, code)
928
+ gl.glCompileShader(self._handle)
929
+ status = gl.glGetShaderParameter(self._handle, gl.GL_COMPILE_STATUS)
930
+ if not status:
931
+ errors = gl.glGetShaderInfoLog(self._handle)
932
+ errormsg = self._get_error(code, errors, 4)
933
+ raise RuntimeError("Shader compilation error in %s:\n%s" %
934
+ (self._target, errormsg))
935
+
936
+ def delete(self):
937
+ gl.glDeleteShader(self._handle)
938
+
939
+ def _get_error(self, code, errors, indentation=0):
940
+ """Get error and show the faulty line + some context
941
+ Other GLIR implementations may omit this.
942
+ """
943
+ # Init
944
+ results = []
945
+ lines = None
946
+ if code is not None:
947
+ lines = [line.strip() for line in code.split('\n')]
948
+
949
+ for error in errors.split('\n'):
950
+ # Strip; skip empy lines
951
+ error = error.strip()
952
+ if not error:
953
+ continue
954
+ # Separate line number from description (if we can)
955
+ linenr, error = self._parse_error(error)
956
+ if None in (linenr, lines):
957
+ results.append('%s' % error)
958
+ else:
959
+ results.append('on line %i: %s' % (linenr, error))
960
+ if linenr > 0 and linenr < len(lines):
961
+ results.append(' %s' % lines[linenr - 1])
962
+
963
+ # Add indentation and return
964
+ results = [' ' * indentation + r for r in results]
965
+ return '\n'.join(results)
966
+
967
+ def _parse_error(self, error):
968
+ """Parses a single GLSL error and extracts the linenr and description
969
+ Other GLIR implementations may omit this.
970
+ """
971
+ error = str(error)
972
+ # Nvidia
973
+ # 0(7): error C1008: undefined variable "MV"
974
+ m = re.match(r'(\d+)\((\d+)\)\s*:\s(.*)', error)
975
+ if m:
976
+ return int(m.group(2)), m.group(3)
977
+ # ATI / Intel
978
+ # ERROR: 0:131: '{' : syntax error parse error
979
+ m = re.match(r'ERROR:\s(\d+):(\d+):\s(.*)', error)
980
+ if m:
981
+ return int(m.group(2)), m.group(3)
982
+ # Nouveau
983
+ # 0:28(16): error: syntax error, unexpected ')', expecting '('
984
+ m = re.match(r'(\d+):(\d+)\((\d+)\):\s(.*)', error)
985
+ if m:
986
+ return int(m.group(2)), m.group(4)
987
+ # Other ...
988
+ return None, error
989
+
990
+
991
+ class GlirVertexShader(GlirShader):
992
+ _target = gl.GL_VERTEX_SHADER
993
+
994
+
995
+ class GlirFragmentShader(GlirShader):
996
+ _target = gl.GL_FRAGMENT_SHADER
997
+
998
+
999
+ class GlirGeometryShader(GlirShader):
1000
+ # _target assignment must be delayed because GL_GEOMETRY_SHADER does not
1001
+ # exist until the user calls use_gl('gl+')
1002
+ _target = None
1003
+
1004
+ def __init__(self, *args, **kwargs):
1005
+ if not hasattr(gl, 'GL_GEOMETRY_SHADER'):
1006
+ raise RuntimeError(gl.current_backend.__name__ +
1007
+ " backend does not support geometry shaders."
1008
+ " Try gloo.gl.use_gl('gl+').")
1009
+ GlirGeometryShader._target = gl.GL_GEOMETRY_SHADER
1010
+ GlirShader.__init__(self, *args, **kwargs)
1011
+
1012
+
1013
+ class GlirProgram(GlirObject):
1014
+
1015
+ UTYPEMAP = {
1016
+ 'float': 'glUniform1fv',
1017
+ 'vec2': 'glUniform2fv',
1018
+ 'vec3': 'glUniform3fv',
1019
+ 'vec4': 'glUniform4fv',
1020
+ 'int': 'glUniform1iv',
1021
+ 'ivec2': 'glUniform2iv',
1022
+ 'ivec3': 'glUniform3iv',
1023
+ 'ivec4': 'glUniform4iv',
1024
+ 'bool': 'glUniform1iv',
1025
+ 'bvec2': 'glUniform2iv',
1026
+ 'bvec3': 'glUniform3iv',
1027
+ 'bvec4': 'glUniform4iv',
1028
+ 'mat2': 'glUniformMatrix2fv',
1029
+ 'mat3': 'glUniformMatrix3fv',
1030
+ 'mat4': 'glUniformMatrix4fv',
1031
+ 'sampler1D': 'glUniform1i',
1032
+ 'sampler2D': 'glUniform1i',
1033
+ 'sampler3D': 'glUniform1i',
1034
+ }
1035
+
1036
+ ATYPEMAP = {
1037
+ 'float': 'glVertexAttrib1f',
1038
+ 'vec2': 'glVertexAttrib2f',
1039
+ 'vec3': 'glVertexAttrib3f',
1040
+ 'vec4': 'glVertexAttrib4f',
1041
+ }
1042
+
1043
+ ATYPEINFO = {
1044
+ 'float': (1, gl.GL_FLOAT, np.float32),
1045
+ 'vec2': (2, gl.GL_FLOAT, np.float32),
1046
+ 'vec3': (3, gl.GL_FLOAT, np.float32),
1047
+ 'vec4': (4, gl.GL_FLOAT, np.float32),
1048
+ 'int': (1, gl.GL_INT, np.int32),
1049
+ 'bool': (1, gl.GL_BOOL, np.int32)
1050
+ }
1051
+
1052
+ def create(self):
1053
+ self._handle = gl.glCreateProgram()
1054
+ self._attached_shaders = []
1055
+ self._validated = False
1056
+ self._linked = False
1057
+ # Keeping track of uniforms/attributes
1058
+ self._handles = {} # cache with handles to attributes/uniforms
1059
+ self._unset_variables = set()
1060
+ # Store samplers in buffers that are bount to uniforms/attributes
1061
+ self._samplers = {} # name -> (tex-target, tex-handle, unit)
1062
+ self._attributes = {} # name -> (vbo-handle, attr-handle, func, args)
1063
+ self._known_invalid = set() # variables that we know are invalid
1064
+
1065
+ def delete(self):
1066
+ gl.glDeleteProgram(self._handle)
1067
+
1068
+ def activate(self):
1069
+ """Avoid overhead in calling glUseProgram with same arg.
1070
+ Warning: this will break if glUseProgram is used somewhere else.
1071
+ Per context we keep track of one current program.
1072
+ """
1073
+ if self._handle != self._parser.env.get('current_program', False):
1074
+ self._parser.env['current_program'] = self._handle
1075
+ gl.glUseProgram(self._handle)
1076
+
1077
+ def deactivate(self):
1078
+ """Avoid overhead in calling glUseProgram with same arg.
1079
+ Warning: this will break if glUseProgram is used somewhere else.
1080
+ Per context we keep track of one current program.
1081
+ """
1082
+ if self._parser.env.get('current_program', 0) != 0:
1083
+ self._parser.env['current_program'] = 0
1084
+ gl.glUseProgram(0)
1085
+
1086
+ def set_shaders(self, vert, frag):
1087
+ """This function takes care of setting the shading code and
1088
+ compiling+linking it into a working program object that is ready
1089
+ to use.
1090
+ """
1091
+ self._linked = False
1092
+
1093
+ # For both vertex and fragment shader: set source, compile, check
1094
+ for code, type_ in [(vert, 'vertex'),
1095
+ (frag, 'fragment')]:
1096
+ self.attach_shader(code, type_)
1097
+
1098
+ self.link_program()
1099
+
1100
+ def attach(self, id_):
1101
+ """Attach a shader to this program."""
1102
+ shader = self._parser.get_object(id_)
1103
+ gl.glAttachShader(self._handle, shader.handle)
1104
+ self._attached_shaders.append(shader)
1105
+
1106
+ def link_program(self):
1107
+ """Link the complete program and check.
1108
+
1109
+ All shaders are detached and deleted if the program was successfully
1110
+ linked.
1111
+ """
1112
+ gl.glLinkProgram(self._handle)
1113
+ if not gl.glGetProgramParameter(self._handle, gl.GL_LINK_STATUS):
1114
+ raise RuntimeError('Program linking error:\n%s'
1115
+ % gl.glGetProgramInfoLog(self._handle))
1116
+
1117
+ # Detach all shaders to prepare them for deletion (they are no longer
1118
+ # needed after linking is complete)
1119
+ for shader in self._attached_shaders:
1120
+ gl.glDetachShader(self._handle, shader.handle)
1121
+ self._attached_shaders = []
1122
+
1123
+ # Now we know what variables will be used by the program
1124
+ self._unset_variables = self._get_active_attributes_and_uniforms()
1125
+ self._handles = {}
1126
+ self._known_invalid = set()
1127
+ self._linked = True
1128
+
1129
+ def _get_active_attributes_and_uniforms(self):
1130
+ """Retrieve active attributes and uniforms to be able to check that
1131
+ all uniforms/attributes are set by the user.
1132
+ Other GLIR implementations may omit this.
1133
+ """
1134
+ # This match a name of the form "name[size]" (= array)
1135
+ regex = re.compile(r"""(?P<name>\w+)\s*(\[(?P<size>\d+)\])\s*""")
1136
+ # Get how many active attributes and uniforms there are
1137
+ cu = gl.glGetProgramParameter(self._handle, gl.GL_ACTIVE_UNIFORMS)
1138
+ ca = gl.glGetProgramParameter(self.handle, gl.GL_ACTIVE_ATTRIBUTES)
1139
+ # Get info on each one
1140
+ attributes = []
1141
+ uniforms = []
1142
+ for container, count, func in [(attributes, ca, gl.glGetActiveAttrib),
1143
+ (uniforms, cu, gl.glGetActiveUniform)]:
1144
+ for i in range(count):
1145
+ name, size, gtype = func(self._handle, i)
1146
+ m = regex.match(name) # Check if xxx[0] instead of xx
1147
+ if m:
1148
+ name = m.group('name')
1149
+ for i in range(size):
1150
+ container.append(('%s[%d]' % (name, i), gtype))
1151
+ else:
1152
+ container.append((name, gtype))
1153
+ # return attributes, uniforms
1154
+ return set([v[0] for v in attributes] + [v[0] for v in uniforms])
1155
+
1156
+ def set_texture(self, name, value):
1157
+ """Set a texture sampler. Value is the id of the texture to link."""
1158
+ if not self._linked:
1159
+ raise RuntimeError('Cannot set uniform when program has no code')
1160
+ # Get handle for the uniform, first try cache
1161
+ handle = self._handles.get(name, -1)
1162
+ if handle < 0:
1163
+ if name in self._known_invalid:
1164
+ return
1165
+ handle = gl.glGetUniformLocation(self._handle, name)
1166
+ self._unset_variables.discard(name) # Mark as set
1167
+ self._handles[name] = handle # Store in cache
1168
+ if handle < 0:
1169
+ self._known_invalid.add(name)
1170
+ logger.info('Not setting texture data for variable %s; '
1171
+ 'uniform is not active.' % name)
1172
+ return
1173
+ # Program needs to be active in order to set uniforms
1174
+ self.activate()
1175
+ if True:
1176
+ # Sampler: the value is the id of the texture
1177
+ tex = self._parser.get_object(value)
1178
+ if tex == JUST_DELETED:
1179
+ return
1180
+ if tex is None:
1181
+ raise RuntimeError('Could not find texture with id %i' % value)
1182
+ unit = len(self._samplers)
1183
+ if name in self._samplers:
1184
+ unit = self._samplers[name][-1] # Use existing unit
1185
+ self._samplers[name] = tex._target, tex.handle, unit
1186
+ gl.glUniform1i(handle, unit)
1187
+
1188
+ def set_uniform(self, name, type_, value):
1189
+ """Set a uniform value. Value is assumed to have been checked."""
1190
+ if not self._linked:
1191
+ raise RuntimeError('Cannot set uniform when program has no code')
1192
+ # Get handle for the uniform, first try cache
1193
+ handle = self._handles.get(name, -1)
1194
+ count = 1
1195
+ if handle < 0:
1196
+ if name in self._known_invalid:
1197
+ return
1198
+ handle = gl.glGetUniformLocation(self._handle, name)
1199
+ self._unset_variables.discard(name) # Mark as set
1200
+ # if we set a uniform_array, mark all as set
1201
+ if not type_.startswith('mat'):
1202
+ count = value.nbytes // (4 * self.ATYPEINFO[type_][0])
1203
+ if count > 1:
1204
+ for ii in range(count):
1205
+ if '%s[%s]' % (name, ii) in self._unset_variables:
1206
+ self._unset_variables.discard('%s[%s]' % (name, ii))
1207
+
1208
+ self._handles[name] = handle # Store in cache
1209
+ if handle < 0:
1210
+ self._known_invalid.add(name)
1211
+ logger.info('Not setting value for variable %s %s; '
1212
+ 'uniform is not active.' % (type_, name))
1213
+ return
1214
+ # Look up function to call
1215
+ funcname = self.UTYPEMAP[type_]
1216
+ func = getattr(gl, funcname)
1217
+ # Program needs to be active in order to set uniforms
1218
+ self.activate()
1219
+ # Triage depending on type
1220
+ if type_.startswith('mat'):
1221
+ # Value is matrix, these gl funcs have alternative signature
1222
+ transpose = False # OpenGL ES 2.0 does not support transpose
1223
+ func(handle, 1, transpose, value)
1224
+ else:
1225
+ # Regular uniform
1226
+ func(handle, count, value)
1227
+
1228
+ def set_attribute(self, name, type_, value, divisor=None):
1229
+ """Set an attribute value. Value is assumed to have been checked."""
1230
+ if not self._linked:
1231
+ raise RuntimeError('Cannot set attribute when program has no code')
1232
+ # Get handle for the attribute, first try cache
1233
+ handle = self._handles.get(name, -1)
1234
+ if handle < 0:
1235
+ if name in self._known_invalid:
1236
+ return
1237
+ handle = gl.glGetAttribLocation(self._handle, name)
1238
+ self._unset_variables.discard(name) # Mark as set
1239
+ self._handles[name] = handle # Store in cache
1240
+ if handle < 0:
1241
+ self._known_invalid.add(name)
1242
+ if value[0] != 0 and value[2] > 0: # VBO with offset
1243
+ return # Probably an unused element in a structured VBO
1244
+ logger.info('Not setting data for variable %s %s; '
1245
+ 'attribute is not active.' % (type_, name))
1246
+ return
1247
+ # Program needs to be active in order to set uniforms
1248
+ self.activate()
1249
+ # Triage depending on VBO or tuple data
1250
+ if value[0] == 0:
1251
+ # Look up function call
1252
+ funcname = self.ATYPEMAP[type_]
1253
+ func = getattr(gl, funcname)
1254
+ # Set data
1255
+ self._attributes[name] = 0, handle, func, value[1:], divisor
1256
+ else:
1257
+ # Get meta data
1258
+ vbo_id, stride, offset = value
1259
+ size, gtype, dtype = self.ATYPEINFO[type_]
1260
+ # Get associated VBO
1261
+ vbo = self._parser.get_object(vbo_id)
1262
+ if vbo == JUST_DELETED:
1263
+ return
1264
+ if vbo is None:
1265
+ raise RuntimeError('Could not find VBO with id %i' % vbo_id)
1266
+ # Set data
1267
+ func = gl.glVertexAttribPointer
1268
+ args = size, gtype, gl.GL_FALSE, stride, offset
1269
+ self._attributes[name] = vbo.handle, handle, func, args, divisor
1270
+
1271
+ def _pre_draw(self):
1272
+ self.activate()
1273
+ # Activate textures
1274
+ for tex_target, tex_handle, unit in self._samplers.values():
1275
+ gl.glActiveTexture(gl.GL_TEXTURE0 + unit)
1276
+ gl.glBindTexture(tex_target, tex_handle)
1277
+ # Activate attributes
1278
+ for vbo_handle, attr_handle, func, args, divisor in self._attributes.values():
1279
+ if vbo_handle:
1280
+ gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo_handle)
1281
+ gl.glEnableVertexAttribArray(attr_handle)
1282
+ func(attr_handle, *args)
1283
+ if divisor is not None:
1284
+ gl.glVertexAttribDivisor(attr_handle, divisor)
1285
+ else:
1286
+ gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
1287
+ gl.glDisableVertexAttribArray(attr_handle)
1288
+ func(attr_handle, *args)
1289
+ # Validate. We need to validate after textures units get assigned
1290
+ if not self._validated:
1291
+ self._validated = True
1292
+ self._validate()
1293
+
1294
+ def _validate(self):
1295
+ # Validate ourselves
1296
+ if self._unset_variables:
1297
+ logger.warning('Program has unset variables: %r' %
1298
+ self._unset_variables)
1299
+ # Validate via OpenGL
1300
+ gl.glValidateProgram(self._handle)
1301
+ if not gl.glGetProgramParameter(self._handle,
1302
+ gl.GL_VALIDATE_STATUS):
1303
+ raise RuntimeError('Program validation error:\n%s'
1304
+ % gl.glGetProgramInfoLog(self._handle))
1305
+
1306
+ def _post_draw(self):
1307
+ # No need to deactivate each texture/buffer, just set to 0
1308
+ gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
1309
+ gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
1310
+ if USE_TEX_3D:
1311
+ gl.glBindTexture(GL_TEXTURE_3D, 0)
1312
+ gl.glBindTexture(GL_TEXTURE_1D, 0)
1313
+
1314
+ # Deactivate program - should not be necessary. In single-program
1315
+ # apps it would not even make sense.
1316
+ # self.deactivate()
1317
+
1318
+ def draw(self, mode, selection, instances=1):
1319
+ """Draw program in given mode, with given selection (IndexBuffer or
1320
+ first, count).
1321
+ """
1322
+ if not self._linked:
1323
+ raise RuntimeError('Cannot draw program if code has not been set')
1324
+ # Init
1325
+ gl.check_error('Check before draw')
1326
+ try:
1327
+ mode = as_enum(mode)
1328
+ except ValueError:
1329
+ if mode == 'lines_adjacency' or mode == 'line_strip_adjacency':
1330
+ raise RuntimeError(gl.current_backend.__name__ +
1331
+ " backend does not support lines_adjacency"
1332
+ " and line_strip_adjacency primitives."
1333
+ " Try gloo.gl.use_gl('gl+').")
1334
+ raise
1335
+
1336
+ # Draw
1337
+ if len(selection) == 3:
1338
+ # Selection based on indices
1339
+ id_, gtype, count = selection
1340
+ if count:
1341
+ self._pre_draw()
1342
+ ibuf = self._parser.get_object(id_)
1343
+ ibuf.activate()
1344
+ if instances > 1:
1345
+ gl.glDrawElementsInstanced(mode, count, as_enum(gtype), None, instances)
1346
+ else:
1347
+ gl.glDrawElements(mode, count, as_enum(gtype), None)
1348
+ ibuf.deactivate()
1349
+ else:
1350
+ # Selection based on start and count
1351
+ first, count = selection
1352
+ if count:
1353
+ self._pre_draw()
1354
+ if instances > 1:
1355
+ gl.glDrawArraysInstanced(mode, first, count, instances)
1356
+ else:
1357
+ gl.glDrawArrays(mode, first, count)
1358
+ # Wrap up
1359
+ gl.check_error('Check after draw')
1360
+ self._post_draw()
1361
+
1362
+
1363
+ class GlirBuffer(GlirObject):
1364
+ _target = None
1365
+ _usage = gl.GL_DYNAMIC_DRAW # STATIC_DRAW, STREAM_DRAW or DYNAMIC_DRAW
1366
+
1367
+ def create(self):
1368
+ self._handle = gl.glCreateBuffer()
1369
+ self._buffer_size = 0
1370
+ self._bufferSubDataOk = False
1371
+
1372
+ def delete(self):
1373
+ gl.glDeleteBuffer(self._handle)
1374
+
1375
+ def activate(self):
1376
+ gl.glBindBuffer(self._target, self._handle)
1377
+
1378
+ def deactivate(self):
1379
+ gl.glBindBuffer(self._target, 0)
1380
+
1381
+ def set_size(self, nbytes): # in bytes
1382
+ if nbytes != self._buffer_size:
1383
+ self.activate()
1384
+ gl.glBufferData(self._target, nbytes, self._usage)
1385
+ self._buffer_size = nbytes
1386
+
1387
+ def set_data(self, offset, data):
1388
+ self.activate()
1389
+ nbytes = data.nbytes
1390
+
1391
+ # Determine whether to check errors to try handling the ATI bug
1392
+ check_ati_bug = ((not self._bufferSubDataOk) and
1393
+ (gl.current_backend.__name__.split(".")[-1] == "gl2") and
1394
+ sys.platform.startswith('win'))
1395
+
1396
+ # flush any pending errors
1397
+ if check_ati_bug:
1398
+ gl.check_error('periodic check')
1399
+
1400
+ try:
1401
+ gl.glBufferSubData(self._target, offset, data)
1402
+ if check_ati_bug:
1403
+ gl.check_error('glBufferSubData')
1404
+ self._bufferSubDataOk = True # glBufferSubData seems to work
1405
+ except Exception:
1406
+ # This might be due to a driver error (seen on ATI), issue #64.
1407
+ # We try to detect this, and if we can use glBufferData instead
1408
+ if offset == 0 and nbytes == self._buffer_size:
1409
+ gl.glBufferData(self._target, data, self._usage)
1410
+ logger.debug("Using glBufferData instead of " +
1411
+ "glBufferSubData (known ATI bug).")
1412
+ else:
1413
+ raise
1414
+
1415
+
1416
+ class GlirVertexBuffer(GlirBuffer):
1417
+ _target = gl.GL_ARRAY_BUFFER
1418
+
1419
+
1420
+ class GlirIndexBuffer(GlirBuffer):
1421
+ _target = gl.GL_ELEMENT_ARRAY_BUFFER
1422
+
1423
+
1424
+ class GlirTexture(GlirObject):
1425
+ _target = None
1426
+
1427
+ _types = {
1428
+ np.dtype(np.int8): gl.GL_BYTE,
1429
+ np.dtype(np.uint8): gl.GL_UNSIGNED_BYTE,
1430
+ np.dtype(np.int16): gl.GL_SHORT,
1431
+ np.dtype(np.uint16): gl.GL_UNSIGNED_SHORT,
1432
+ np.dtype(np.int32): gl.GL_INT,
1433
+ np.dtype(np.uint32): gl.GL_UNSIGNED_INT,
1434
+ # np.dtype(np.float16) : gl.GL_HALF_FLOAT,
1435
+ np.dtype(np.float32): gl.GL_FLOAT,
1436
+ # np.dtype(np.float64) : gl.GL_DOUBLE
1437
+ }
1438
+
1439
+ def create(self):
1440
+ self._handle = gl.glCreateTexture()
1441
+ self._shape_formats = 0 # To make setting size cheap
1442
+
1443
+ def delete(self):
1444
+ gl.glDeleteTexture(self._handle)
1445
+
1446
+ def activate(self):
1447
+ gl.glBindTexture(self._target, self._handle)
1448
+
1449
+ def deactivate(self):
1450
+ gl.glBindTexture(self._target, 0)
1451
+
1452
+ # Taken from pygly
1453
+ def _get_alignment(self, width):
1454
+ """Determines a textures byte alignment.
1455
+
1456
+ If the width isn't a power of 2
1457
+ we need to adjust the byte alignment of the image.
1458
+ The image height is unimportant
1459
+
1460
+ www.opengl.org/wiki/Common_Mistakes#Texture_upload_and_pixel_reads
1461
+ """
1462
+ # we know the alignment is appropriate
1463
+ # if we can divide the width by the
1464
+ # alignment cleanly
1465
+ # valid alignments are 1,2,4 and 8
1466
+ # 4 is the default
1467
+ alignments = [8, 4, 2, 1]
1468
+ for alignment in alignments:
1469
+ if width % alignment == 0:
1470
+ return alignment
1471
+
1472
+ def set_wrapping(self, wrapping):
1473
+ self.activate()
1474
+ wrapping = [as_enum(w) for w in wrapping]
1475
+ if len(wrapping) == 3:
1476
+ GL_TEXTURE_WRAP_R = 32882
1477
+ gl.glTexParameterf(self._target, GL_TEXTURE_WRAP_R, wrapping[0])
1478
+ if len(wrapping) >= 2:
1479
+ gl.glTexParameterf(self._target,
1480
+ gl.GL_TEXTURE_WRAP_S, wrapping[-2])
1481
+ gl.glTexParameterf(self._target, gl.GL_TEXTURE_WRAP_T, wrapping[-1])
1482
+
1483
+ def set_interpolation(self, min, mag):
1484
+ self.activate()
1485
+ min, mag = as_enum(min), as_enum(mag)
1486
+ gl.glTexParameterf(self._target, gl.GL_TEXTURE_MIN_FILTER, min)
1487
+ gl.glTexParameterf(self._target, gl.GL_TEXTURE_MAG_FILTER, mag)
1488
+
1489
+ # these should be auto generated in _constants.py. But that doesn't seem
1490
+ # to be happening. TODO - figure out why the C parser in (createglapi.py)
1491
+ # is not extracting these constanst out.
1492
+ # found the constant value at:
1493
+ # http://docs.factorcode.org/content/word-GL_TEXTURE_1D,opengl.gl.html
1494
+ # http://docs.factorcode.org/content/word-GL_SAMPLER_1D%2Copengl.gl.html
1495
+ GL_SAMPLER_1D = gl.Enum('GL_SAMPLER_1D', 35677)
1496
+ GL_TEXTURE_1D = gl.Enum('GL_TEXTURE_1D', 3552)
1497
+
1498
+
1499
+ class GlirTexture1D(GlirTexture):
1500
+ _target = GL_TEXTURE_1D
1501
+
1502
+ def set_size(self, shape, format, internalformat):
1503
+ format = as_enum(format)
1504
+ if internalformat is not None:
1505
+ internalformat = as_enum(internalformat)
1506
+ else:
1507
+ internalformat = format
1508
+ # Shape is width
1509
+ if (shape, format, internalformat) != self._shape_formats:
1510
+ self.activate()
1511
+ self._shape_formats = shape, format, internalformat
1512
+ glTexImage1D(self._target, 0, internalformat, format,
1513
+ gl.GL_BYTE, shape[:1])
1514
+
1515
+ def set_data(self, offset, data):
1516
+ self.activate()
1517
+ shape, format, internalformat = self._shape_formats
1518
+ x = offset[0]
1519
+ # Get gtype
1520
+ gtype = self._types.get(np.dtype(data.dtype), None)
1521
+ if gtype is None:
1522
+ raise ValueError("Type %r not allowed for texture" % data.dtype)
1523
+ # Set alignment (width is nbytes_per_pixel * npixels_per_line)
1524
+ alignment = self._get_alignment(data.shape[-1] * data.itemsize)
1525
+ if alignment != 4:
1526
+ gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, alignment)
1527
+ # Upload
1528
+ glTexSubImage1D(self._target, 0, x, format, gtype, data)
1529
+ # Set alignment back
1530
+ if alignment != 4:
1531
+ gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 4)
1532
+
1533
+
1534
+ class GlirTexture2D(GlirTexture):
1535
+ _target = gl.GL_TEXTURE_2D
1536
+
1537
+ def set_size(self, shape, format, internalformat):
1538
+ # Shape is height, width
1539
+ format = as_enum(format)
1540
+ internalformat = format if internalformat is None \
1541
+ else as_enum(internalformat)
1542
+ if (shape, format, internalformat) != self._shape_formats:
1543
+ self._shape_formats = shape, format, internalformat
1544
+ self.activate()
1545
+ gl.glTexImage2D(self._target, 0, internalformat, format,
1546
+ gl.GL_UNSIGNED_BYTE, shape[:2])
1547
+
1548
+ def set_data(self, offset, data):
1549
+ self.activate()
1550
+ shape, format, internalformat = self._shape_formats
1551
+ y, x = offset
1552
+ # Get gtype
1553
+ gtype = self._types.get(np.dtype(data.dtype), None)
1554
+ if gtype is None:
1555
+ raise ValueError("Type %r not allowed for texture" % data.dtype)
1556
+ # Set alignment (width is nbytes_per_pixel * npixels_per_line)
1557
+ alignment = self._get_alignment(data.shape[-2] * data.shape[-1] * data.itemsize)
1558
+ if alignment != 4:
1559
+ gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, alignment)
1560
+ # Upload
1561
+ gl.glTexSubImage2D(self._target, 0, x, y, format, gtype, data)
1562
+ # Set alignment back
1563
+ if alignment != 4:
1564
+ gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 4)
1565
+
1566
+
1567
+ GL_SAMPLER_3D = gl.Enum('GL_SAMPLER_3D', 35679)
1568
+ GL_TEXTURE_3D = gl.Enum('GL_TEXTURE_3D', 32879)
1569
+
1570
+ USE_TEX_3D = False
1571
+
1572
+
1573
+ def _check_pyopengl_3D():
1574
+ """Helper to ensure users have OpenGL for 3D texture support (for now)"""
1575
+ global USE_TEX_3D
1576
+ USE_TEX_3D = True
1577
+ try:
1578
+ import OpenGL.GL as _gl
1579
+ except ImportError:
1580
+ raise ImportError('PyOpenGL is required for 3D texture support')
1581
+ return _gl
1582
+
1583
+
1584
+ def glTexImage3D(target, level, internalformat, format, type, pixels):
1585
+ # Import from PyOpenGL
1586
+ _gl = _check_pyopengl_3D()
1587
+ border = 0
1588
+ assert isinstance(pixels, (tuple, list)) # the only way we use this now
1589
+ depth, height, width = pixels
1590
+ _gl.glTexImage3D(target, level, internalformat,
1591
+ width, height, depth, border, format, type, None)
1592
+
1593
+
1594
+ def glTexImage1D(target, level, internalformat, format, type, pixels):
1595
+ # Import from PyOpenGL
1596
+ _gl = _check_pyopengl_3D()
1597
+ border = 0
1598
+ assert isinstance(pixels, (tuple, list)) # the only way we use this now
1599
+ # pixels will be a tuple of the form (width, )
1600
+ # we only need the first argument
1601
+ width = pixels[0]
1602
+
1603
+ _gl.glTexImage1D(target, level, internalformat,
1604
+ width, border, format, type, None)
1605
+
1606
+
1607
+ def glTexSubImage1D(target, level, xoffset,
1608
+ format, type, pixels):
1609
+ # Import from PyOpenGL
1610
+ _gl = _check_pyopengl_3D()
1611
+ width = pixels.shape[:1]
1612
+
1613
+ # width will be a tuple of the form (w, )
1614
+ # we need to take the first element (integer)
1615
+ _gl.glTexSubImage1D(target, level, xoffset,
1616
+ width[0], format, type, pixels)
1617
+
1618
+
1619
+ def glTexSubImage3D(target, level, xoffset, yoffset, zoffset,
1620
+ format, type, pixels):
1621
+ # Import from PyOpenGL
1622
+ _gl = _check_pyopengl_3D()
1623
+ depth, height, width = pixels.shape[:3]
1624
+ _gl.glTexSubImage3D(target, level, xoffset, yoffset, zoffset,
1625
+ width, height, depth, format, type, pixels)
1626
+
1627
+
1628
+ class GlirTexture3D(GlirTexture):
1629
+ _target = GL_TEXTURE_3D
1630
+
1631
+ def set_size(self, shape, format, internalformat):
1632
+ format = as_enum(format)
1633
+ if internalformat is not None:
1634
+ internalformat = as_enum(internalformat)
1635
+ else:
1636
+ internalformat = format
1637
+ # Shape is depth, height, width
1638
+ if (shape, format, internalformat) != self._shape_formats:
1639
+ self.activate()
1640
+ self._shape_formats = shape, format, internalformat
1641
+ glTexImage3D(self._target, 0, internalformat, format,
1642
+ gl.GL_BYTE, shape[:3])
1643
+
1644
+ def set_data(self, offset, data):
1645
+ self.activate()
1646
+ shape, format, internalformat = self._shape_formats
1647
+ z, y, x = offset
1648
+ # Get gtype
1649
+ gtype = self._types.get(np.dtype(data.dtype), None)
1650
+ if gtype is None:
1651
+ raise ValueError("Type not allowed for texture")
1652
+ # Set alignment (width is nbytes_per_pixel * npixels_per_line)
1653
+ alignment = self._get_alignment(data.shape[-2] * data.shape[-1] * data.itemsize)
1654
+ if alignment != 4:
1655
+ gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, alignment)
1656
+ # Upload
1657
+ glTexSubImage3D(self._target, 0, x, y, z, format, gtype, data)
1658
+ # Set alignment back
1659
+ if alignment != 4:
1660
+ gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 4)
1661
+
1662
+
1663
+ class GlirTextureCube(GlirTexture):
1664
+ _target = gl.GL_TEXTURE_CUBE_MAP
1665
+ _cube_targets = [
1666
+ gl.GL_TEXTURE_CUBE_MAP_POSITIVE_X,
1667
+ gl.GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
1668
+ gl.GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
1669
+ gl.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
1670
+ gl.GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
1671
+ gl.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
1672
+ ]
1673
+
1674
+ def set_size(self, shape, format, internalformat):
1675
+ format = as_enum(format)
1676
+ internalformat = format if internalformat is None \
1677
+ else as_enum(internalformat)
1678
+ if (shape, format, internalformat) != self._shape_formats:
1679
+ self._shape_formats = shape, format, internalformat
1680
+ self.activate()
1681
+ for target in self._cube_targets:
1682
+ gl.glTexImage2D(target, 0, internalformat, format,
1683
+ gl.GL_UNSIGNED_BYTE, shape[1:3])
1684
+
1685
+ def set_data(self, offset, data):
1686
+ shape, format, internalformat = self._shape_formats
1687
+ y, x = offset[:2]
1688
+ # Get gtype
1689
+ gtype = self._types.get(np.dtype(data.dtype), None)
1690
+ if gtype is None:
1691
+ raise ValueError("Type %r not allowed for texture" % data.dtype)
1692
+ self.activate()
1693
+ # Set alignment (width is nbytes_per_pixel * npixels_per_line)
1694
+ alignment = self._get_alignment(data.shape[-2] * data.shape[-1] * data.itemsize)
1695
+ if alignment != 4:
1696
+ gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, alignment)
1697
+ # Upload
1698
+ for i, target in enumerate(self._cube_targets):
1699
+ gl.glTexSubImage2D(target, 0, x, y, format, gtype, data[i])
1700
+ # Set alignment back
1701
+ if alignment != 4:
1702
+ gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 4)
1703
+
1704
+
1705
+ class GlirRenderBuffer(GlirObject):
1706
+
1707
+ def create(self):
1708
+ self._handle = gl.glCreateRenderbuffer()
1709
+ self._shape_format = 0 # To make setting size cheap
1710
+
1711
+ def delete(self):
1712
+ gl.glDeleteRenderbuffer(self._handle)
1713
+
1714
+ def activate(self):
1715
+ gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, self._handle)
1716
+
1717
+ def deactivate(self):
1718
+ gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, 0)
1719
+
1720
+ def set_size(self, shape, format):
1721
+ if isinstance(format, str):
1722
+ format = GlirFrameBuffer._formats[format][1]
1723
+ if (shape, format) != self._shape_format:
1724
+ self._shape_format = shape, format
1725
+ self.activate()
1726
+ gl.glRenderbufferStorage(gl.GL_RENDERBUFFER, format,
1727
+ shape[1], shape[0])
1728
+
1729
+
1730
+ class GlirFrameBuffer(GlirObject):
1731
+
1732
+ # todo: on ES 2.0 -> gl.gl_RGBA4
1733
+ _formats = {'color': (gl.GL_COLOR_ATTACHMENT0, gl.GL_RGBA),
1734
+ 'depth': (gl.GL_DEPTH_ATTACHMENT, gl.GL_DEPTH_COMPONENT16),
1735
+ 'stencil': (gl.GL_STENCIL_ATTACHMENT, gl.GL_STENCIL_INDEX8)}
1736
+
1737
+ def create(self):
1738
+ # self._parser._fb_stack = [0] # To keep track of active FB
1739
+ self._handle = gl.glCreateFramebuffer()
1740
+ self._validated = False
1741
+
1742
+ def delete(self):
1743
+ gl.glDeleteFramebuffer(self._handle)
1744
+
1745
+ def set_framebuffer(self, yes):
1746
+ if yes:
1747
+ self.activate()
1748
+ if not self._validated:
1749
+ self._validated = True
1750
+ self._validate()
1751
+ else:
1752
+ self.deactivate()
1753
+
1754
+ def activate(self):
1755
+ stack = self._parser.env.setdefault('fb_stack',
1756
+ [self._parser.env['fbo']])
1757
+ if stack[-1] != self._handle:
1758
+ stack.append(self._handle)
1759
+ gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self._handle)
1760
+
1761
+ def deactivate(self):
1762
+ stack = self._parser.env.setdefault('fb_stack',
1763
+ [self._parser.env['fbo']])
1764
+ while self._handle in stack:
1765
+ stack.remove(self._handle)
1766
+ gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, stack[-1])
1767
+
1768
+ def attach(self, attachment, buffer_id):
1769
+ attachment = GlirFrameBuffer._formats[attachment][0]
1770
+ self.activate()
1771
+ if buffer_id == 0:
1772
+ gl.glFramebufferRenderbuffer(gl.GL_FRAMEBUFFER, attachment,
1773
+ gl.GL_RENDERBUFFER, 0)
1774
+ else:
1775
+ buffer = self._parser.get_object(buffer_id)
1776
+ if buffer == JUST_DELETED:
1777
+ return
1778
+ if buffer is None:
1779
+ raise ValueError("Unknown buffer with id %i for attachement" %
1780
+ buffer_id)
1781
+ elif isinstance(buffer, GlirRenderBuffer):
1782
+ buffer.activate()
1783
+ gl.glFramebufferRenderbuffer(gl.GL_FRAMEBUFFER, attachment,
1784
+ gl.GL_RENDERBUFFER, buffer.handle)
1785
+ buffer.deactivate()
1786
+ elif isinstance(buffer, GlirTexture2D):
1787
+ buffer.activate()
1788
+ # INFO: 0 is for mipmap level 0 (default) of the texture
1789
+ gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, attachment,
1790
+ gl.GL_TEXTURE_2D, buffer.handle, 0)
1791
+ buffer.deactivate()
1792
+ else:
1793
+ raise ValueError("Invalid attachment: %s" % type(buffer))
1794
+ self._validated = False
1795
+ self.deactivate()
1796
+
1797
+ def _validate(self):
1798
+ res = gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER)
1799
+ if res == gl.GL_FRAMEBUFFER_COMPLETE:
1800
+ return
1801
+ _bad_map = {
1802
+ 0: 'Target not equal to GL_FRAMEBUFFER',
1803
+ gl.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
1804
+ 'FrameBuffer attachments are incomplete.',
1805
+ gl.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
1806
+ 'No valid attachments in the FrameBuffer.',
1807
+ gl.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
1808
+ 'attachments do not have the same width and height.',
1809
+ # gl.GL_FRAMEBUFFER_INCOMPLETE_FORMATS: \ # not in es 2.0
1810
+ # 'Internal format of attachment is not renderable.'
1811
+ gl.GL_FRAMEBUFFER_UNSUPPORTED:
1812
+ 'Combination of internal formats used by attachments is '
1813
+ 'not supported.',
1814
+ }
1815
+ raise RuntimeError(_bad_map.get(res, 'Unknown framebuffer error: %r.'
1816
+ % res))