├── tests └── __init__.py ├── tutorials ├── __init__.py ├── media │ ├── __init__.py │ ├── shaders │ │ ├── light.frag │ │ ├── triangle.frag │ │ ├── triangle.vert │ │ ├── triangle2.frag │ │ ├── texture.frag │ │ ├── texture.vert │ │ ├── triangle2.vert │ │ ├── cube.vert │ │ └── cube.frag │ └── images │ │ ├── im0.png │ │ └── im1.png ├── 01-triangle │ ├── __init__.py │ ├── app.py │ └── gltriangle.py ├── 04-texture │ ├── __init__.py │ ├── app.py │ ├── gltexture.py │ └── TextureTutorial.ipynb ├── 05-cube │ ├── __init__.py │ ├── app.py │ ├── glcube.py │ └── CubeTutorial.ipynb ├── 06-events │ ├── __init__.py │ ├── app.py │ ├── EventsTutorial.ipynb │ └── glevents.py ├── utils │ ├── __init__.py │ ├── window.py │ ├── utils.py │ └── camera.py ├── 03-VaoVbo │ ├── app.py │ ├── glshader.py │ └── VAOsVBOs.ipynb └── 02-rectangle │ ├── app.py │ ├── RectangleTutorial.ipynb │ └── glrectangle.py ├── requirements.txt ├── setup.py ├── .gitignore ├── README.md └── LICENSE /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tutorials/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tutorials/media/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tutorials/01-triangle/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tutorials/04-texture/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tutorials/05-cube/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tutorials/06-events/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tutorials/utils/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | jupyter 2 | PySide2 == 5.11 3 | shiboken2 == 5.12 4 | -------------------------------------------------------------------------------- /tutorials/media/shaders/light.frag: -------------------------------------------------------------------------------- 1 | void main(){ 2 | gl_FragColor = vec4(1.0); 3 | } 4 | -------------------------------------------------------------------------------- /tutorials/media/images/im0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/D-K-E/pyside-opengl-tutorials/HEAD/tutorials/media/images/im0.png -------------------------------------------------------------------------------- /tutorials/media/images/im1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/D-K-E/pyside-opengl-tutorials/HEAD/tutorials/media/images/im1.png -------------------------------------------------------------------------------- /tutorials/media/shaders/triangle.frag: -------------------------------------------------------------------------------- 1 | uniform mediump vec4 color; 2 | 3 | void main(void) 4 | { 5 | gl_FragColor = color; 6 | } 7 | -------------------------------------------------------------------------------- /tutorials/media/shaders/triangle.vert: -------------------------------------------------------------------------------- 1 | attribute highp vec3 aPos; 2 | void main(void) 3 | { 4 | gl_Position = vec4(aPos, 1.0); 5 | } 6 | -------------------------------------------------------------------------------- /tutorials/media/shaders/triangle2.frag: -------------------------------------------------------------------------------- 1 | #version 420 core 2 | 3 | varying mediump vec4 vertexColor; 4 | 5 | void main() { 6 | gl_FragColor = vertexColor; 7 | } 8 | -------------------------------------------------------------------------------- /tutorials/media/shaders/texture.frag: -------------------------------------------------------------------------------- 1 | varying highp vec2 TexCoord; 2 | 3 | uniform sampler2D myTexture; 4 | 5 | void main(void) 6 | { 7 | gl_FragColor = texture(myTexture, TexCoord); 8 | } 9 | -------------------------------------------------------------------------------- /tutorials/media/shaders/texture.vert: -------------------------------------------------------------------------------- 1 | attribute highp vec3 aPos; 2 | attribute highp vec2 aTexCoord; 3 | 4 | varying highp vec2 TexCoord; 5 | 6 | void main(void) 7 | { 8 | gl_Position = vec4(aPos, 1.0); 9 | TexCoord = aTexCoord; 10 | } 11 | -------------------------------------------------------------------------------- /tutorials/media/shaders/triangle2.vert: -------------------------------------------------------------------------------- 1 | 2 | attribute highp vec3 aPos; 3 | 4 | varying mediump vec4 vertexColor; 5 | 6 | void main() { 7 | gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0); 8 | vertexColor = vec4(0.1, 0.3, 0.8, 1.0); 9 | } 10 | -------------------------------------------------------------------------------- /tutorials/media/shaders/cube.vert: -------------------------------------------------------------------------------- 1 | attribute highp vec3 aPos; 2 | attribute mediump vec2 aTexCoord; 3 | 4 | uniform highp mat4 view; 5 | uniform highp mat4 model; 6 | uniform highp mat4 projection; 7 | 8 | varying mediump vec2 TexCoord; 9 | 10 | void main(void) 11 | { 12 | gl_Position = projection * view * model * vec4(aPos, 1.0); 13 | TexCoord = aTexCoord; 14 | } 15 | -------------------------------------------------------------------------------- /tutorials/05-cube/app.py: -------------------------------------------------------------------------------- 1 | # Author: Kaan Eraslan 2 | 3 | from PySide2 import QtWidgets 4 | from tutorials.utils.window import GLWindow as AppWindow 5 | from glcube import CubeGL 6 | import sys 7 | 8 | 9 | if __name__ == '__main__': 10 | app = QtWidgets.QApplication(sys.argv) 11 | window = AppWindow(CubeGL) 12 | window.show() 13 | res = app.exec_() 14 | sys.exit(res) 15 | -------------------------------------------------------------------------------- /tutorials/03-VaoVbo/app.py: -------------------------------------------------------------------------------- 1 | # Author: Kaan Eraslan 2 | 3 | from PySide2 import QtWidgets 4 | from glshader import TriangleGL 5 | from tutorials.utils.window import GLWindow as AppWindow 6 | import sys 7 | 8 | 9 | if __name__ == '__main__': 10 | app = QtWidgets.QApplication(sys.argv) 11 | window = AppWindow(TriangleGL) 12 | window.show() 13 | res = app.exec_() 14 | sys.exit(res) 15 | -------------------------------------------------------------------------------- /tutorials/04-texture/app.py: -------------------------------------------------------------------------------- 1 | # Author: Kaan Eraslan 2 | 3 | from PySide2 import QtWidgets 4 | from tutorials.utils.window import GLWindow as AppWindow 5 | from gltexture import TextureGL 6 | import sys 7 | 8 | 9 | if __name__ == '__main__': 10 | app = QtWidgets.QApplication(sys.argv) 11 | window = AppWindow(TextureGL) 12 | window.show() 13 | res = app.exec_() 14 | sys.exit(res) 15 | -------------------------------------------------------------------------------- /tutorials/01-triangle/app.py: -------------------------------------------------------------------------------- 1 | # Author: Kaan Eraslan 2 | 3 | from PySide2 import QtWidgets 4 | from gltriangle import TriangleGL 5 | from tutorials.utils.window import GLWindow as AppWindow 6 | import sys 7 | 8 | if __name__ == '__main__': 9 | app = QtWidgets.QApplication(sys.argv) 10 | window = AppWindow(glwidget=TriangleGL) 11 | window.show() 12 | res = app.exec_() 13 | sys.exit(res) 14 | -------------------------------------------------------------------------------- /tutorials/02-rectangle/app.py: -------------------------------------------------------------------------------- 1 | # Author: Kaan Eraslan 2 | 3 | from PySide2 import QtWidgets, QtCore, QtGui 4 | from glrectangle import RectangleGL 5 | from tutorials.utils.window import GLWindow as AppWindow 6 | import sys 7 | 8 | 9 | if __name__ == '__main__': 10 | app = QtWidgets.QApplication(sys.argv) 11 | window = AppWindow(RectangleGL) 12 | window.show() 13 | res = app.exec_() 14 | sys.exit(res) 15 | -------------------------------------------------------------------------------- /tutorials/media/shaders/cube.frag: -------------------------------------------------------------------------------- 1 | varying mediump vec2 TexCoord; 2 | 3 | uniform sampler2D myTexture1; 4 | uniform sampler2D myTexture2; 5 | 6 | void main(void) 7 | { 8 | // linear interpolation of first texture with second one 9 | // 30% indicates the amount of the presence of the second one 10 | gl_FragColor = mix(texture(myTexture1, TexCoord), texture(myTexture2, TexCoord), 0.4); 11 | //gl_FragColor = texture(myTexture2, TexCoord); 12 | } 13 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | import setuptools 3 | 4 | 5 | # currentdir = os.getcwd() 6 | 7 | with open("README.md", "r", encoding="utf-8") as f: 8 | long_desc = f.read() 9 | 10 | with open("LICENSE", "r", encoding="utf-8") as f: 11 | license_str = f.read() 12 | 13 | setuptools.setup( 14 | name="PysideOpenGLTutorials", 15 | version="0.1", 16 | author='Kaan Eraslan', 17 | python_requires='>=3.5.0', 18 | author_email="kaaneraslan@gmail.com", 19 | description="Tutorials on OpenGL api of PySide2", 20 | long_description=long_desc, 21 | long_description_content_type="text/markdown", 22 | license=license_str, 23 | url="https://github.com/D-K-E/pyside-opengl-tutorials", 24 | packages=setuptools.find_packages( 25 | exclude=["tests", "*.tests", "*.tests.*", "tests.*", 26 | "docs", ".gitignore", "README.md"], 27 | ), 28 | test_suite="tests", 29 | install_requires=[ 30 | "numpy", 31 | "jupyter" 32 | ], 33 | classifiers=[ 34 | "Programming Language :: Python :: 3", 35 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 36 | "Operating System :: OS Independent", 37 | ], 38 | ) 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pyside-opengl-tutorials 2 | Tutorials on the new QtGui based OpenGL api of PySide2 3 | 4 | 5 | ## Requirements 6 | 7 | In the main folder which contains the `setup.py` execute the following 8 | commands on the terminal. 9 | 10 | - Create a virtual env with conda `conda create -n pyside-opengl-tuto` 11 | 12 | - Activate your virtual env `conda activate pyside-opengl-tuto` 13 | 14 | - Install python `conda install -c conda-forge python=3` 15 | 16 | - Install requirements with pip `pip install -r requirements.txt` 17 | 18 | - Install PyOpenGL_accelerate `conda install -c anaconda pyopengl-accelerate` 19 | 20 | - Normally PyOpenGL_accelerate installation automatically installs the 21 | PyOpenGL, check this by verfying your list of packages `conda list` 22 | 23 | - Setup the rest of the packages using pip `pip install .` 24 | 25 | 26 | ## Description 27 | 28 | There are unfortunately not a lot of tutorials on using pyside2 for rendering 29 | OpenGL. 30 | This is simply a collection of tutorials on using PySide2 for rendering 31 | opengl graphics. 32 | If you are not an experienced user with opengl the code can be strange and 33 | daunting at times due to low level nature of OpenGL though I try to 34 | comment as much as I can. 35 | If you are an absolute beginner, I suggest you to follow at least the Getting Started section from the infamous `https://learnopengl.com/` 36 | 37 | If you are somewhat experienced with opengl but just want to test PySide2 as 38 | front end to it. These tutorials should give you a rough idea about how to 39 | initialize GL, how to render your drawing loop, as well as passing data to 40 | your scene like textures or keystrokes etc. 41 | 42 | The first tutorial `triangle` is heavily commented, the rest of them simply 43 | points out differences with respect to c/c++ or to other tutorials. 44 | 45 | The tutorials are linear in nature, so you can use it alongside with 46 | other learning ressources for OpenGL. 47 | 48 | If you feel like you can contribute to tutorials, they are always welcomed. 49 | 50 | 51 | ## List of Tutorials 52 | 53 | As stated in the description the list is progressive. 54 | 55 | 1. [Hello Triangle](./tutorials/01-triangle/TriangleTutorial.ipynb) 56 | 2. [Rectangle](./tutorials/02-rectangle/RectangleTutorial.ipynb) 57 | 3. [Multiple VAO-VBO couples](./tutorials/03-VaoVbo/VAOsVBOs.ipynb) 58 | 4. [Render an Image - Texture](./tutorials/04-texture/TextureTutorial.ipynb) 59 | 5. [Hello Cube - 3D rendering](./tutorials/05-cube/CubeTutorial.ipynb) 60 | 5. [Event Handling](./tutorials/06-events/EventsTutorial.ipynb) 61 | -------------------------------------------------------------------------------- /tutorials/06-events/app.py: -------------------------------------------------------------------------------- 1 | # Author: Kaan Eraslan 2 | 3 | from PySide2 import QtWidgets 4 | from tutorials.utils.window import GLWindow as AppWindow 5 | from glevents import EventsGL 6 | import sys 7 | 8 | 9 | class EventAppWindow(AppWindow): 10 | "Overriding base class with event methods" 11 | 12 | def __init__(self, 13 | glwidget: QtWidgets.QOpenGLWidget, 14 | parent=None, 15 | ): 16 | super().__init__(glwidget, 17 | parent) 18 | self.camX.setRange(-520.0, 520.0) 19 | self.camY.setRange(-520.0, 520.0) 20 | self.xSlider.setRange(-180.0, 180.0) 21 | self.ySlider.setRange(-180.0, 180.0) 22 | self.zSlider.setRange(-180.0, 180.0) 23 | self.upBtn.clicked.connect(self.moveCameraForward) 24 | self.downBtn.clicked.connect(self.moveCameraBackward) 25 | self.leftBtn.clicked.connect(self.moveCameraLeft) 26 | self.rightBtn.clicked.connect(self.moveCameraRight) 27 | self.camX.valueChanged.connect(self.turnCameraX) 28 | self.camY.valueChanged.connect(self.turnCameraY) 29 | self.xSlider.valueChanged.connect(self.rotateCubes) 30 | self.ySlider.valueChanged.connect(self.rotateCubes) 31 | self.zSlider.valueChanged.connect(self.rotateCubes) 32 | # 33 | self.lastCamXVal = self.camX.value() 34 | # 35 | self.lastCamYVal = self.camY.value() 36 | 37 | def moveGLCamera(self, direction: str): 38 | self.glWidget.moveCamera(direction) 39 | 40 | def moveCameraForward(self): 41 | self.moveGLCamera("forward") 42 | 43 | def moveCameraBackward(self): 44 | self.moveGLCamera("backward") 45 | 46 | def moveCameraLeft(self): 47 | self.moveGLCamera("left") 48 | 49 | def moveCameraRight(self): 50 | self.moveGLCamera("right") 51 | 52 | def turnCameraX(self, newVal: int): 53 | "Turn camera around" 54 | offsetx = newVal - self.lastCamXVal 55 | valy = self.camY.value() - self.lastCamYVal 56 | self.glWidget.turnAround(x=float(offsetx), 57 | y=float(valy)) 58 | self.lastCamXVal = newVal 59 | 60 | def turnCameraY(self, newVal: int): 61 | "Turn camera around" 62 | offsety = newVal - self.lastCamYVal 63 | valx = self.camX.value() - self.lastCamXVal 64 | self.glWidget.turnAround(x=float(valx), 65 | y=float(offsety)) 66 | self.lastCamYVal = newVal 67 | 68 | def rotateCubes(self): 69 | rx = self.xSlider.value() 70 | ry = self.ySlider.value() 71 | rz = self.zSlider.value() 72 | self.glWidget.rotateCubes(rx, ry, rz) 73 | 74 | 75 | if __name__ == '__main__': 76 | app = QtWidgets.QApplication(sys.argv) 77 | window = EventAppWindow(EventsGL) 78 | window.show() 79 | res = app.exec_() 80 | sys.exit(res) 81 | -------------------------------------------------------------------------------- /tutorials/utils/window.py: -------------------------------------------------------------------------------- 1 | # window for showing widgets 2 | from PySide2 import QtWidgets, QtCore, QtGui 3 | 4 | 5 | def createSlider(): 6 | slider = QtWidgets.QSlider(QtCore.Qt.Vertical) 7 | 8 | slider.setRange(0, 360 * 16) 9 | slider.setSingleStep(16) 10 | slider.setPageStep(15 * 16) 11 | slider.setTickInterval(15 * 16) 12 | slider.setTickPosition(QtWidgets.QSlider.TicksRight) 13 | return slider 14 | 15 | 16 | class GLWindow(QtWidgets.QMainWindow): 17 | "Application window" 18 | 19 | def __init__(self, 20 | glwidget: QtWidgets.QOpenGLWidget, 21 | parent=None, 22 | ): 23 | super().__init__(parent) 24 | # 25 | self.glLayout = QtWidgets.QVBoxLayout() 26 | self.glLabel = QtWidgets.QLabel("OpenGL Widget") 27 | self.glWidget = glwidget() 28 | self.glLayout.addWidget(self.glLabel) 29 | self.glLayout.addWidget(self.glWidget) 30 | self.glLayout.setStretchFactor(self.glWidget, 1) 31 | self.glSection = QtWidgets.QWidget() 32 | self.glSection.setLayout(self.glLayout) 33 | # 34 | self.labelx = QtWidgets.QLabel("x") 35 | self.labely = QtWidgets.QLabel("y") 36 | self.labelz = QtWidgets.QLabel("z") 37 | self.xSlider = createSlider() 38 | self.ySlider = createSlider() 39 | self.zSlider = createSlider() 40 | # 41 | sliderLayoutV1 = QtWidgets.QVBoxLayout() 42 | sliderLayoutV1.addWidget(self.labelx) 43 | sliderLayoutV1.addWidget(self.xSlider) 44 | # 45 | sliderLayoutV2 = QtWidgets.QVBoxLayout() 46 | sliderLayoutV2.addWidget(self.labely) 47 | sliderLayoutV2.addWidget(self.ySlider) 48 | # 49 | sliderLayoutV3 = QtWidgets.QVBoxLayout() 50 | sliderLayoutV3.addWidget(self.labelz) 51 | sliderLayoutV3.addWidget(self.zSlider) 52 | # 53 | sliderSection = QtWidgets.QVBoxLayout() 54 | slidersLayout = QtWidgets.QHBoxLayout() 55 | slidersTitle = QtWidgets.QLabel('Rotate cubes') 56 | slidersLayout.addLayout(sliderLayoutV1) 57 | slidersLayout.addLayout(sliderLayoutV2) 58 | slidersLayout.addLayout(sliderLayoutV3) 59 | sliderSection.addWidget(slidersTitle) 60 | sliderSection.addLayout(slidersLayout) 61 | slidersWidget = QtWidgets.QWidget() 62 | slidersWidget.setLayout(sliderSection) 63 | # Rotate camera 64 | self.camX = createSlider() 65 | self.camY = createSlider() 66 | self.camlabelx = QtWidgets.QLabel("x") 67 | self.camlabely = QtWidgets.QLabel("y") 68 | self.camlabel = QtWidgets.QLabel("Rotate camera") 69 | camV1 = QtWidgets.QVBoxLayout() 70 | camV2 = QtWidgets.QVBoxLayout() 71 | camV1.addWidget(self.camlabelx) 72 | camV1.addWidget(self.camX) 73 | camV2.addWidget(self.camlabely) 74 | camV2.addWidget(self.camY) 75 | cams = QtWidgets.QHBoxLayout() 76 | cams.addLayout(camV1) 77 | cams.addLayout(camV2) 78 | camsWidget = QtWidgets.QWidget() 79 | camsWidget.setLayout(cams) 80 | 81 | camSection = QtWidgets.QVBoxLayout() 82 | camSection.addWidget(self.camlabel) 83 | camSection.addWidget(camsWidget) 84 | camSection.setStretchFactor(camsWidget, 1) 85 | camSecWidget = QtWidgets.QWidget() 86 | camSecWidget.setLayout(camSection) 87 | # 88 | buttonsTitel = QtWidgets.QLabel("Move camera") 89 | buttonsLayoutH1 = QtWidgets.QHBoxLayout() 90 | buttonsLayoutH2 = QtWidgets.QHBoxLayout() 91 | buttonsLayoutV = QtWidgets.QVBoxLayout() 92 | self.leftBtn = QtWidgets.QPushButton() 93 | self.rightBtn = QtWidgets.QPushButton() 94 | self.upBtn = QtWidgets.QPushButton() 95 | self.downBtn = QtWidgets.QPushButton() 96 | buttonsLayoutH1.addWidget(self.upBtn) 97 | buttonsLayoutH2.addWidget(self.leftBtn) 98 | buttonsLayoutH2.addWidget(self.downBtn) 99 | buttonsLayoutH2.addWidget(self.rightBtn) 100 | buttonsLayoutV.addWidget(buttonsTitel) 101 | buttonsLayoutV.addLayout(buttonsLayoutH1) 102 | buttonsLayoutV.addLayout(buttonsLayoutH2) 103 | buttonsLayoutV.addWidget(camSecWidget) 104 | buttonsWidget = QtWidgets.QWidget() 105 | buttonsWidget.setLayout(buttonsLayoutV) 106 | # 107 | self.leftBtn.setText("<") 108 | self.rightBtn.setText(">") 109 | self.upBtn.setText("^") 110 | self.downBtn.setText("v") 111 | 112 | mainLayout = QtWidgets.QHBoxLayout() 113 | mainLayout.addWidget(self.glSection) 114 | mainLayout.addWidget(slidersWidget) 115 | mainLayout.addWidget(buttonsWidget) 116 | mainLayout.setStretchFactor(self.glSection, 1) 117 | self.mainwidget = QtWidgets.QWidget() 118 | self.mainwidget.setLayout(mainLayout) 119 | self.setCentralWidget(self.mainwidget) 120 | self.setWindowTitle("PySide2 OpenGL Test Window") 121 | self.setMinimumSize(800, 600) 122 | 123 | def keyPressEvent(self, event): 124 | if event.key() == QtCore.Qt.Key_Escape: 125 | self.close() 126 | else: 127 | super().keyPressEvent(event) 128 | -------------------------------------------------------------------------------- /tutorials/02-rectangle/RectangleTutorial.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Rectangle Tutorial" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "Welcome to the tutorial on how to draw a rectangle using the new QtGui based OpenGL api of PySide2.\n", 15 | "\n", 16 | "As we have mentioned on the first tutorial on how to draw the `Hello Triangle`. I will be giving only the relative parts of the code and explain the differences rather than commenting everything.\n", 17 | "\n", 18 | "Let's see the final output of our application" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 2, 24 | "metadata": {}, 25 | "outputs": [ 26 | { 27 | "data": { 28 | "text/plain": [ 29 | "CompletedProcess(args=['python', 'app.py'], returncode=0)" 30 | ] 31 | }, 32 | "execution_count": 2, 33 | "metadata": {}, 34 | "output_type": "execute_result" 35 | } 36 | ], 37 | "source": [ 38 | "import subprocess\n", 39 | "\n", 40 | "subprocess.run([\"python\", \"app.py\"])" 41 | ] 42 | }, 43 | { 44 | "cell_type": "markdown", 45 | "metadata": {}, 46 | "source": [ 47 | "Not so bad right !" 48 | ] 49 | }, 50 | { 51 | "cell_type": "markdown", 52 | "metadata": {}, 53 | "source": [ 54 | "I am skipping the code on the window holding the gl widget. \n", 55 | "\n", 56 | "Here is the constructor of our gl widget." 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": null, 62 | "metadata": {}, 63 | "outputs": [], 64 | "source": [ 65 | "class RectangleGL(QOpenGLWidget):\n", 66 | " \"Texture loading opengl widget\"\n", 67 | "\n", 68 | " def __init__(self, parent=None):\n", 69 | " \"Constructor\"\n", 70 | " QOpenGLWidget.__init__(self, parent)\n", 71 | " tutoTutoDir = os.path.dirname(__file__)\n", 72 | " tutoPardir = os.path.join(tutoTutoDir, os.pardir)\n", 73 | " tutoPardir = os.path.realpath(tutoPardir)\n", 74 | " mediaDir = os.path.join(tutoPardir, \"media\")\n", 75 | " shaderDir = os.path.join(mediaDir, \"shaders\")\n", 76 | " #\n", 77 | " availableShaders = [\"rectangle\", \"triangle\"]\n", 78 | " self.shaders = {\n", 79 | " name: {\n", 80 | " \"fragment\": os.path.join(shaderDir, name + \".frag\"),\n", 81 | " \"vertex\": os.path.join(shaderDir, name + \".vert\")\n", 82 | " } for name in availableShaders\n", 83 | " }\n", 84 | " self.core = \"--coreprofile\" in QCoreApplication.arguments()\n", 85 | "\n", 86 | " # opengl data related\n", 87 | " self.context = QOpenGLContext()\n", 88 | " self.program = QOpenGLShaderProgram()\n", 89 | " self.vao = QOpenGLVertexArrayObject()\n", 90 | " self.vbo = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer)\n", 91 | " \n", 92 | " # ############ Diff 1 ##########################\n", 93 | " # this is the novelty in this code. We specify #\n", 94 | " # indices of triangles that would made up #\n", 95 | " # our rectangle. Notice its data type #\n", 96 | " self.indices = np.array([\n", 97 | " 0, 1, 3, # first triangle\n", 98 | " 1, 2, 3 # second triangle\n", 99 | " ], dtype=ctypes.c_uint)\n", 100 | "\n", 101 | " # vertex data of the panel that would hold the image\n", 102 | " \n", 103 | " self.vertexData = np.array([\n", 104 | " # corners of the rectangle\n", 105 | " 0.5, 0.5, 0.0, # top right\n", 106 | " 0.5, -0.5, 0.0, # bottom right\n", 107 | " -0.5, -0.5, 0.0, # bottom left\n", 108 | " -0.5, 0.5, 0.0, # top left\n", 109 | " ], dtype=ctypes.c_float)\n", 110 | "\n", 111 | " self.rectColor = QVector4D(0.0, 1.0, 1.0, 0.0)" 112 | ] 113 | }, 114 | { 115 | "cell_type": "markdown", 116 | "metadata": {}, 117 | "source": [ 118 | "As you can see it is fairly close to the constructor of the triangle widget.\n", 119 | "The initialization is exactly the same as triangle widget so we are skipping that entirely.\n", 120 | "\n", 121 | "Let's see the drawing function." 122 | ] 123 | }, 124 | { 125 | "cell_type": "code", 126 | "execution_count": null, 127 | "metadata": {}, 128 | "outputs": [], 129 | "source": [ 130 | " def paintGL(self):\n", 131 | " \"paint gl\"\n", 132 | " funcs = self.context.functions()\n", 133 | " # clean up what was drawn\n", 134 | " funcs.glClear(pygl.GL_COLOR_BUFFER_BIT)\n", 135 | "\n", 136 | " # bind texture\n", 137 | " vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao)\n", 138 | " self.program.bind()\n", 139 | "\n", 140 | " # draw stuff\n", 141 | " ########## Diff #############\n", 142 | " # This is another drawing function in opengl\n", 143 | " # Notice that its signature is from OpenGL ES 2\n", 144 | " \n", 145 | " funcs.glDrawElements(\n", 146 | " pygl.GL_TRIANGLES,\n", 147 | " self.indices.size,\n", 148 | " pygl.GL_UNSIGNED_INT,\n", 149 | " self.indices.tobytes())\n", 150 | " # VoidPtr(self.indices.tobytes() * ctypes.sizeof(ctypes.c_uint)))\n", 151 | " vaoBinder = None\n", 152 | " self.program.release()" 153 | ] 154 | }, 155 | { 156 | "cell_type": "markdown", 157 | "metadata": {}, 158 | "source": [ 159 | "- The first parameter is the drawing mode.\n", 160 | "- The second is the number of elements that is to be drawn, since the indice specifies the index of an element that is to be drawn, it is equal to the size of indices.\n", 161 | "- We specify the type of the elements of indices\n", 162 | "- We specify the data of indices. \n", 163 | "\n", 164 | "If we want to follow documentation more closely we can also use the commented line instead of the final parameter which creates the void pointer to data of the indices" 165 | ] 166 | }, 167 | { 168 | "cell_type": "markdown", 169 | "metadata": {}, 170 | "source": [ 171 | "That's it now you know how to draw a rectangle in opengl api of pyside2" 172 | ] 173 | } 174 | ], 175 | "metadata": { 176 | "kernelspec": { 177 | "display_name": "Python 3", 178 | "language": "python", 179 | "name": "python3" 180 | }, 181 | "language_info": { 182 | "codemirror_mode": { 183 | "name": "ipython", 184 | "version": 3 185 | }, 186 | "file_extension": ".py", 187 | "mimetype": "text/x-python", 188 | "name": "python", 189 | "nbconvert_exporter": "python", 190 | "pygments_lexer": "ipython3", 191 | "version": "3.7.3" 192 | } 193 | }, 194 | "nbformat": 4, 195 | "nbformat_minor": 2 196 | } 197 | -------------------------------------------------------------------------------- /tutorials/utils/utils.py: -------------------------------------------------------------------------------- 1 | # author: Kaan Eraslan 2 | # some util functions 3 | 4 | import numpy as np 5 | 6 | from PySide2.QtGui import QVector3D 7 | from PySide2.QtGui import QVector4D 8 | from PySide2.QtGui import QMatrix4x4 9 | 10 | 11 | def normalize_1d_array(arr): 12 | "Normalize 1d array" 13 | assert arr.ndim == 1 14 | result = None 15 | if np.linalg.norm(arr) == 0: 16 | result = arr 17 | else: 18 | result = arr / np.linalg.norm(arr) 19 | return result 20 | 21 | 22 | def normalize_tuple(vec: tuple): 23 | "Normalize 1 d tuple" 24 | vecSum = sum([v ** 2 for v in vec]) 25 | if vecSum == 0: 26 | return vec 27 | else: 28 | return tuple([v/vecSum for v in vec]) 29 | 30 | 31 | def crossProduct(vec1, vec2): 32 | "take cross products of two vectors" 33 | assert len(vec1) == 3 and len(vec2) == 3 34 | vec3x = vec1[1] * vec2[2] - vec1[2] * vec2[1] 35 | vec3y = vec1[2] * vec2[0] - vec1[0] * vec2[2] 36 | vec3z = vec1[0] * vec2[1] - vec1[1] * vec2[0] 37 | return (vec3x, vec3y, vec3z) 38 | 39 | 40 | def vec2vecDot(vec1, vec2): 41 | "vector to vector dot product" 42 | assert len(vec1) == len(vec2) 43 | return tuple( 44 | sum(v1*v2 for v1, v2 in zip(vec1, vec2)) 45 | ) 46 | 47 | 48 | def sliceCol(colInd: int, matrix): 49 | "slice column values from matrix" 50 | rownb = len(matrix) 51 | return [matrix[i, colInd] for i in range(rownb)] 52 | 53 | 54 | def mat2matDot(mat1: list, mat2: list): 55 | "Dot product in pure python" 56 | assert len(mat1[0]) == len(mat2) 57 | colnb = len(mat1[0]) 58 | mat = [] 59 | for rown in range(len(mat1)): 60 | newmatRow = [] 61 | mat1Row = mat1[rown] 62 | for coln in range(colnb): 63 | mat2col = sliceCol(coln, mat2) 64 | newmatRow.append( 65 | vec2vecDot(mat1Row, mat2col) 66 | ) 67 | mat.append(newmatRow) 68 | return mat 69 | 70 | 71 | def scalar2vecMult(vec, scalar): 72 | "scalar multiplication of a vector" 73 | return tuple([v * scalar for v in vec]) 74 | 75 | 76 | def vec2vecAdd(vec1, vec2): 77 | "vector to vector addition" 78 | assert len(vec1) == len(vec2) 79 | return tuple( 80 | [vec1[i]+vec2[i] for i in range(len(vec1))] 81 | ) 82 | 83 | 84 | def vec2vecSubs(vec1, vec2): 85 | "vector to vector subtraction" 86 | assert len(vec1) == len(vec2) 87 | return tuple( 88 | [vec1[i]-vec2[i] for i in range(len(vec1))] 89 | ) 90 | 91 | 92 | def computeLookAtPure(pos: tuple, 93 | center: tuple, 94 | up: tuple): 95 | "" 96 | 97 | 98 | def computePerspectiveNp(fieldOfView: float, 99 | aspect: float, 100 | zNear: float, zFar: float): 101 | "Reproduces glm perspective function" 102 | assert aspect != 0 103 | assert zNear != zFar 104 | fieldOfViewRad = np.radians(fieldOfView) 105 | fieldHalfTan = np.tan(fieldOfViewRad / 2) 106 | # mat4 107 | result = np.zeros((4, 4), dtype=float) 108 | result[0, 0] = 1 / (aspect * fieldHalfTan) 109 | result[1, 1] = 1 / fieldHalfTan 110 | result[2, 2] = -(zFar + zNear) / (zFar - zNear) 111 | result[3, 2] = -1 112 | result[2, 3] = -(2 * zFar * zNear) / (zFar - zNear) 113 | return result 114 | 115 | 116 | def computePerspectiveQt(fieldOfView: float, 117 | aspect: float, 118 | zNear: float, zFar: float): 119 | "matrice" 120 | mat = QMatrix4x4(*[0.0 for i in range(16)]) 121 | return mat.perspective(fieldOfView, 122 | aspect, 123 | zNear, zFar) 124 | 125 | 126 | def computeLookAtPure(pos: tuple, 127 | target: tuple, 128 | worldUp: tuple): 129 | "" 130 | assert len(pos) == 3 and len(target) == 3 131 | assert len(worldUp) == 3 132 | zaxis = normalize_tuple(vec2vecSubs(pos, target)) 133 | 134 | # x axis 135 | normWorld = normalize_tuple(worldUp) 136 | xaxis = normalize_tuple(crossProduct(normWorld, 137 | zaxis)) 138 | yaxis = crossProduct(zaxis, xaxis) 139 | translation = [ 140 | [1 for i in range(4)] for k in range(4) 141 | ] 142 | translation[0][3] = -pos[0] 143 | translation[1][3] = -pos[1] # third col, second row 144 | translation[2][3] = -pos[2] 145 | 146 | rotation = [ 147 | [1 for i in range(4)] for k in range(4) 148 | ] 149 | rotation[0][0] = xaxis[0] 150 | rotation[0][1] = xaxis[1] 151 | rotation[0][2] = xaxis[2] 152 | rotation[1][0] = yaxis[0] 153 | rotation[1][1] = yaxis[1] 154 | rotation[1][2] = yaxis[2] 155 | rotation[2][0] = zaxis[0] 156 | rotation[2][1] = zaxis[1] 157 | rotation[2][2] = zaxis[2] 158 | return mat2matDot(translation, rotation) 159 | 160 | 161 | def computeLookAtMatrixNp(position: np.ndarray, 162 | target: np.ndarray, 163 | worldUp: np.ndarray): 164 | "Compute a look at matrix for given position and target" 165 | assert position.ndim == 1 and target.ndim == 1 and worldUp.ndim == 1 166 | zaxis = normalize_1d_array(position - target) 167 | 168 | # positive xaxis at right 169 | xaxis = normalize_1d_array(np.cross( 170 | normalize_1d_array(worldUp), zaxis) 171 | ) 172 | # camera up 173 | yaxis = np.cross(zaxis, xaxis) 174 | 175 | # compute translation matrix 176 | translation = np.ones((4, 4), dtype=np.float) 177 | translation[0, 3] = -position[0] # third col, first row 178 | translation[1, 3] = -position[1] # third col, second row 179 | translation[2, 3] = -position[2] 180 | 181 | # compute rotation matrix 182 | rotation = np.ones((4, 4), dtype=np.float) 183 | rotation[0, 0] = xaxis[0] 184 | rotation[0, 1] = xaxis[1] 185 | rotation[0, 2] = xaxis[2] 186 | rotation[1, 0] = yaxis[0] 187 | rotation[1, 1] = yaxis[1] 188 | rotation[1, 2] = yaxis[2] 189 | rotation[2, 0] = zaxis[0] 190 | rotation[2, 1] = zaxis[1] 191 | rotation[2, 2] = zaxis[2] 192 | 193 | return np.dot(translation, rotation) 194 | 195 | 196 | def computeLookAtMatrixQt(position: np.ndarray, 197 | target: np.ndarray, 198 | up: np.ndarray): 199 | "look at matrice" 200 | eye = QVector3D(position[0], 201 | position[1], 202 | position[2]) 203 | target = QVector3D(target[0], 204 | target[1], 205 | target[2]) 206 | upvec = QVector3D(up[0], 207 | up[1], 208 | up[2]) 209 | mat4 = QMatrix4x4() 210 | return mat4.lookAt(eye, target, upvec) 211 | 212 | 213 | def arr2vec(arr: np.ndarray): 214 | "convert array 2 vector" 215 | sqarr = np.squeeze(arr) 216 | assert sqarr.size == 4 217 | return QVector4D(sqarr[0], 218 | sqarr[1], 219 | sqarr[2], 220 | sqarr[3]) 221 | 222 | 223 | def arr2qmat(arr: np.ndarray): 224 | "array to matrix 4x4" 225 | assert arr.shape == (4, 4) 226 | mat4 = QMatrix4x4() 227 | for rowNb in range(arr.shape[0]): 228 | rowarr = arr[rowNb, :] 229 | rowvec = arr2vec(rowarr) 230 | mat4.setRow(rowNb, rowvec) 231 | # 232 | return mat4 233 | -------------------------------------------------------------------------------- /tutorials/01-triangle/gltriangle.py: -------------------------------------------------------------------------------- 1 | # Author: Kaan Eraslan 2 | 3 | import numpy as np 4 | import os 5 | import sys 6 | import ctypes 7 | 8 | from PySide2.QtGui import QOpenGLVertexArrayObject 9 | from PySide2.QtGui import QOpenGLBuffer 10 | from PySide2.QtGui import QOpenGLShaderProgram 11 | from PySide2.QtGui import QOpenGLShader 12 | from PySide2.QtGui import QOpenGLContext 13 | from PySide2.QtGui import QVector4D 14 | 15 | from PySide2.QtWidgets import QApplication 16 | from PySide2.QtWidgets import QMessageBox 17 | from PySide2.QtWidgets import QOpenGLWidget 18 | 19 | from PySide2.QtCore import QCoreApplication 20 | 21 | from PySide2.shiboken2 import VoidPtr 22 | 23 | try: 24 | from OpenGL import GL as pygl 25 | except ImportError: 26 | app = QApplication(sys.argv) 27 | messageBox = QMessageBox(QMessageBox.Critical, "OpenGL hellogl", 28 | "PyOpenGL must be installed to run this example.", 29 | QMessageBox.Close) 30 | messageBox.setDetailedText( 31 | "Run:\npip install PyOpenGL PyOpenGL_accelerate") 32 | messageBox.exec_() 33 | sys.exit(1) 34 | 35 | 36 | class TriangleGL(QOpenGLWidget): 37 | def __init__(self, parent=None): 38 | QOpenGLWidget.__init__(self, parent) 39 | 40 | # shaders etc 41 | triangleTutoDir = os.path.dirname(__file__) 42 | trianglePardir = os.path.join(triangleTutoDir, os.pardir) 43 | trianglePardir = os.path.realpath(trianglePardir) 44 | mediaDir = os.path.join(trianglePardir, "media") 45 | shaderDir = os.path.join(mediaDir, "shaders") 46 | print(shaderDir) 47 | availableShaders = ["triangle"] 48 | self.shaders = { 49 | name: { 50 | "fragment": os.path.join(shaderDir, name + ".frag"), 51 | "vertex": os.path.join(shaderDir, name + ".vert") 52 | } for name in availableShaders 53 | } 54 | self.core = "--coreprofile" in QCoreApplication.arguments() 55 | 56 | # opengl data related 57 | self.context = QOpenGLContext() 58 | self.vao = QOpenGLVertexArrayObject() 59 | self.vbo = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer) 60 | self.program = QOpenGLShaderProgram() 61 | 62 | # some vertex data for corners of triangle 63 | self.vertexData = np.array( 64 | [-0.5, -0.5, 0.0, # x, y, z 65 | 0.5, -0.5, 0.0, # x, y, z 66 | 0.0, 0.5, 0.0], # x, y, z 67 | dtype=ctypes.c_float 68 | ) 69 | # triangle color 70 | self.triangleColor = QVector4D(0.5, 0.5, 0.0, 0.0) # yellow triangle 71 | # notice the correspondance the vec4 of fragment shader 72 | # and our choice here 73 | 74 | def loadShader(self, 75 | shaderName: str, 76 | shaderType: str): 77 | "Load shader" 78 | shader = self.shaders[shaderName] 79 | shaderSourcePath = shader[shaderType] 80 | if shaderType == "vertex": 81 | shader = QOpenGLShader(QOpenGLShader.Vertex) 82 | else: 83 | shader = QOpenGLShader(QOpenGLShader.Fragment) 84 | # 85 | isCompiled = shader.compileSourceFile(shaderSourcePath) 86 | 87 | if isCompiled is False: 88 | print(shader.log()) 89 | raise ValueError( 90 | "{0} shader {2} known as {1} is not compiled".format( 91 | shaderType, shaderName, shaderSourcePath 92 | ) 93 | ) 94 | return shader 95 | 96 | def loadVertexShader(self, shaderName: str): 97 | "load vertex shader" 98 | return self.loadShader(shaderName, "vertex") 99 | 100 | def loadFragmentShader(self, shaderName: str): 101 | "load fragment shader" 102 | return self.loadShader(shaderName, "fragment") 103 | 104 | def getGlInfo(self): 105 | "Get opengl info" 106 | info = """ 107 | Vendor: {0} 108 | Renderer: {1} 109 | OpenGL Version: {2} 110 | Shader Version: {3} 111 | """.format( 112 | pygl.glGetString(pygl.GL_VENDOR), 113 | pygl.glGetString(pygl.GL_RENDERER), 114 | pygl.glGetString(pygl.GL_VERSION), 115 | pygl.glGetString(pygl.GL_SHADING_LANGUAGE_VERSION) 116 | ) 117 | return info 118 | 119 | def initializeGL(self): 120 | print('gl initial') 121 | print(self.getGlInfo()) 122 | # create context and make it current 123 | self.context.create() 124 | self.context.aboutToBeDestroyed.connect(self.cleanUpGl) 125 | 126 | # initialize functions 127 | funcs = self.context.functions() 128 | funcs.initializeOpenGLFunctions() 129 | funcs.glClearColor(1, 1, 1, 1) 130 | 131 | # deal with shaders 132 | shaderName = "triangle" 133 | vshader = self.loadVertexShader(shaderName) 134 | fshader = self.loadFragmentShader(shaderName) 135 | 136 | # creating shader program 137 | self.program = QOpenGLShaderProgram(self.context) 138 | self.program.addShader(vshader) # adding vertex shader 139 | self.program.addShader(fshader) # adding fragment shader 140 | 141 | # bind attribute to a location 142 | self.program.bindAttributeLocation("aPos", 0) 143 | 144 | # link shader program 145 | isLinked = self.program.link() 146 | print("shader program is linked: ", isLinked) 147 | 148 | # bind the program 149 | self.program.bind() 150 | 151 | # specify uniform value 152 | colorLoc = self.program.uniformLocation("color") 153 | self.program.setUniformValue(colorLoc, 154 | self.triangleColor) 155 | 156 | # self.useShader("triangle") 157 | 158 | # deal with vao and vbo 159 | 160 | # create vao and vbo 161 | 162 | # vao 163 | isVao = self.vao.create() 164 | vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao) 165 | 166 | # vbo 167 | isVbo = self.vbo.create() 168 | isBound = self.vbo.bind() 169 | 170 | # check if vao and vbo are created 171 | print('vao created: ', isVao) 172 | print('vbo created: ', isVbo) 173 | 174 | floatSize = ctypes.sizeof(ctypes.c_float) 175 | 176 | # allocate space on buffer 177 | self.vbo.allocate(self.vertexData.tobytes(), 178 | floatSize * self.vertexData.size) 179 | funcs.glEnableVertexAttribArray(0) 180 | nullptr = VoidPtr(0) 181 | funcs.glVertexAttribPointer(0, 182 | 3, 183 | int(pygl.GL_FLOAT), 184 | int(pygl.GL_FALSE), 185 | 3 * floatSize, 186 | nullptr) 187 | self.vbo.release() 188 | self.program.release() 189 | vaoBinder = None 190 | 191 | def cleanUpGl(self): 192 | "Clean up everything" 193 | self.context.makeCurrent() 194 | self.vbo.destroy() 195 | del self.program 196 | self.program = None 197 | self.doneCurrent() 198 | 199 | def resizeGL(self, width: int, height: int): 200 | "Resize the viewport" 201 | funcs = self.context.functions() 202 | funcs.glViewport(0, 0, width, height) 203 | 204 | def paintGL(self): 205 | "drawing loop" 206 | funcs = self.context.functions() 207 | 208 | # clean up what was drawn 209 | funcs.glClear(pygl.GL_COLOR_BUFFER_BIT) 210 | 211 | # actual drawing 212 | vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao) 213 | self.program.bind() 214 | funcs.glDrawArrays(pygl.GL_TRIANGLES, # mode 215 | 0, # first 216 | 3) # count 217 | self.program.release() 218 | vaoBinder = None 219 | -------------------------------------------------------------------------------- /tutorials/02-rectangle/glrectangle.py: -------------------------------------------------------------------------------- 1 | # author: Kaan Eraslan 2 | 3 | import numpy as np 4 | import os 5 | import sys 6 | import ctypes 7 | 8 | from PySide2.QtGui import QOpenGLVertexArrayObject 9 | from PySide2.QtGui import QOpenGLBuffer 10 | from PySide2.QtGui import QOpenGLShaderProgram 11 | from PySide2.QtGui import QOpenGLShader 12 | from PySide2.QtGui import QOpenGLContext 13 | from PySide2.QtGui import QVector4D 14 | 15 | from PySide2.QtWidgets import QApplication 16 | from PySide2.QtWidgets import QMessageBox 17 | from PySide2.QtWidgets import QOpenGLWidget 18 | 19 | from PySide2.QtCore import QCoreApplication 20 | 21 | from PySide2.shiboken2 import VoidPtr 22 | 23 | 24 | try: 25 | from OpenGL import GL as pygl 26 | except ImportError: 27 | app = QApplication(sys.argv) 28 | messageBox = QMessageBox(QMessageBox.Critical, "OpenGL hellogl", 29 | "PyOpenGL must be installed to run this example.", 30 | QMessageBox.Close) 31 | messageBox.setDetailedText( 32 | "Run:\npip install PyOpenGL PyOpenGL_accelerate") 33 | messageBox.exec_() 34 | sys.exit(1) 35 | 36 | 37 | class RectangleGL(QOpenGLWidget): 38 | "Texture loading opengl widget" 39 | 40 | def __init__(self, parent=None): 41 | "Constructor" 42 | QOpenGLWidget.__init__(self, parent) 43 | tutoTutoDir = os.path.dirname(__file__) 44 | tutoPardir = os.path.join(tutoTutoDir, os.pardir) 45 | tutoPardir = os.path.realpath(tutoPardir) 46 | mediaDir = os.path.join(tutoPardir, "media") 47 | shaderDir = os.path.join(mediaDir, "shaders") 48 | # 49 | availableShaders = ["rectangle", "triangle"] 50 | self.shaders = { 51 | name: { 52 | "fragment": os.path.join(shaderDir, name + ".frag"), 53 | "vertex": os.path.join(shaderDir, name + ".vert") 54 | } for name in availableShaders 55 | } 56 | self.core = "--coreprofile" in QCoreApplication.arguments() 57 | 58 | # opengl data related 59 | self.context = QOpenGLContext() 60 | self.program = QOpenGLShaderProgram() 61 | self.vao = QOpenGLVertexArrayObject() 62 | self.vbo = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer) 63 | self.indices = np.array([ 64 | 0, 1, 3, # first triangle 65 | 1, 2, 3 # second triangle 66 | ], dtype=ctypes.c_uint) 67 | 68 | # vertex data of the panel that would hold the image 69 | self.vertexData = np.array([ 70 | # viewport position || colors || texture coords 71 | 0.5, 0.5, 0.0, # top right 72 | 0.5, -0.5, 0.0, # bottom right 73 | -0.5, -0.5, 0.0, # bottom left 74 | -0.5, 0.5, 0.0, # top left 75 | ], dtype=ctypes.c_float) 76 | 77 | self.rectColor = QVector4D(0.0, 1.0, 1.0, 0.0) 78 | 79 | def loadShader(self, 80 | shaderName: str, 81 | shaderType: str): 82 | "Load shader" 83 | shader = self.shaders[shaderName] 84 | shaderSourcePath = shader[shaderType] 85 | if shaderType == "vertex": 86 | shader = QOpenGLShader(QOpenGLShader.Vertex) 87 | else: 88 | shader = QOpenGLShader(QOpenGLShader.Fragment) 89 | # 90 | isCompiled = shader.compileSourceFile(shaderSourcePath) 91 | 92 | if isCompiled is False: 93 | print(shader.log()) 94 | raise ValueError( 95 | "{0} shader {2} known as {1} is not compiled".format( 96 | shaderType, shaderName, shaderSourcePath 97 | ) 98 | ) 99 | return shader 100 | 101 | def loadVertexShader(self, shaderName: str): 102 | "load vertex shader" 103 | return self.loadShader(shaderName, "vertex") 104 | 105 | def loadFragmentShader(self, shaderName: str): 106 | "load fragment shader" 107 | return self.loadShader(shaderName, "fragment") 108 | 109 | def getGlInfo(self): 110 | "Get opengl info" 111 | info = """ 112 | Vendor: {0} 113 | Renderer: {1} 114 | OpenGL Version: {2} 115 | Shader Version: {3} 116 | """.format( 117 | pygl.glGetString(pygl.GL_VENDOR), 118 | pygl.glGetString(pygl.GL_RENDERER), 119 | pygl.glGetString(pygl.GL_VERSION), 120 | pygl.glGetString(pygl.GL_SHADING_LANGUAGE_VERSION) 121 | ) 122 | return info 123 | 124 | def cleanUpGl(self): 125 | "Clean up everything" 126 | self.context.makeCurrent() 127 | del self.program 128 | self.program = None 129 | self.vbo.release() 130 | self.doneCurrent() 131 | 132 | def resizeGL(self, width: int, height: int): 133 | "Resize the viewport" 134 | funcs = self.context.functions() 135 | funcs.glViewport(0, 0, width, height) 136 | 137 | def initializeGL(self): 138 | "Initialize opengl " 139 | print('gl initial') 140 | print(self.getGlInfo()) 141 | # create context and make it current 142 | self.context.create() 143 | self.context.aboutToBeDestroyed.connect(self.cleanUpGl) 144 | 145 | # initialize functions 146 | funcs = self.context.functions() 147 | funcs.initializeOpenGLFunctions() 148 | funcs.glClearColor(1, 1, 1, 1) 149 | 150 | # shader 151 | shaderName = "triangle" 152 | vshader = self.loadVertexShader(shaderName) 153 | fshader = self.loadFragmentShader(shaderName) 154 | 155 | # create shader program 156 | self.program = QOpenGLShaderProgram(self.context) 157 | self.program.addShader(vshader) 158 | self.program.addShader(fshader) 159 | 160 | # bind attribute location 161 | self.program.bindAttributeLocation("aPos", 0) 162 | 163 | # link shader program 164 | isLinked = self.program.link() 165 | print("shader program is linked: ", isLinked) 166 | 167 | # activate shader program to set uniform an attribute values 168 | self.program.bind() 169 | 170 | # specify uniform value 171 | colorLoc = self.program.uniformLocation("color") 172 | self.program.setUniformValue(colorLoc, 173 | self.rectColor) 174 | 175 | 176 | # vao, vbo, texture 177 | # vao 178 | isVao = self.vao.create() 179 | vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao) 180 | 181 | # vbo 182 | isVbo = self.vbo.create() 183 | isVboBound = self.vbo.bind() 184 | 185 | floatSize = ctypes.sizeof(ctypes.c_float) 186 | 187 | # allocate vbo 188 | self.vbo.allocate(self.vertexData.tobytes(), 189 | floatSize * self.vertexData.size) 190 | 191 | print("vao created: ", isVao) 192 | print("vbo created: ", isVbo) 193 | print("vbo bound: ", isVboBound) 194 | 195 | # dealing with attributes 196 | # vertex array position 197 | funcs.glVertexAttribPointer(0, 198 | 3, 199 | int(pygl.GL_FLOAT), 200 | int(pygl.GL_FALSE), 201 | 3 * floatSize, 202 | VoidPtr(0)) 203 | funcs.glEnableVertexAttribArray(0) 204 | 205 | self.vbo.release() 206 | vaoBinder = None 207 | 208 | def paintGL(self): 209 | "paint gl" 210 | funcs = self.context.functions() 211 | # clean up what was drawn 212 | funcs.glClear(pygl.GL_COLOR_BUFFER_BIT) 213 | 214 | # bind texture 215 | vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao) 216 | self.program.bind() 217 | 218 | # draw stuff 219 | funcs.glDrawElements( 220 | pygl.GL_TRIANGLES, 221 | self.indices.size, 222 | pygl.GL_UNSIGNED_INT, 223 | self.indices.tobytes()) 224 | # VoidPtr(self.indices.tobytes() * ctypes.sizeof(ctypes.c_uint))) 225 | vaoBinder = None 226 | self.program.release() 227 | -------------------------------------------------------------------------------- /tutorials/04-texture/gltexture.py: -------------------------------------------------------------------------------- 1 | # author: Kaan Eraslan 2 | 3 | import numpy as np 4 | from PIL import Image 5 | import os 6 | import sys 7 | import ctypes 8 | 9 | from PySide2.QtGui import QImage 10 | from PySide2.QtGui import QOpenGLVertexArrayObject 11 | from PySide2.QtGui import QOpenGLBuffer 12 | from PySide2.QtGui import QOpenGLShaderProgram 13 | from PySide2.QtGui import QOpenGLShader 14 | from PySide2.QtGui import QOpenGLTexture 15 | from PySide2.QtGui import QOpenGLContext 16 | 17 | from PySide2.QtWidgets import QApplication 18 | from PySide2.QtWidgets import QMessageBox 19 | from PySide2.QtWidgets import QOpenGLWidget 20 | 21 | from PySide2.QtCore import QCoreApplication 22 | from PySide2.QtCore import Qt 23 | 24 | from PySide2.shiboken2 import VoidPtr 25 | 26 | 27 | try: 28 | from OpenGL import GL as pygl 29 | except ImportError: 30 | app = QApplication(sys.argv) 31 | messageBox = QMessageBox(QMessageBox.Critical, "OpenGL hellogl", 32 | "PyOpenGL must be installed to run this example.", 33 | QMessageBox.Close) 34 | messageBox.setDetailedText( 35 | "Run:\npip install PyOpenGL PyOpenGL_accelerate") 36 | messageBox.exec_() 37 | sys.exit(1) 38 | 39 | 40 | class TextureGL(QOpenGLWidget): 41 | "Texture loading opengl widget" 42 | 43 | def __init__(self, parent=None): 44 | "Constructor" 45 | QOpenGLWidget.__init__(self, parent) 46 | tutoTutoDir = os.path.dirname(__file__) 47 | tutoPardir = os.path.join(tutoTutoDir, os.pardir) 48 | tutoPardir = os.path.realpath(tutoPardir) 49 | mediaDir = os.path.join(tutoPardir, "media") 50 | shaderDir = os.path.join(mediaDir, "shaders") 51 | # 52 | availableShaders = ["texture"] 53 | self.shaders = { 54 | name: { 55 | "fragment": os.path.join(shaderDir, name + ".frag"), 56 | "vertex": os.path.join(shaderDir, name + ".vert") 57 | } for name in availableShaders 58 | } 59 | imdir = os.path.join(mediaDir, "images") 60 | imFName = "im" 61 | imageFile = os.path.join(imdir, imFName + "0.png") 62 | self.image = QImage(imageFile).mirrored() 63 | self.core = "--coreprofile" in QCoreApplication.arguments() 64 | 65 | # opengl data related 66 | self.context = QOpenGLContext() 67 | self.program = QOpenGLShaderProgram() 68 | self.vao = QOpenGLVertexArrayObject() 69 | self.vbo = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer) 70 | self.texture = None 71 | self.indices = np.array([ 72 | 0, 1, 3, # first triangle 73 | 1, 2, 3 # second triangle 74 | ], dtype=ctypes.c_uint) 75 | 76 | # vertex data of the panel that would hold the image 77 | self.vertexData = np.array([ 78 | # viewport position || texture coords 79 | 0.5, 0.5, 0.0, 1.0, 1.0, # top right 80 | 0.5, -0.5, 0.0, 1.0, 0.0, # bottom right 81 | -0.5, -0.5, 0.0, 0.0, 0.0, # bottom left 82 | -0.5, 0.5, 0.0, 0.0, 1.0 # top left 83 | ], dtype=ctypes.c_float) 84 | 85 | def loadShader(self, 86 | shaderName: str, 87 | shaderType: str): 88 | "Load shader" 89 | shader = self.shaders[shaderName] 90 | shaderSourcePath = shader[shaderType] 91 | if shaderType == "vertex": 92 | shader = QOpenGLShader(QOpenGLShader.Vertex) 93 | else: 94 | shader = QOpenGLShader(QOpenGLShader.Fragment) 95 | # 96 | isCompiled = shader.compileSourceFile(shaderSourcePath) 97 | 98 | if isCompiled is False: 99 | print(shader.log()) 100 | raise ValueError( 101 | "{0} shader {2} known as {1} is not compiled".format( 102 | shaderType, shaderName, shaderSourcePath 103 | ) 104 | ) 105 | return shader 106 | 107 | def loadVertexShader(self, shaderName: str): 108 | "load vertex shader" 109 | return self.loadShader(shaderName, "vertex") 110 | 111 | def loadFragmentShader(self, shaderName: str): 112 | "load fragment shader" 113 | return self.loadShader(shaderName, "fragment") 114 | 115 | def getGlInfo(self): 116 | "Get opengl info" 117 | info = """ 118 | Vendor: {0} 119 | Renderer: {1} 120 | OpenGL Version: {2} 121 | Shader Version: {3} 122 | """.format( 123 | pygl.glGetString(pygl.GL_VENDOR), 124 | pygl.glGetString(pygl.GL_RENDERER), 125 | pygl.glGetString(pygl.GL_VERSION), 126 | pygl.glGetString(pygl.GL_SHADING_LANGUAGE_VERSION) 127 | ) 128 | return info 129 | 130 | def cleanUpGl(self): 131 | "Clean up everything" 132 | self.context.makeCurrent() 133 | del self.program 134 | self.program = None 135 | self.texture.release() 136 | self.doneCurrent() 137 | 138 | def resizeGL(self, width: int, height: int): 139 | "Resize the viewport" 140 | funcs = self.context.functions() 141 | funcs.glViewport(0, 0, width, height) 142 | 143 | def initializeGL(self): 144 | "Initialize opengl " 145 | print('gl initial') 146 | print(self.getGlInfo()) 147 | # create context and make it current 148 | self.context.create() 149 | self.context.aboutToBeDestroyed.connect(self.cleanUpGl) 150 | 151 | # initialize functions 152 | funcs = self.context.functions() 153 | funcs.initializeOpenGLFunctions() 154 | funcs.glClearColor(1, 0, 1, 1) 155 | 156 | # shader 157 | shaderName = "texture" 158 | vshader = self.loadVertexShader(shaderName) 159 | fshader = self.loadFragmentShader(shaderName) 160 | 161 | # create shader program 162 | self.program = QOpenGLShaderProgram(self.context) 163 | self.program.addShader(vshader) 164 | self.program.addShader(fshader) 165 | 166 | # bind attribute location 167 | self.program.bindAttributeLocation("aPos", 0) 168 | self.program.bindAttributeLocation("aTexCoord", 1) 169 | 170 | # link shader program 171 | isLinked = self.program.link() 172 | print("shader program is linked: ", isLinked) 173 | 174 | # activate shader program to set uniform an attribute values 175 | self.program.bind() 176 | self.program.setUniformValue('myTexture', 0) 177 | 178 | # vbo 179 | isVbo = self.vbo.create() 180 | isVboBound = self.vbo.bind() 181 | 182 | floatSize = ctypes.sizeof(ctypes.c_float) 183 | 184 | # allocate vbo 185 | self.vbo.allocate(self.vertexData.tobytes(), 186 | floatSize * self.vertexData.size) 187 | 188 | # texture new school 189 | self.texture = QOpenGLTexture(QOpenGLTexture.Target2D) 190 | self.texture.create() 191 | # new school 192 | self.texture.bind() 193 | self.texture.setData(self.image) 194 | self.texture.setMinMagFilters(QOpenGLTexture.Linear, 195 | QOpenGLTexture.Linear) 196 | self.texture.setWrapMode(QOpenGLTexture.DirectionS, 197 | QOpenGLTexture.Repeat) 198 | self.texture.setWrapMode(QOpenGLTexture.DirectionT, 199 | QOpenGLTexture.Repeat) 200 | 201 | def paintGL(self): 202 | "paint gl" 203 | funcs = self.context.functions() 204 | # clean up what was drawn 205 | funcs.glClear(pygl.GL_COLOR_BUFFER_BIT) 206 | 207 | self.program.bind() 208 | self.program.enableAttributeArray(0) 209 | self.program.enableAttributeArray(1) 210 | floatSize = ctypes.sizeof(ctypes.c_float) 211 | 212 | # set attribute values 213 | self.program.setAttributeBuffer(0, # viewport position 214 | pygl.GL_FLOAT, # coord type 215 | 0, # offset 216 | 3, 217 | 5 * floatSize 218 | ) 219 | self.program.setAttributeBuffer(1, # viewport position 220 | pygl.GL_FLOAT, # coord type 221 | 3 * floatSize, # offset 222 | 2, 223 | 5 * floatSize 224 | ) 225 | # bind texture 226 | self.texture.bind() 227 | funcs.glDrawElements(pygl.GL_TRIANGLES, 228 | self.indices.size, pygl.GL_UNSIGNED_INT, 229 | self.indices.tobytes()) 230 | # funcs.glDrawArrays(pygl.GL_TRIANGLES, 0, 6) 231 | -------------------------------------------------------------------------------- /tutorials/03-VaoVbo/glshader.py: -------------------------------------------------------------------------------- 1 | # Author: Kaan Eraslan 2 | 3 | import numpy as np 4 | import os 5 | import sys 6 | import ctypes 7 | 8 | from PySide2.QtGui import QOpenGLVertexArrayObject 9 | from PySide2.QtGui import QOpenGLBuffer 10 | from PySide2.QtGui import QOpenGLShaderProgram 11 | from PySide2.QtGui import QOpenGLShader 12 | from PySide2.QtGui import QOpenGLContext 13 | from PySide2.QtGui import QVector4D 14 | 15 | from PySide2.QtWidgets import QApplication 16 | from PySide2.QtWidgets import QMessageBox 17 | from PySide2.QtWidgets import QOpenGLWidget 18 | 19 | from PySide2.QtCore import QCoreApplication 20 | 21 | from PySide2.shiboken2 import VoidPtr 22 | 23 | try: 24 | from OpenGL import GL as pygl 25 | except ImportError: 26 | app = QApplication(sys.argv) 27 | messageBox = QMessageBox(QMessageBox.Critical, "OpenGL hellogl", 28 | "PyOpenGL must be installed to run this example.", 29 | QMessageBox.Close) 30 | messageBox.setDetailedText( 31 | "Run:\npip install PyOpenGL PyOpenGL_accelerate") 32 | messageBox.exec_() 33 | sys.exit(1) 34 | 35 | 36 | class TriangleGL(QOpenGLWidget): 37 | def __init__(self, parent=None): 38 | QOpenGLWidget.__init__(self, parent) 39 | 40 | # shaders etc 41 | triangleTutoDir = os.path.dirname(__file__) 42 | trianglePardir = os.path.join(triangleTutoDir, os.pardir) 43 | mediaDir = os.path.join(trianglePardir, "media") 44 | shaderDir = os.path.join(mediaDir, "shaders") 45 | availableShaders = ["triangle", "triangle2"] 46 | self.shaders = { 47 | name: { 48 | "fragment": os.path.join(shaderDir, name + ".frag"), 49 | "vertex": os.path.join(shaderDir, name + ".vert") 50 | } for name in availableShaders 51 | } 52 | self.core = "--coreprofile" in QCoreApplication.arguments() 53 | 54 | # opengl data related 55 | self.context = QOpenGLContext() 56 | self.vao1 = QOpenGLVertexArrayObject() 57 | self.vbo1 = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer) 58 | self.vao2 = QOpenGLVertexArrayObject() 59 | self.vbo2 = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer) 60 | 61 | self.program1 = QOpenGLShaderProgram() 62 | self.program2 = QOpenGLShaderProgram() 63 | 64 | # some vertex data for corners of triangle 65 | self.vertexData1 = np.array( 66 | [0.9, 0.9, 0.0, # x, y, z 67 | 0.9, 0.7, 0.0, # x, y, z 68 | 0.7, 0.9, 0.0], # x, y, z 69 | dtype=ctypes.c_float 70 | ) 71 | self.vertexData2 = np.array( 72 | [-0.9, -0.9, 0.0, # x, y, z 73 | -0.9, -0.7, 0.0, # x, y, z 74 | -0.7, -0.9, 0.0], # x, y, z 75 | dtype=ctypes.c_float 76 | ) 77 | # triangle color 78 | self.triangleColor1 = QVector4D(1.0, 0.0, 0.0, 0.0) # yellow triangle 79 | self.triangleColor2 = QVector4D( 80 | 0.0, 0.0, 0.5, 0.0) # not yellow triangle 81 | 82 | def loadShader(self, 83 | shaderName: str, 84 | shaderType: str): 85 | "Load shader" 86 | shader = self.shaders[shaderName] 87 | shaderSourcePath = shader[shaderType] 88 | if shaderType == "vertex": 89 | shader = QOpenGLShader(QOpenGLShader.Vertex) 90 | else: 91 | shader = QOpenGLShader(QOpenGLShader.Fragment) 92 | # 93 | isCompiled = shader.compileSourceFile(shaderSourcePath) 94 | 95 | if isCompiled is False: 96 | print(shader.log()) 97 | raise ValueError( 98 | "{0} shader {2} known as {1} is not compiled".format( 99 | shaderType, shaderName, shaderSourcePath 100 | ) 101 | ) 102 | return shader 103 | 104 | def loadVertexShader(self, shaderName: str): 105 | "load vertex shader" 106 | return self.loadShader(shaderName, "vertex") 107 | 108 | def loadFragmentShader(self, shaderName: str): 109 | "load fragment shader" 110 | return self.loadShader(shaderName, "fragment") 111 | 112 | def getGlInfo(self): 113 | "Get opengl info" 114 | info = """ 115 | Vendor: {0} 116 | Renderer: {1} 117 | OpenGL Version: {2} 118 | Shader Version: {3} 119 | """.format( 120 | pygl.glGetString(pygl.GL_VENDOR), 121 | pygl.glGetString(pygl.GL_RENDERER), 122 | pygl.glGetString(pygl.GL_VERSION), 123 | pygl.glGetString(pygl.GL_SHADING_LANGUAGE_VERSION) 124 | ) 125 | return info 126 | 127 | def initializeGL(self): 128 | print('gl initial') 129 | print(self.getGlInfo()) 130 | # create context and make it current 131 | self.context.create() 132 | self.context.aboutToBeDestroyed.connect(self.cleanUpGl) 133 | 134 | # initialize functions 135 | funcs = self.context.functions() 136 | funcs.initializeOpenGLFunctions() 137 | funcs.glClearColor(1, 1, 1, 1) 138 | 139 | # deal with shaders 140 | # first shader 141 | shaderName = "triangle" 142 | vshader = self.loadVertexShader(shaderName) 143 | fshader = self.loadFragmentShader(shaderName) 144 | 145 | # creating shader program 146 | self.program1 = QOpenGLShaderProgram(self.context) 147 | self.program1.addShader(vshader) # adding vertex shader 148 | self.program1.addShader(fshader) # adding fragment shader 149 | 150 | # bind attribute to a location 151 | self.program1.bindAttributeLocation("aPos", 0) 152 | 153 | # link shader program1 154 | isLinked = self.program1.link() 155 | print("shader program1 is linked: ", isLinked) 156 | 157 | # bind the program1 158 | self.program1.bind() 159 | 160 | # specify uniform value 161 | colorLoc = self.program1.uniformLocation("color") 162 | self.program1.setUniformValue(colorLoc, 163 | self.triangleColor1) 164 | 165 | # second shader 166 | shaderName = "triangle2" 167 | vshader = self.loadVertexShader(shaderName) 168 | fshader = self.loadFragmentShader(shaderName) 169 | 170 | # 171 | self.program2 = QOpenGLShaderProgram(self.context) 172 | self.program2.addShader(vshader) # adding vertex shader 173 | self.program2.addShader(fshader) # adding fragment shader 174 | 175 | # bind attribute to a location 176 | self.program2.bindAttributeLocation("aPos", 0) 177 | 178 | # link shader program2 179 | isLinked = self.program2.link() 180 | print("shader program2 is linked: ", isLinked) 181 | 182 | # bind the program2 183 | self.program2.bind() 184 | 185 | # specify uniform value 186 | colorLoc = self.program2.uniformLocation("color") 187 | self.program2.setUniformValue(colorLoc, 188 | self.triangleColor2) 189 | 190 | # self.useShader("triangle") 191 | 192 | # deal with vao and vbo 193 | 194 | # create vao and vbo 195 | 196 | # vao 197 | isVao = self.vao1.create() 198 | vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao1) 199 | 200 | # vbo 201 | isVbo = self.vbo1.create() 202 | isBound = self.vbo1.bind() 203 | 204 | # check if vao and vbo are created 205 | print('vao created: ', isVao) 206 | print('vbo created: ', isVbo) 207 | 208 | floatSize = ctypes.sizeof(ctypes.c_float) 209 | 210 | # allocate space on buffer 211 | self.vbo1.allocate(self.vertexData1.tobytes(), 212 | floatSize * self.vertexData1.size) 213 | funcs.glEnableVertexAttribArray(0) 214 | nullptr = VoidPtr(0) 215 | funcs.glVertexAttribPointer(0, 216 | 3, 217 | int(pygl.GL_FLOAT), 218 | int(pygl.GL_FALSE), 219 | 3 * floatSize, 220 | nullptr) 221 | self.vbo1.release() 222 | vaoBinder = None 223 | 224 | # second triangle vao vbo 225 | # vao 226 | isVao = self.vao2.create() 227 | vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao2) 228 | 229 | # vbo 230 | isVbo = self.vbo2.create() 231 | isBound = self.vbo2.bind() 232 | 233 | # check if vao and vbo are created 234 | print('vao created: ', isVao) 235 | print('vbo created: ', isVbo) 236 | 237 | floatSize = ctypes.sizeof(ctypes.c_float) 238 | 239 | # allocate space on buffer 240 | self.vbo2.allocate(self.vertexData2.tobytes(), 241 | floatSize * self.vertexData2.size) 242 | funcs.glEnableVertexAttribArray(0) 243 | nullptr = VoidPtr(0) 244 | funcs.glVertexAttribPointer(0, 245 | 3, 246 | int(pygl.GL_FLOAT), 247 | int(pygl.GL_FALSE), 248 | 3 * floatSize, 249 | nullptr) 250 | self.vbo2.release() 251 | self.program2.release() 252 | 253 | def cleanUpGl(self): 254 | "Clean up everything" 255 | self.context.makeCurrent() 256 | self.vbo.destroy() 257 | del self.program 258 | self.program = None 259 | self.doneCurrent() 260 | 261 | def resizeGL(self, width: int, height: int): 262 | "Resize the viewport" 263 | funcs = self.context.functions() 264 | funcs.glViewport(0, 0, width, height) 265 | 266 | def paintGL(self): 267 | "drawing loop" 268 | funcs = self.context.functions() 269 | 270 | # clean up what was drawn 271 | funcs.glClear(pygl.GL_COLOR_BUFFER_BIT) 272 | 273 | # actual drawing 274 | vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao1) 275 | self.program1.bind() 276 | funcs.glDrawArrays(pygl.GL_TRIANGLES, # mode 277 | 0, # first 278 | 3) # count 279 | vaoBinder = None 280 | self.program1.release() 281 | vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao2) 282 | self.program2.bind() 283 | funcs.glDrawArrays(pygl.GL_TRIANGLES, # mode 284 | 0, # first 285 | 3) # count 286 | vaoBinder = None 287 | self.program2.release() 288 | -------------------------------------------------------------------------------- /tutorials/06-events/EventsTutorial.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Event Handling for PySide2 OpenGL Widget" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "Welcome to the event handling tutorial for the new OpenGL api of PySide2.\n", 15 | "\n", 16 | "By event handling we mean two things: \n", 17 | "\n", 18 | "- Acquiring the user input through the aid of other widgets and displaying its effect on scene.\n", 19 | "\n", 20 | "- Responding to a state of scene with respect to a condition.\n", 21 | "\n", 22 | "We are going to see an example of the first one in this tutorial. \n", 23 | "For the second one, remember that once a scene is drawn it is as good as gone, because the main use of OpenGL is rendering objects on scene not changing their state.\n", 24 | "It is possible to do computation on OpenGL of course and we shall see an example in the next tutorial while dealing with light effects, but it is better to do critical computation at the client code rather than in OpenGL.\n", 25 | "\n", 26 | "This is also evident in the `qt` api as well. \n", 27 | "Simply look at the amount of setters with respect to that of getters, if they exist at all. \n", 28 | "Qt also favors a mindset where you send stuff for rendering only.\n", 29 | "\n", 30 | "Now let's see our final application window, where we finally start to use some of the handles that we had defined from the beginning." 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": 5, 36 | "metadata": {}, 37 | "outputs": [ 38 | { 39 | "data": { 40 | "text/plain": [ 41 | "CompletedProcess(args=['python', 'app.py'], returncode=0)" 42 | ] 43 | }, 44 | "execution_count": 5, 45 | "metadata": {}, 46 | "output_type": "execute_result" 47 | } 48 | ], 49 | "source": [ 50 | "import subprocess\n", 51 | "\n", 52 | "subprocess.run([\"python\", \"app.py\"])" 53 | ] 54 | }, 55 | { 56 | "cell_type": "markdown", 57 | "metadata": {}, 58 | "source": [ 59 | "It is not very well oriented due to the absence of mouse control but it should give you an idea about how everything works together.\n", 60 | "\n", 61 | "We had also changed the content of the `app.py` to better handle the event mechanism. \n", 62 | "\n", 63 | "Let's see what's new in `app.py` " 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": null, 69 | "metadata": {}, 70 | "outputs": [], 71 | "source": [ 72 | "from PySide2 import QtWidgets\n", 73 | "from tutorials.utils.window import GLWindow as AppWindow\n", 74 | "from glevents import EventsGL\n", 75 | "import sys\n", 76 | "\n", 77 | "\n", 78 | "class EventAppWindow(AppWindow):\n", 79 | " \"Overriding base class with event methods\"\n", 80 | "\n", 81 | " def __init__(self,\n", 82 | " glwidget: QtWidgets.QOpenGLWidget,\n", 83 | " parent=None,\n", 84 | " ):\n", 85 | " super().__init__(glwidget,\n", 86 | " parent)\n", 87 | " self.camX.setRange(-180.0, 180.0)\n", 88 | " self.camY.setRange(-180.0, 180.0)\n", 89 | " self.xSlider.setRange(-180.0, 180.0)\n", 90 | " self.ySlider.setRange(-180.0, 180.0)\n", 91 | " self.zSlider.setRange(-180.0, 180.0)\n", 92 | " self.upBtn.clicked.connect(self.moveCameraForward)\n", 93 | " self.downBtn.clicked.connect(self.moveCameraBackward)\n", 94 | " self.leftBtn.clicked.connect(self.moveCameraLeft)\n", 95 | " self.rightBtn.clicked.connect(self.moveCameraRight)\n", 96 | " self.camX.valueChanged.connect(self.turnCameraX)\n", 97 | " self.camY.valueChanged.connect(self.turnCameraY)\n", 98 | " self.xSlider.valueChanged.connect(self.rotateCubes)\n", 99 | " self.ySlider.valueChanged.connect(self.rotateCubes)\n", 100 | " self.zSlider.valueChanged.connect(self.rotateCubes)\n", 101 | " #\n", 102 | " self.lastCamXVal = self.camX.value()\n", 103 | " #\n", 104 | " self.lastCamYVal = self.camY.value()\n", 105 | "\n", 106 | " def moveGLCamera(self, direction: str):\n", 107 | " self.glWidget.moveCamera(direction)\n", 108 | "\n", 109 | " def moveCameraForward(self):\n", 110 | " self.moveGLCamera(\"forward\")\n", 111 | "\n", 112 | " def moveCameraBackward(self):\n", 113 | " self.moveGLCamera(\"backward\")\n", 114 | "\n", 115 | " def moveCameraLeft(self):\n", 116 | " self.moveGLCamera(\"left\")\n", 117 | "\n", 118 | " def moveCameraRight(self):\n", 119 | " self.moveGLCamera(\"right\")\n", 120 | "\n", 121 | " def turnCameraX(self, newVal: int):\n", 122 | " \"Turn camera around\"\n", 123 | " offsetx = newVal - self.lastCamXVal\n", 124 | " valy = self.camY.value() - self.lastCamYVal\n", 125 | " self.glWidget.turnAround(x=float(offsetx),\n", 126 | " y=float(valy))\n", 127 | " self.lastCamXVal = newVal\n", 128 | "\n", 129 | " def turnCameraY(self, newVal: int):\n", 130 | " \"Turn camera around\"\n", 131 | " offsety = newVal - self.lastCamYVal\n", 132 | " valx = self.camX.value() - self.lastCamXVal\n", 133 | " self.glWidget.turnAround(x=float(valx),\n", 134 | " y=float(offsety))\n", 135 | " self.lastCamYVal = newVal\n", 136 | "\n", 137 | " def rotateCubes(self):\n", 138 | " rx = self.xSlider.value()\n", 139 | " ry = self.ySlider.value()\n", 140 | " rz = self.zSlider.value()\n", 141 | " self.glWidget.rotateCubes(rx, ry, rz)" 142 | ] 143 | }, 144 | { 145 | "cell_type": "markdown", 146 | "metadata": {}, 147 | "source": [ 148 | "As you can see, we now have another window which wires the events triggered by other widgets on the window to the glwidget.\n", 149 | "\n", 150 | "GLwidget then simply calls the related method.\n", 151 | "\n", 152 | "Let's see for example what `turnCameraY` method of the window, which is triggered by a value change in `camY` slider, basically the camera slider with `y` label on top, triggers in glwidget.\n", 153 | "\n", 154 | "It calls the `turnAround` method of glwidget with two offset values. Then `turnAround` does the following." 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": null, 160 | "metadata": {}, 161 | "outputs": [], 162 | "source": [ 163 | " def turnAround(self, x: float, y: float):\n", 164 | " \"\"\n", 165 | " self.camera.lookAround(xoffset=x,\n", 166 | " yoffset=y,\n", 167 | " pitchBound=True)\n", 168 | " self.update()\n" 169 | ] 170 | }, 171 | { 172 | "cell_type": "markdown", 173 | "metadata": {}, 174 | "source": [ 175 | "It simply passes these offset values to a camera method. \n", 176 | "You can check `lookAround` method inside `camera.py`, but it simply assigns new `pitch` and `yaw` values using these offsets then updates the vectors of the camera like front, right, up.\n", 177 | "\n", 178 | "More importantly `turnAround` calls the `update` method of the glwidget.\n", 179 | "The update method is common for qtwidgets. \n", 180 | "Here it triggers repainting the scene with new values. \n", 181 | "These values happen to modify the orientation of the camera effectively changing the field of visibility.\n", 182 | "\n", 183 | "This has the following implication on code. \n", 184 | "We need to set the data related to triggered events in the `paintGL` rather than `initializeGL`, since `update` simply recalls `paintGL` for repainting the scene, and `initializeGL` is called only once before the first use of `paintGL`.\n", 185 | "\n", 186 | "Let's see now the body of our `paintGL`" 187 | ] 188 | }, 189 | { 190 | "cell_type": "code", 191 | "execution_count": null, 192 | "metadata": {}, 193 | "outputs": [], 194 | "source": [ 195 | " def paintGL(self):\n", 196 | " \"drawing loop\"\n", 197 | " funcs = self.context.functions()\n", 198 | "\n", 199 | " # clean up what was drawn\n", 200 | " funcs.glClear(\n", 201 | " pygl.GL_COLOR_BUFFER_BIT | pygl.GL_DEPTH_BUFFER_BIT\n", 202 | " )\n", 203 | " self.vao.bind()\n", 204 | " self.vbo.bind()\n", 205 | "\n", 206 | " # actual drawing\n", 207 | " self.program.bind()\n", 208 | " ############ Diff ###############\n", 209 | " # Notice that this exactly the same code\n", 210 | " # that we had used in CubeGL widget\n", 211 | " # I simply copy pasted the same thing\n", 212 | " # to paintGL here.\n", 213 | " # set projection matrix\n", 214 | " projectionMatrix = QMatrix4x4()\n", 215 | " projectionMatrix.perspective(\n", 216 | " self.camera.zoom,\n", 217 | " self.width() / self.height(),\n", 218 | " 0.2, 100.0)\n", 219 | "\n", 220 | " self.program.setUniformValue('projection',\n", 221 | " projectionMatrix)\n", 222 | "\n", 223 | " # set view/camera matrix\n", 224 | " viewMatrix = self.camera.getViewMatrix()\n", 225 | " self.program.setUniformValue('view',\n", 226 | " viewMatrix)\n", 227 | "\n", 228 | " # bind textures\n", 229 | " for i, pos in enumerate(self.cubeCoords):\n", 230 | " #\n", 231 | " cubeModel = QMatrix4x4()\n", 232 | " cubeModel.translate(pos)\n", 233 | " angle = 30 * i\n", 234 | " cubeModel.rotate(angle, self.rotateVector)\n", 235 | " self.program.setUniformValue(\"model\",\n", 236 | " cubeModel)\n", 237 | " self.texture1.bind(0)\n", 238 | " self.texture2.bind(1)\n", 239 | " funcs.glDrawArrays(\n", 240 | " pygl.GL_TRIANGLES,\n", 241 | " 0,\n", 242 | " 36\n", 243 | " )\n", 244 | " self.vbo.release()\n", 245 | " self.program.release()\n", 246 | " self.texture1.release()\n", 247 | " self.texture2.release()" 248 | ] 249 | }, 250 | { 251 | "cell_type": "markdown", 252 | "metadata": {}, 253 | "source": [ 254 | "Congragulations, that's it!\n", 255 | "\n", 256 | "Now you know a big part of 3d rendering. \n", 257 | "Most of the stuff from now on would be more or less the same thing with fancier shaders and/or objects and/or transformations. " 258 | ] 259 | } 260 | ], 261 | "metadata": { 262 | "kernelspec": { 263 | "display_name": "Python 3", 264 | "language": "python", 265 | "name": "python3" 266 | }, 267 | "language_info": { 268 | "codemirror_mode": { 269 | "name": "ipython", 270 | "version": 3 271 | }, 272 | "file_extension": ".py", 273 | "mimetype": "text/x-python", 274 | "name": "python", 275 | "nbconvert_exporter": "python", 276 | "pygments_lexer": "ipython3", 277 | "version": "3.7.3" 278 | } 279 | }, 280 | "nbformat": 4, 281 | "nbformat_minor": 2 282 | } 283 | -------------------------------------------------------------------------------- /tutorials/04-texture/TextureTutorial.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## PySide2 OpenGL Texture Tutorial" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "Welcome to PySide2 OpenGL texture tutorial. \n", 15 | "What is a texture ?\n", 16 | "\n", 17 | "Basically a texture is something you can fill vertex area with.\n", 18 | "For the most part this would mean using images to cover up certain areas. \n", 19 | "For example, you have drawn a rectangle, you collate and picture of bricks to it and it becomes a brick wall. You collate a picture of stones to it and it becomes a stone wall. \n", 20 | "\n", 21 | "If you can use a detailed image then you can create the illusion of such a wall without having to define vertices. You can use 1D, 2D, and 3D textures in opengl. \n", 22 | "We will cover probably the most common case of using 2D textures.\n", 23 | "\n", 24 | "Now let's see the final result before we start looking at the code." 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": 16, 30 | "metadata": {}, 31 | "outputs": [ 32 | { 33 | "data": { 34 | "text/plain": [ 35 | "CompletedProcess(args=['python', 'app.py'], returncode=0)" 36 | ] 37 | }, 38 | "execution_count": 16, 39 | "metadata": {}, 40 | "output_type": "execute_result" 41 | } 42 | ], 43 | "source": [ 44 | "import subprocess\n", 45 | "\n", 46 | "subprocess.run([\"python\", \"app.py\"])" 47 | ] 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "metadata": {}, 52 | "source": [ 53 | "As usual the application window is the same as in the previous tutorials.\n", 54 | "\n", 55 | "Let's see the constructor of our gl widget." 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": null, 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [ 64 | "class TextureGL(QOpenGLWidget):\n", 65 | " \"Texture loading opengl widget\"\n", 66 | "\n", 67 | " def __init__(self, parent=None):\n", 68 | " \"Constructor\"\n", 69 | " QOpenGLWidget.__init__(self, parent)\n", 70 | " tutoTutoDir = os.path.dirname(__file__)\n", 71 | " tutoPardir = os.path.join(tutoTutoDir, os.pardir)\n", 72 | " tutoPardir = os.path.realpath(tutoPardir)\n", 73 | " mediaDir = os.path.join(tutoPardir, \"media\")\n", 74 | " shaderDir = os.path.join(mediaDir, \"shaders\")\n", 75 | " #\n", 76 | " ############## Diff #####################\n", 77 | " # please do look at the shader code of \n", 78 | " # the texture. It is a little different\n", 79 | " # than triangle shader.\n", 80 | " availableShaders = [\"texture\"]\n", 81 | " self.shaders = {\n", 82 | " name: {\n", 83 | " \"fragment\": os.path.join(shaderDir, name + \".frag\"),\n", 84 | " \"vertex\": os.path.join(shaderDir, name + \".vert\")\n", 85 | " } for name in availableShaders\n", 86 | " }\n", 87 | " ############### Diff #####################\n", 88 | " # Notice that we are simply using an image\n", 89 | " # The use of QImage is particularly important\n", 90 | " # since it facilitates a lot of things with \n", 91 | " # with respect to traditional opengl\n", 92 | " imdir = os.path.join(mediaDir, \"images\")\n", 93 | " imFName = \"im\"\n", 94 | " imageFile = os.path.join(imdir, imFName + \"0.png\")\n", 95 | " print(\"image file:\", imageFile)\n", 96 | " self.imagefile = imageFile\n", 97 | " # Notice that we are using\n", 98 | " self.image = QImage(imageFile).mirrored()\n", 99 | " self.core = \"--coreprofile\" in QCoreApplication.arguments()\n", 100 | "\n", 101 | " # opengl data related\n", 102 | " self.context = QOpenGLContext()\n", 103 | " self.program = QOpenGLShaderProgram()\n", 104 | " self.vao = QOpenGLVertexArrayObject()\n", 105 | " self.vbo = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer)\n", 106 | " \n", 107 | " ################ Diff ##############\n", 108 | " # texture is going to be defined\n", 109 | " # afterwards but it is important\n", 110 | " # to define it right now due to its\n", 111 | " # reuse in two different methods\n", 112 | " self.texture = None\n", 113 | " self.indices = np.array([\n", 114 | " 0, 1, 3, # first triangle\n", 115 | " 1, 2, 3 # second triangle\n", 116 | " ], dtype=ctypes.c_uint)\n", 117 | "\n", 118 | " # vertex data of the panel that would hold the image\n", 119 | " self.vertexData = np.array([\n", 120 | " # viewport position || texture coords\n", 121 | " 0.5, 0.5, 0.0, 1.0, 1.0, # top right\n", 122 | " 0.5, -0.5, 0.0, 1.0, 0.0, # bottom right\n", 123 | " -0.5, -0.5, 0.0, 0.0, 0.0, # bottom left\n", 124 | " -0.5, 0.5, 0.0, 0.0, 1.0 # top left\n", 125 | " ], dtype=ctypes.c_float)" 126 | ] 127 | }, 128 | { 129 | "cell_type": "markdown", 130 | "metadata": {}, 131 | "source": [ 132 | "Mainly there are two differences.\n", 133 | "We define a QImage that would be used as the content of the texture.\n", 134 | "We also define a texture object to be defined later on during the initialization.\n", 135 | "\n", 136 | "As a side note, see the texture shader in the media `texture.frag` and `texture.vert`.\n", 137 | "\n", 138 | "Let's see the code of `initializeGL`." 139 | ] 140 | }, 141 | { 142 | "cell_type": "code", 143 | "execution_count": null, 144 | "metadata": {}, 145 | "outputs": [], 146 | "source": [ 147 | " def initializeGL(self):\n", 148 | " \"Initialize opengl \"\n", 149 | " print('gl initial')\n", 150 | " print(self.getGlInfo())\n", 151 | " # create context and make it current\n", 152 | " self.context.create()\n", 153 | " self.context.aboutToBeDestroyed.connect(self.cleanUpGl)\n", 154 | "\n", 155 | " # initialize functions\n", 156 | " funcs = self.context.functions()\n", 157 | " funcs.initializeOpenGLFunctions()\n", 158 | " funcs.glClearColor(1, 0, 1, 1)\n", 159 | " \n", 160 | " # shader\n", 161 | " shaderName = \"texture\"\n", 162 | " vshader = self.loadVertexShader(shaderName)\n", 163 | " fshader = self.loadFragmentShader(shaderName)\n", 164 | "\n", 165 | " # create shader program\n", 166 | " self.program = QOpenGLShaderProgram(self.context)\n", 167 | " self.program.addShader(vshader)\n", 168 | " self.program.addShader(fshader)\n", 169 | "\n", 170 | " # bind attribute location\n", 171 | " self.program.bindAttributeLocation(\"aPos\", 0)\n", 172 | " self.program.bindAttributeLocation(\"aTexCoord\", 1)\n", 173 | "\n", 174 | " # link shader program\n", 175 | " isLinked = self.program.link()\n", 176 | " print(\"shader program is linked: \", isLinked)\n", 177 | "\n", 178 | " # activate shader program to set uniform an attribute values\n", 179 | " self.program.bind()\n", 180 | " self.program.setUniformValue('myTexture', 0)\n", 181 | "\n", 182 | " # vbo\n", 183 | " isVbo = self.vbo.create()\n", 184 | " isVboBound = self.vbo.bind()\n", 185 | "\n", 186 | " floatSize = ctypes.sizeof(ctypes.c_float)\n", 187 | "\n", 188 | " # allocate vbo\n", 189 | " self.vbo.allocate(self.vertexData.tobytes(),\n", 190 | " floatSize * self.vertexData.size)\n", 191 | "\n", 192 | " ################## Diff #######################\n", 193 | " # this how pyside handles textures to those\n", 194 | " # who are familiar to opengl it should be self \n", 195 | " # evident what it does. Notice that this is \n", 196 | " # how we initialize the texture and set \n", 197 | " # parameters to it\n", 198 | " self.texture = QOpenGLTexture(QOpenGLTexture.Target2D)\n", 199 | " self.texture.create()\n", 200 | " # new school\n", 201 | " self.texture.bind()\n", 202 | " self.texture.setData(self.image)\n", 203 | " self.texture.setMinMagFilters(QOpenGLTexture.Linear,\n", 204 | " QOpenGLTexture.Linear)\n", 205 | " self.texture.setWrapMode(QOpenGLTexture.DirectionS,\n", 206 | " QOpenGLTexture.Repeat)\n", 207 | " self.texture.setWrapMode(QOpenGLTexture.DirectionT,\n", 208 | " QOpenGLTexture.Repeat)" 209 | ] 210 | }, 211 | { 212 | "cell_type": "markdown", 213 | "metadata": {}, 214 | "source": [ 215 | "Now as you can see the main difference is how we set texture.\n", 216 | "\n", 217 | "- We provide the target in opengl. Target2D means GL_TEXTURE_2D\n", 218 | "- We set data to it AFTER binding the texture.\n", 219 | "- We set other parameters using the related set methods.\n", 220 | "\n", 221 | "Now let's see the drawing loop." 222 | ] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "execution_count": null, 227 | "metadata": {}, 228 | "outputs": [], 229 | "source": [ 230 | " def paintGL(self):\n", 231 | " \"paint gl\"\n", 232 | " funcs = self.context.functions()\n", 233 | " # clean up what was drawn\n", 234 | " funcs.glClear(pygl.GL_COLOR_BUFFER_BIT)\n", 235 | "\n", 236 | " self.program.bind()\n", 237 | " ############### Diff #################\n", 238 | " self.program.enableAttributeArray(0)\n", 239 | " self.program.enableAttributeArray(1)\n", 240 | " floatSize = ctypes.sizeof(ctypes.c_float)\n", 241 | "\n", 242 | " # set attribute values\n", 243 | " self.program.setAttributeBuffer(0, # viewport position\n", 244 | " pygl.GL_FLOAT, # coord type\n", 245 | " 0, # offset\n", 246 | " 3,\n", 247 | " 5 * floatSize\n", 248 | " )\n", 249 | " self.program.setAttributeBuffer(1, # viewport position\n", 250 | " pygl.GL_FLOAT, # coord type\n", 251 | " 3 * floatSize, # offset\n", 252 | " 2,\n", 253 | " 5 * floatSize\n", 254 | " )\n", 255 | " # bind texture\n", 256 | " self.texture.bind()\n", 257 | " funcs.glDrawElements(pygl.GL_TRIANGLES,\n", 258 | " self.indices.size, pygl.GL_UNSIGNED_INT,\n", 259 | " self.indices.tobytes())" 260 | ] 261 | }, 262 | { 263 | "cell_type": "markdown", 264 | "metadata": {}, 265 | "source": [ 266 | "By far the most different part about rendering texture is the drawing loop. The main difference is that we set values related to VAO in here rather than in `initializeGL`." 267 | ] 268 | }, 269 | { 270 | "cell_type": "markdown", 271 | "metadata": {}, 272 | "source": [ 273 | "And that's it. Now you know how to load a texture, or how to render an image in opengl. " 274 | ] 275 | } 276 | ], 277 | "metadata": { 278 | "kernelspec": { 279 | "display_name": "Python 3", 280 | "language": "python", 281 | "name": "python3" 282 | }, 283 | "language_info": { 284 | "codemirror_mode": { 285 | "name": "ipython", 286 | "version": 3 287 | }, 288 | "file_extension": ".py", 289 | "mimetype": "text/x-python", 290 | "name": "python", 291 | "nbconvert_exporter": "python", 292 | "pygments_lexer": "ipython3", 293 | "version": "3.7.3" 294 | } 295 | }, 296 | "nbformat": 4, 297 | "nbformat_minor": 2 298 | } 299 | -------------------------------------------------------------------------------- /tutorials/utils/camera.py: -------------------------------------------------------------------------------- 1 | # author: Kaan Eraslan 2 | # camera 3 | 4 | import numpy as np 5 | import math 6 | from tutorials.utils.utils import computeLookAtPure 7 | from tutorials.utils.utils import normalize_tuple 8 | from tutorials.utils.utils import crossProduct 9 | from tutorials.utils.utils import scalar2vecMult 10 | from tutorials.utils.utils import vec2vecAdd 11 | from tutorials.utils.utils import vec2vecSubs 12 | from PySide2.QtGui import QVector3D 13 | from PySide2.QtGui import QMatrix4x4 14 | from PySide2.QtGui import QVector4D 15 | 16 | 17 | class PureCamera: 18 | "A camera that is in pure python for 3d movement" 19 | 20 | def __init__(self): 21 | self.availableMoves = ["forward", "backward", "left", "right"] 22 | # Camera attributes 23 | self.position = (0.0, 0.0, 0.0) 24 | self.front = (0.0, 0.0, -1.0) 25 | self.up = (0.0, 1.0, 0.0) 26 | self.right = (0.0, 0.0, 0.0) 27 | self.worldUp = (0.0, 0.0, 0.0) 28 | 29 | # Euler Angles for rotation 30 | self.yaw = -90.0 31 | self.pitch = 0.0 32 | 33 | # camera options 34 | self.movementSpeed = 2.5 35 | self.movementSensitivity = 0.00001 36 | self.zoom = 45.0 37 | 38 | def updateCameraVectors(self): 39 | "Update the camera vectors and compute a new front" 40 | yawRadian = math.radians(self.yaw) 41 | yawCos = math.cos(yawRadian) 42 | pitchRadian = math.radians(self.pitch) 43 | pitchCos = math.cos(pitchRadian) 44 | frontX = yawCos * pitchCos 45 | frontY = math.sin(pitchRadian) 46 | frontZ = math.sin(yawRadian) * pitchCos 47 | self.front = (frontX, frontY, frontZ) 48 | self.front = normalize_tuple(self.front) 49 | self.right = crossProduct( 50 | self.front, 51 | self.worldUp) 52 | self.right = normalize_tuple(self.right) 53 | self.up = crossProduct( 54 | self.right, 55 | self.front) 56 | self.up = normalize_tuple(self.up) 57 | 58 | def move(self, direction: str, deltaTime: float): 59 | "" 60 | velocity = self.movementSpeed * deltaTime 61 | direction = direction.lower() 62 | if direction not in self.availableMoves: 63 | raise ValueError( 64 | "Unknown direction {0}, available moves are {1}".format( 65 | direction, self.availableMoves 66 | ) 67 | ) 68 | if direction == "forward": 69 | multip = scalar2vecMult(self.front, 70 | velocity) 71 | self.position = vec2vecAdd(self.position, 72 | multip) 73 | elif direction == "backward": 74 | multip = scalar2vecMult(self.front, 75 | velocity) 76 | self.position = vec2vecSubs(self.position, 77 | multip) 78 | elif direction == "right": 79 | multip = scalar2vecMult(self.right, 80 | velocity) 81 | self.position = vec2vecAdd(self.position, 82 | multip) 83 | elif direction == "left": 84 | multip = scalar2vecMult(self.right, 85 | velocity) 86 | self.position = vec2vecSubs(self.position, 87 | multip) 88 | 89 | def lookAround(self, 90 | xoffset: float, 91 | yoffset: float, 92 | pitchBound: bool): 93 | "Look around with camera" 94 | xoffset *= self.movementSensitivity 95 | yoffset *= self.movementSensitivity 96 | self.yaw += xoffset 97 | self.pitch += yoffset 98 | 99 | if pitchBound: 100 | if self.pitch > 90.0: 101 | self.pitch = 90.0 102 | elif self.pitch < -90.0: 103 | self.pitch = -90.0 104 | # 105 | self.updateCameraVectors() 106 | 107 | def zoomInOut(self, yoffset: float, 108 | zoomBound=45.0): 109 | "Zoom with camera" 110 | if self.zoom >= 1.0 and self.zoom <= zoomBound: 111 | self.zoom -= yoffset 112 | elif self.zoom <= 1.0: 113 | self.zoom = 1.0 114 | elif self.zoom >= zoomBound: 115 | self.zoom = zoomBound 116 | 117 | def setCameraWithVectors(self, 118 | position: tuple, 119 | up: tuple, 120 | front: tuple, 121 | yaw: float, 122 | pitch: float, 123 | zoom: float, 124 | speed: float, 125 | sensitivity: float): 126 | "Set camera" 127 | assert len(position) == len(up) 128 | assert len(up) == len(front) 129 | assert len(front) == 3 130 | self.position = position 131 | self.worldUp = up 132 | self.pitch = pitch 133 | self.yaw = yaw 134 | self.movementSpeed = speed 135 | self.movementSensitivity = sensitivity 136 | self.front = front 137 | self.zoom = zoom 138 | self.updateCameraVectors() 139 | 140 | def setCameraWithFloatVals(self, 141 | posx: float, 142 | posy: float, 143 | posz: float, 144 | upx: float, 145 | upy: float, 146 | upz: float, 147 | yaw: float, 148 | pitch: float, 149 | speed: float, 150 | sensitivity: float, 151 | zoom: float, 152 | front: tuple): 153 | "Set camera floats" 154 | assert len(front) == 3 155 | self.position = (posx, posy, posz) 156 | self.worldUp = (upx, upy, upz) 157 | self.yaw = yaw 158 | self.pitch = pitch 159 | self.movementSpeed = speed 160 | self.movementSensitivity = sensitivity 161 | self.zoom = zoom 162 | self.front = front 163 | self.updateCameraVectors() 164 | 165 | def getViewMatrix(self): 166 | "Obtain view matrix for camera" 167 | return computeLookAtPure( 168 | pos=self.position, 169 | target=vec2vecAdd(self.position, 170 | self.front), 171 | worldUp=self.worldUp 172 | ) 173 | 174 | 175 | class QtCamera: 176 | "An abstract camera for 3d movement in world" 177 | 178 | def __init__(self): 179 | "" 180 | self.availableMoves = ["forward", "backward", "left", "right"] 181 | # Camera attributes 182 | self.position = QVector3D(0.0, 0.0, 0.0) 183 | self.front = QVector3D(0.0, 0.0, -0.5) 184 | self.worldUp = QVector3D(0.0, 1.0, 0.0) 185 | self.right = QVector3D() 186 | self.up = QVector3D() 187 | 188 | # Euler Angles for rotation 189 | self.yaw = -90.0 190 | self.pitch = 0.0 191 | 192 | # camera options 193 | self.movementSpeed = 2.5 194 | self.movementSensitivity = 0.00001 195 | self.zoom = 45.0 196 | 197 | def updateCameraVectors(self): 198 | "Update the camera vectors and compute a new front" 199 | yawRadian = np.radians(self.yaw) 200 | yawCos = np.cos(yawRadian) 201 | pitchRadian = np.radians(self.pitch) 202 | pitchCos = np.cos(pitchRadian) 203 | frontX = yawCos * pitchCos 204 | frontY = np.sin(pitchRadian) 205 | frontZ = np.sin(yawRadian) * pitchCos 206 | self.front = QVector3D(frontX, frontY, frontZ) 207 | self.front.normalize() 208 | self.right = QVector3D.crossProduct( 209 | self.front, 210 | self.worldUp) 211 | self.right.normalize() 212 | self.up = QVector3D.crossProduct( 213 | self.right, 214 | self.front) 215 | self.up.normalize() 216 | 217 | def move(self, direction: str, deltaTime: float): 218 | "" 219 | velocity = self.movementSpeed * deltaTime 220 | direction = direction.lower() 221 | if direction not in self.availableMoves: 222 | raise ValueError( 223 | "Unknown direction {0}, available moves are {1}".format( 224 | direction, self.availableMoves 225 | ) 226 | ) 227 | if direction == "forward": 228 | self.position += self.front * velocity 229 | elif direction == "backward": 230 | self.position -= self.front * velocity 231 | elif direction == "right": 232 | self.position += self.right * velocity 233 | elif direction == "left": 234 | self.position -= self.right * velocity 235 | 236 | def lookAround(self, 237 | xoffset: float, 238 | yoffset: float, 239 | pitchBound: bool): 240 | "Look around with camera" 241 | xoffset *= self.movementSensitivity 242 | yoffset *= self.movementSensitivity 243 | self.yaw += xoffset 244 | self.pitch += yoffset 245 | 246 | if pitchBound: 247 | if self.pitch > 89.9: 248 | self.pitch = 89.9 249 | elif self.pitch < -89.9: 250 | self.pitch = -89.9 251 | # 252 | self.updateCameraVectors() 253 | 254 | def zoomInOut(self, yoffset: float, 255 | zoomBound=45.0): 256 | "Zoom with camera" 257 | if self.zoom >= 1.0 and self.zoom <= zoomBound: 258 | self.zoom -= yoffset 259 | elif self.zoom <= 1.0: 260 | self.zoom = 1.0 261 | elif self.zoom >= zoomBound: 262 | self.zoom = zoomBound 263 | 264 | def getViewMatrix(self): 265 | "Obtain view matrix for camera" 266 | view = QMatrix4x4() 267 | view.lookAt(self.position, 268 | self.position+self.front, 269 | self.up 270 | ) 271 | return view 272 | 273 | def setCameraWithVectors(self, 274 | position=QVector3D(0.0, 0.0, 0.0), 275 | worldUp=QVector3D(0.0, 1.0, 0.0), 276 | yaw=-90.0, 277 | pitch=0.0, 278 | zoom=45.0, 279 | speed=2.5, 280 | sensitivity=0.00001): 281 | "Set camera" 282 | self.position = position 283 | self.worldUp = worldUp 284 | self.pitch = pitch 285 | self.yaw = yaw 286 | self.movementSpeed = speed 287 | self.movementSensitivity = sensitivity 288 | self.zoom = zoom 289 | self.updateCameraVectors() 290 | 291 | def setCameraWithFloatVals(self, 292 | posx=0.0, 293 | posy=0.0, 294 | posz=0.0, 295 | upx=0.0, 296 | upy=1.0, 297 | upz=0.0, 298 | yaw=-90.0, 299 | pitch=0.0, 300 | zoom=45.0, 301 | speed=2.5, 302 | sensitivity=0.00001, 303 | ): 304 | "Set camera floats" 305 | self.position = QVector3D(posx, posy, posz) 306 | self.worldUp = QVector3D(upx, upy, upz) 307 | self.yaw = yaw 308 | self.pitch = pitch 309 | self.movementSpeed = speed 310 | self.movementSensitivity = sensitivity 311 | self.zoom = zoom 312 | self.updateCameraVectors() 313 | 314 | 315 | class FPSCameraQt(QtCamera): 316 | "FPS Camera based on qtcamera" 317 | 318 | def __init__(self): 319 | super().__init__() 320 | 321 | def move(self, direction: str, deltaTime: float): 322 | "Move camera in single axis" 323 | velocity = self.movementSpeed * deltaTime 324 | direction = direction.lower() 325 | if direction not in self.availableMoves: 326 | raise ValueError( 327 | "Unknown direction {0}, available moves are {1}".format( 328 | direction, self.availableMoves 329 | ) 330 | ) 331 | if direction == "forward": 332 | self.position += self.front * velocity 333 | elif direction == "backward": 334 | self.position -= self.front * velocity 335 | elif direction == "right": 336 | self.position += self.right * velocity 337 | elif direction == "left": 338 | self.position -= self.right * velocity 339 | 340 | self.position.setY(0.0) # y val == 0 341 | -------------------------------------------------------------------------------- /tutorials/05-cube/glcube.py: -------------------------------------------------------------------------------- 1 | # Author: Kaan Eraslan 2 | # purpose draw a rectangle on window 3 | 4 | import numpy as np 5 | import os 6 | import sys 7 | import ctypes 8 | from tutorials.utils.camera import QtCamera 9 | from tutorials.utils.utils import computePerspectiveNp 10 | from tutorials.utils.utils import computePerspectiveQt 11 | from tutorials.utils.utils import arr2qmat 12 | 13 | from PySide2.QtGui import QVector3D 14 | from PySide2.QtGui import QImage 15 | from PySide2.QtGui import QOpenGLVertexArrayObject 16 | from PySide2.QtGui import QOpenGLBuffer 17 | from PySide2.QtGui import QOpenGLShaderProgram 18 | from PySide2.QtGui import QOpenGLShader 19 | from PySide2.QtGui import QOpenGLContext 20 | from PySide2.QtGui import QOpenGLTexture 21 | from PySide2.QtGui import QMatrix4x4 22 | from PySide2.QtGui import QVector4D 23 | from PySide2.QtGui import QColor 24 | 25 | from PySide2.QtWidgets import QApplication 26 | from PySide2.QtWidgets import QMessageBox 27 | from PySide2.QtWidgets import QOpenGLWidget 28 | 29 | from PySide2.QtCore import QCoreApplication 30 | 31 | from PySide2.shiboken2 import VoidPtr 32 | 33 | 34 | try: 35 | from OpenGL import GL as pygl 36 | except ImportError: 37 | app = QApplication(sys.argv) 38 | messageBox = QMessageBox(QMessageBox.Critical, "OpenGL hellogl", 39 | "PyOpenGL must be installed to run this example.", 40 | QMessageBox.Close) 41 | messageBox.setDetailedText( 42 | "Run:\npip install PyOpenGL PyOpenGL_accelerate") 43 | messageBox.exec_() 44 | sys.exit(1) 45 | 46 | 47 | class CubeGL(QOpenGLWidget): 48 | "Cube gl widget" 49 | 50 | def __init__(self, parent=None): 51 | QOpenGLWidget.__init__(self, parent) 52 | 53 | # camera 54 | self.camera = QtCamera() 55 | self.camera.position = QVector3D(0.0, 0.0, 3.0) 56 | self.camera.front = QVector3D(0.0, 0.0, -1.0) 57 | self.camera.up = QVector3D(0.0, 1.0, 0.0) 58 | 59 | # shaders etc 60 | tutoTutoDir = os.path.dirname(__file__) 61 | tutoPardir = os.path.join(tutoTutoDir, os.pardir) 62 | tutoPardir = os.path.realpath(tutoPardir) 63 | mediaDir = os.path.join(tutoPardir, "media") 64 | shaderDir = os.path.join(mediaDir, "shaders") 65 | 66 | availableShaders = ["cube"] 67 | self.shaders = { 68 | name: { 69 | "fragment": os.path.join(shaderDir, name + ".frag"), 70 | "vertex": os.path.join(shaderDir, name + ".vert") 71 | } for name in availableShaders 72 | } 73 | self.core = "--coreprofile" in QCoreApplication.arguments() 74 | imdir = os.path.join(mediaDir, "images") 75 | imFName = "im" 76 | imageFile1 = os.path.join(imdir, imFName + "0.png") 77 | self.image1 = QImage(imageFile1).mirrored() 78 | imageFile2 = os.path.join(imdir, imFName + "1.png") 79 | self.image2 = QImage(imageFile2).mirrored() 80 | 81 | # opengl data related 82 | self.context = QOpenGLContext() 83 | self.vao = QOpenGLVertexArrayObject() 84 | self.vbo = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer) 85 | self.program = QOpenGLShaderProgram() 86 | self.texture1 = None 87 | self.texture2 = None 88 | self.texUnit1 = 0 89 | self.texUnit2 = 1 90 | 91 | # vertex data 92 | self.cubeVertices = np.array([ 93 | # pos vec3 || texcoord vec2 94 | -0.5, -0.5, -0.5, 0.0, 0.0, 95 | 0.5, -0.5, -0.5, 1.0, 0.0, 96 | 0.5, 0.5, -0.5, 1.0, 1.0, 97 | 0.5, 0.5, -0.5, 1.0, 1.0, 98 | -0.5, 0.5, -0.5, 0.0, 1.0, 99 | -0.5, -0.5, -0.5, 0.0, 0.0, 100 | 101 | -0.5, -0.5, 0.5, 0.0, 0.0, 102 | 0.5, -0.5, 0.5, 1.0, 0.0, 103 | 0.5, 0.5, 0.5, 1.0, 1.0, 104 | 0.5, 0.5, 0.5, 1.0, 1.0, 105 | -0.5, 0.5, 0.5, 0.0, 1.0, 106 | -0.5, -0.5, 0.5, 0.0, 0.0, 107 | 108 | -0.5, 0.5, 0.5, 1.0, 0.0, 109 | -0.5, 0.5, -0.5, 1.0, 1.0, 110 | -0.5, -0.5, -0.5, 0.0, 1.0, 111 | -0.5, -0.5, -0.5, 0.0, 1.0, 112 | -0.5, -0.5, 0.5, 0.0, 0.0, 113 | -0.5, 0.5, 0.5, 1.0, 0.0, 114 | 115 | 0.5, 0.5, 0.5, 1.0, 0.0, 116 | 0.5, 0.5, -0.5, 1.0, 1.0, 117 | 0.5, -0.5, -0.5, 0.0, 1.0, 118 | 0.5, -0.5, -0.5, 0.0, 1.0, 119 | 0.5, -0.5, 0.5, 0.0, 0.0, 120 | 0.5, 0.5, 0.5, 1.0, 0.0, 121 | 122 | -0.5, -0.5, -0.5, 0.0, 1.0, 123 | 0.5, -0.5, -0.5, 1.0, 1.0, 124 | 0.5, -0.5, 0.5, 1.0, 0.0, 125 | 0.5, -0.5, 0.5, 1.0, 0.0, 126 | -0.5, -0.5, 0.5, 0.0, 0.0, 127 | -0.5, -0.5, -0.5, 0.0, 1.0, 128 | 129 | -0.5, 0.5, -0.5, 0.0, 1.0, 130 | 0.5, 0.5, -0.5, 1.0, 1.0, 131 | 0.5, 0.5, 0.5, 1.0, 0.0, 132 | 0.5, 0.5, 0.5, 1.0, 0.0, 133 | -0.5, 0.5, 0.5, 0.0, 0.0, 134 | -0.5, 0.5, -0.5, 0.0, 1.0 135 | ], dtype=ctypes.c_float 136 | ) 137 | # cube worldSpace coordinates 138 | self.cubeCoords = [ 139 | QVector3D(0.0, 0.0, 0.0), 140 | QVector3D(2.0, 5.0, -15.0), 141 | QVector3D(-1.5, -2.2, -2.5), 142 | QVector3D(-3.8, -2.0, -12.3), 143 | QVector3D(2.4, -0.4, -3.5), 144 | QVector3D(-1.7, 3.0, -7.5), 145 | QVector3D(1.3, -2.0, -2.5), 146 | QVector3D(1.5, 2.0, -2.5), 147 | QVector3D(1.5, 0.2, -1.5), 148 | QVector3D(-1.3, 1.0, -1.5) 149 | ] 150 | # notice the correspondance the vec4 of fragment shader 151 | # and our choice here 152 | 153 | def loadShader(self, 154 | shaderName: str, 155 | shaderType: str): 156 | "Load shader" 157 | shader = self.shaders[shaderName] 158 | shaderSourcePath = shader[shaderType] 159 | if shaderType == "vertex": 160 | shader = QOpenGLShader(QOpenGLShader.Vertex) 161 | else: 162 | shader = QOpenGLShader(QOpenGLShader.Fragment) 163 | # 164 | isCompiled = shader.compileSourceFile(shaderSourcePath) 165 | 166 | if isCompiled is False: 167 | print(shader.log()) 168 | raise ValueError( 169 | "{0} shader {2} known as {1} is not compiled".format( 170 | shaderType, shaderName, shaderSourcePath 171 | ) 172 | ) 173 | return shader 174 | 175 | def useShaders( 176 | self, 177 | shaderProgram: QOpenGLShaderProgram, 178 | shaders: {"shaderName": ["shaderType"]}, 179 | attrLocs: dict 180 | ): 181 | "" 182 | print("program shaders: ", 183 | shaderProgram.shaders()) 184 | for shaderName, shaderTypes in shaders.items(): 185 | # 186 | if len(shaderTypes) == 2: 187 | self.useShaderSingleName( 188 | shaderProgram=shaderProgram, 189 | shaderName=shaderName, 190 | attrLocs=attrLocs 191 | ) 192 | elif len(shaderTypes) == 1: 193 | shaderType = shaderTypes[0] 194 | if shaderType == "vertex": 195 | shader = self.loadVertexShader( 196 | shaderName) 197 | else: 198 | shader = self.loadFragmentShader( 199 | shaderName 200 | ) 201 | 202 | shaderProgram.addShader(shader) 203 | # adding shader 204 | self.bindLinkProgram( 205 | shaderProgram, 206 | attrLocs) 207 | 208 | def loadVertexShader(self, shaderName: str): 209 | "load vertex shader" 210 | return self.loadShader(shaderName, "vertex") 211 | 212 | def loadFragmentShader(self, shaderName: str): 213 | "load fragment shader" 214 | return self.loadShader(shaderName, "fragment") 215 | 216 | def getGlInfo(self): 217 | "Get opengl info" 218 | info = """ 219 | Vendor: {0} 220 | Renderer: {1} 221 | OpenGL Version: {2} 222 | Shader Version: {3} 223 | """.format( 224 | pygl.glGetString(pygl.GL_VENDOR), 225 | pygl.glGetString(pygl.GL_RENDERER), 226 | pygl.glGetString(pygl.GL_VERSION), 227 | pygl.glGetString(pygl.GL_SHADING_LANGUAGE_VERSION) 228 | ) 229 | return info 230 | 231 | def cleanUpGl(self): 232 | "Clean up everything" 233 | self.context.makeCurrent() 234 | self.vbo.destroy() 235 | self.texture1.destroy() 236 | self.texture2.destroy() 237 | self.vao.destroy() 238 | del self.program 239 | self.program = None 240 | self.doneCurrent() 241 | 242 | def resizeGL(self, width: int, height: int): 243 | "Resize the viewport" 244 | funcs = self.context.functions() 245 | funcs.glViewport(0, 0, width, height) 246 | 247 | def initializeGL(self): 248 | print('gl initial') 249 | print(self.getGlInfo()) 250 | 251 | # create context and make it current 252 | self.context.create() 253 | self.context.aboutToBeDestroyed.connect( 254 | self.cleanUpGl) 255 | 256 | # initialize functions 257 | funcs = self.context.functions() 258 | funcs.initializeOpenGLFunctions() 259 | funcs.glClearColor(0.0, 0.4, 0.4, 0) 260 | funcs.glEnable(pygl.GL_DEPTH_TEST) 261 | funcs.glEnable(pygl.GL_TEXTURE_2D) 262 | 263 | # create uniform values for shaders 264 | # deal with shaders 265 | 266 | # cube shader 267 | self.program = QOpenGLShaderProgram( 268 | self.context 269 | ) 270 | vshader = self.loadVertexShader("cube") 271 | fshader = self.loadFragmentShader("cube") 272 | self.program.addShader(vshader) # adding vertex shader 273 | self.program.addShader(fshader) # adding fragment shader 274 | self.program.bindAttributeLocation( 275 | "aPos", 0) 276 | self.program.bindAttributeLocation( 277 | "aTexCoord", 1) 278 | 279 | isLinked = self.program.link() 280 | print("cube shader program is linked: ", 281 | isLinked) 282 | # bind the program 283 | self.program.bind() 284 | 285 | # set projection matrix 286 | projectionMatrix = QMatrix4x4() 287 | projectionMatrix.perspective( 288 | self.camera.zoom, 289 | self.width() / self.height(), 290 | 0.2, 100.0) 291 | 292 | self.program.setUniformValue('projection', 293 | projectionMatrix) 294 | 295 | # set view/camera matrix 296 | viewMatrix = self.camera.getViewMatrix() 297 | self.program.setUniformValue('view', 298 | viewMatrix) 299 | self.program.setUniformValue('myTexture1', self.texUnit1) 300 | self.program.setUniformValue('myTexture2', self.texUnit2) 301 | # 302 | # deal with vaos and vbo 303 | # vbo 304 | isVbo = self.vbo.create() 305 | isVboBound = self.vbo.bind() 306 | 307 | floatSize = ctypes.sizeof(ctypes.c_float) 308 | 309 | # allocate space on vbo buffer 310 | self.vbo.allocate( 311 | self.cubeVertices.tobytes(), 312 | floatSize * self.cubeVertices.size) 313 | self.vao.create() 314 | vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao) 315 | funcs.glEnableVertexAttribArray(0) # viewport 316 | funcs.glVertexAttribPointer(0, 317 | 3, 318 | int(pygl.GL_FLOAT), 319 | int(pygl.GL_FALSE), 320 | 5 * floatSize, 321 | VoidPtr(0) 322 | ) 323 | funcs.glEnableVertexAttribArray(1) 324 | funcs.glVertexAttribPointer(1, 325 | 2, 326 | int(pygl.GL_FLOAT), 327 | int(pygl.GL_FALSE), 328 | 5 * floatSize, 329 | VoidPtr(3 * floatSize) 330 | ) 331 | # deal with textures 332 | # first texture 333 | self.texture1 = QOpenGLTexture( 334 | QOpenGLTexture.Target2D) 335 | self.texture1.create() 336 | self.texture1.bind(self.texUnit1) 337 | self.texture1.setData(self.image1) 338 | self.texture1.setMinMagFilters( 339 | QOpenGLTexture.Nearest, 340 | QOpenGLTexture.Nearest) 341 | self.texture1.setWrapMode( 342 | QOpenGLTexture.DirectionS, 343 | QOpenGLTexture.Repeat) 344 | self.texture1.setWrapMode( 345 | QOpenGLTexture.DirectionT, 346 | QOpenGLTexture.Repeat) 347 | 348 | # second texture 349 | self.texture2 = QOpenGLTexture( 350 | QOpenGLTexture.Target2D) 351 | self.texture2.create() 352 | self.texture2.bind(self.texUnit2) 353 | self.texture2.setData(self.image2) 354 | self.texture2.setMinMagFilters( 355 | QOpenGLTexture.Linear, 356 | QOpenGLTexture.Linear) 357 | self.texture2.setWrapMode( 358 | QOpenGLTexture.DirectionS, 359 | QOpenGLTexture.Repeat) 360 | self.texture2.setWrapMode( 361 | QOpenGLTexture.DirectionT, 362 | QOpenGLTexture.Repeat) 363 | 364 | self.vbo.release() 365 | vaoBinder = None 366 | print("gl initialized") 367 | 368 | def paintGL(self): 369 | "drawing loop" 370 | funcs = self.context.functions() 371 | 372 | # clean up what was drawn 373 | funcs.glClear( 374 | pygl.GL_COLOR_BUFFER_BIT | pygl.GL_DEPTH_BUFFER_BIT 375 | ) 376 | self.vao.bind() 377 | self.vbo.bind() 378 | 379 | # actual drawing 380 | self.program.bind() 381 | rotvec = QVector3D(0.7, 0.2, 0.5) 382 | # bind textures 383 | for i, pos in enumerate(self.cubeCoords): 384 | # 385 | cubeModel = QMatrix4x4() 386 | cubeModel.translate(pos) 387 | angle = 30 * i 388 | cubeModel.rotate(angle, rotvec) 389 | self.program.setUniformValue("model", 390 | cubeModel) 391 | self.texture1.bind(self.texUnit1) 392 | self.texture2.bind(self.texUnit2) 393 | funcs.glDrawArrays( 394 | pygl.GL_TRIANGLES, 395 | 0, 396 | self.cubeVertices.size 397 | ) 398 | self.vbo.release() 399 | self.program.release() 400 | self.texture1.release() 401 | self.texture2.release() -------------------------------------------------------------------------------- /tutorials/06-events/glevents.py: -------------------------------------------------------------------------------- 1 | # Author: Kaan Eraslan 2 | # purpose interactive widget 3 | 4 | import numpy as np 5 | import os 6 | import sys 7 | import ctypes 8 | from tutorials.utils.camera import QtCamera 9 | from tutorials.utils.utils import computePerspectiveNp 10 | from tutorials.utils.utils import computePerspectiveQt 11 | from tutorials.utils.utils import arr2qmat 12 | 13 | from PySide2.QtGui import QVector3D 14 | from PySide2.QtGui import QImage 15 | from PySide2.QtGui import QOpenGLVertexArrayObject 16 | from PySide2.QtGui import QOpenGLBuffer 17 | from PySide2.QtGui import QOpenGLShaderProgram 18 | from PySide2.QtGui import QOpenGLShader 19 | from PySide2.QtGui import QOpenGLContext 20 | from PySide2.QtGui import QOpenGLTexture 21 | from PySide2.QtGui import QMatrix4x4 22 | from PySide2.QtGui import QVector4D 23 | from PySide2.QtGui import QColor 24 | 25 | from PySide2.QtWidgets import QApplication 26 | from PySide2.QtWidgets import QMessageBox 27 | from PySide2.QtWidgets import QOpenGLWidget 28 | 29 | from PySide2.QtCore import QCoreApplication 30 | 31 | from PySide2.shiboken2 import VoidPtr 32 | 33 | 34 | try: 35 | from OpenGL import GL as pygl 36 | except ImportError: 37 | app = QApplication(sys.argv) 38 | messageBox = QMessageBox(QMessageBox.Critical, "OpenGL hellogl", 39 | "PyOpenGL must be installed to run this example.", 40 | QMessageBox.Close) 41 | messageBox.setDetailedText( 42 | "Run:\npip install PyOpenGL PyOpenGL_accelerate") 43 | messageBox.exec_() 44 | sys.exit(1) 45 | 46 | 47 | class EventsGL(QOpenGLWidget): 48 | "Cube gl widget" 49 | 50 | def __init__(self, parent=None): 51 | QOpenGLWidget.__init__(self, parent) 52 | 53 | # camera 54 | self.camera = QtCamera() 55 | self.camera.position = QVector3D(0.0, 0.0, 3.0) 56 | self.camera.front = QVector3D(0.0, 0.0, -1.0) 57 | self.camera.up = QVector3D(0.0, 1.0, 0.0) 58 | self.camera.movementSensitivity = 0.05 59 | 60 | # shaders etc 61 | tutoTutoDir = os.path.dirname(__file__) 62 | tutoPardir = os.path.join(tutoTutoDir, os.pardir) 63 | tutoPardir = os.path.realpath(tutoPardir) 64 | mediaDir = os.path.join(tutoPardir, "media") 65 | shaderDir = os.path.join(mediaDir, "shaders") 66 | 67 | availableShaders = ["cube"] 68 | self.shaders = { 69 | name: { 70 | "fragment": os.path.join(shaderDir, name + ".frag"), 71 | "vertex": os.path.join(shaderDir, name + ".vert") 72 | } for name in availableShaders 73 | } 74 | self.core = "--coreprofile" in QCoreApplication.arguments() 75 | imdir = os.path.join(mediaDir, "images") 76 | imFName = "im" 77 | imageFile1 = os.path.join(imdir, imFName + "0.png") 78 | self.image1 = QImage(imageFile1).mirrored() 79 | imageFile2 = os.path.join(imdir, imFName + "1.png") 80 | self.image2 = QImage(imageFile2).mirrored() 81 | 82 | # opengl data related 83 | self.context = QOpenGLContext() 84 | self.vao = QOpenGLVertexArrayObject() 85 | self.vbo = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer) 86 | self.program = QOpenGLShaderProgram() 87 | self.texture1 = None 88 | self.texture2 = None 89 | self.texUnit1 = 0 90 | self.texUnit2 = 1 91 | 92 | # vertex data 93 | self.cubeVertices = np.array([ 94 | # pos vec3 || texcoord vec2 95 | -0.5, -0.5, -0.5, 0.0, 0.0, 96 | 0.5, -0.5, -0.5, 1.0, 0.0, 97 | 0.5, 0.5, -0.5, 1.0, 1.0, 98 | 0.5, 0.5, -0.5, 1.0, 1.0, 99 | -0.5, 0.5, -0.5, 0.0, 1.0, 100 | -0.5, -0.5, -0.5, 0.0, 0.0, 101 | 102 | -0.5, -0.5, 0.5, 0.0, 0.0, 103 | 0.5, -0.5, 0.5, 1.0, 0.0, 104 | 0.5, 0.5, 0.5, 1.0, 1.0, 105 | 0.5, 0.5, 0.5, 1.0, 1.0, 106 | -0.5, 0.5, 0.5, 0.0, 1.0, 107 | -0.5, -0.5, 0.5, 0.0, 0.0, 108 | 109 | -0.5, 0.5, 0.5, 1.0, 0.0, 110 | -0.5, 0.5, -0.5, 1.0, 1.0, 111 | -0.5, -0.5, -0.5, 0.0, 1.0, 112 | -0.5, -0.5, -0.5, 0.0, 1.0, 113 | -0.5, -0.5, 0.5, 0.0, 0.0, 114 | -0.5, 0.5, 0.5, 1.0, 0.0, 115 | 116 | 0.5, 0.5, 0.5, 1.0, 0.0, 117 | 0.5, 0.5, -0.5, 1.0, 1.0, 118 | 0.5, -0.5, -0.5, 0.0, 1.0, 119 | 0.5, -0.5, -0.5, 0.0, 1.0, 120 | 0.5, -0.5, 0.5, 0.0, 0.0, 121 | 0.5, 0.5, 0.5, 1.0, 0.0, 122 | 123 | -0.5, -0.5, -0.5, 0.0, 1.0, 124 | 0.5, -0.5, -0.5, 1.0, 1.0, 125 | 0.5, -0.5, 0.5, 1.0, 0.0, 126 | 0.5, -0.5, 0.5, 1.0, 0.0, 127 | -0.5, -0.5, 0.5, 0.0, 0.0, 128 | -0.5, -0.5, -0.5, 0.0, 1.0, 129 | 130 | -0.5, 0.5, -0.5, 0.0, 1.0, 131 | 0.5, 0.5, -0.5, 1.0, 1.0, 132 | 0.5, 0.5, 0.5, 1.0, 0.0, 133 | 0.5, 0.5, 0.5, 1.0, 0.0, 134 | -0.5, 0.5, 0.5, 0.0, 0.0, 135 | -0.5, 0.5, -0.5, 0.0, 1.0 136 | ], dtype=ctypes.c_float 137 | ) 138 | # cube worldSpace coordinates 139 | self.cubeCoords = [ 140 | QVector3D(0.2, 1.1, -1.0), 141 | QVector3D(2.0, 5.0, -15.0), 142 | QVector3D(-1.5, -2.2, -2.5), 143 | QVector3D(-3.8, -2.0, -12.3), 144 | QVector3D(2.4, -0.4, -3.5), 145 | QVector3D(-1.7, 3.0, -7.5), 146 | QVector3D(1.3, -2.0, -2.5), 147 | QVector3D(1.5, 2.0, -2.5), 148 | QVector3D(1.5, 0.2, -1.5), 149 | QVector3D(-1.3, 1.0, -1.5) 150 | ] 151 | self.rotateVector = QVector3D(0.7, 0.2, 0.5) 152 | 153 | def loadShader(self, 154 | shaderName: str, 155 | shaderType: str): 156 | "Load shader" 157 | shader = self.shaders[shaderName] 158 | shaderSourcePath = shader[shaderType] 159 | if shaderType == "vertex": 160 | shader = QOpenGLShader(QOpenGLShader.Vertex) 161 | else: 162 | shader = QOpenGLShader(QOpenGLShader.Fragment) 163 | # 164 | isCompiled = shader.compileSourceFile(shaderSourcePath) 165 | 166 | if isCompiled is False: 167 | print(shader.log()) 168 | raise ValueError( 169 | "{0} shader {2} known as {1} is not compiled".format( 170 | shaderType, shaderName, shaderSourcePath 171 | ) 172 | ) 173 | return shader 174 | 175 | def useShaders( 176 | self, 177 | shaderProgram: QOpenGLShaderProgram, 178 | shaders: {"shaderName": ["shaderType"]}, 179 | attrLocs: dict 180 | ): 181 | "" 182 | print("program shaders: ", 183 | shaderProgram.shaders()) 184 | for shaderName, shaderTypes in shaders.items(): 185 | # 186 | if len(shaderTypes) == 2: 187 | self.useShaderSingleName( 188 | shaderProgram=shaderProgram, 189 | shaderName=shaderName, 190 | attrLocs=attrLocs 191 | ) 192 | elif len(shaderTypes) == 1: 193 | shaderType = shaderTypes[0] 194 | if shaderType == "vertex": 195 | shader = self.loadVertexShader( 196 | shaderName) 197 | else: 198 | shader = self.loadFragmentShader( 199 | shaderName 200 | ) 201 | 202 | shaderProgram.addShader(shader) 203 | # adding shader 204 | self.bindLinkProgram( 205 | shaderProgram, 206 | attrLocs) 207 | 208 | def loadVertexShader(self, shaderName: str): 209 | "load vertex shader" 210 | return self.loadShader(shaderName, "vertex") 211 | 212 | def loadFragmentShader(self, shaderName: str): 213 | "load fragment shader" 214 | return self.loadShader(shaderName, "fragment") 215 | 216 | def getGlInfo(self): 217 | "Get opengl info" 218 | info = """ 219 | Vendor: {0} 220 | Renderer: {1} 221 | OpenGL Version: {2} 222 | Shader Version: {3} 223 | """.format( 224 | pygl.glGetString(pygl.GL_VENDOR), 225 | pygl.glGetString(pygl.GL_RENDERER), 226 | pygl.glGetString(pygl.GL_VERSION), 227 | pygl.glGetString(pygl.GL_SHADING_LANGUAGE_VERSION) 228 | ) 229 | return info 230 | 231 | def moveCamera(self, direction: str): 232 | "Move camera to certain direction and update gl widget" 233 | self.camera.move(direction, deltaTime=0.05) 234 | self.update() 235 | 236 | def turnAround(self, x: float, y: float): 237 | "" 238 | self.camera.lookAround(xoffset=x, 239 | yoffset=y, 240 | pitchBound=True) 241 | self.update() 242 | 243 | def rotateCubes(self, xval: float, 244 | yval: float, zval: float): 245 | "" 246 | self.rotateVector.setZ(zval) 247 | self.rotateVector.setY(yval) 248 | self.rotateVector.setX(xval) 249 | self.update() 250 | 251 | def cleanUpGl(self): 252 | "Clean up everything" 253 | self.context.makeCurrent() 254 | self.vbo.destroy() 255 | self.texture1.destroy() 256 | self.texture2.destroy() 257 | self.vao.destroy() 258 | del self.program 259 | self.program = None 260 | self.doneCurrent() 261 | 262 | def resizeGL(self, width: int, height: int): 263 | "Resize the viewport" 264 | funcs = self.context.functions() 265 | funcs.glViewport(0, 0, width, height) 266 | 267 | def initializeGL(self): 268 | print('gl initial') 269 | print(self.getGlInfo()) 270 | 271 | # create context and make it current 272 | self.context.create() 273 | self.context.aboutToBeDestroyed.connect( 274 | self.cleanUpGl) 275 | 276 | # initialize functions 277 | funcs = self.context.functions() 278 | funcs.initializeOpenGLFunctions() 279 | funcs.glClearColor(0.0, 0.4, 0.4, 0) 280 | funcs.glEnable(pygl.GL_DEPTH_TEST) 281 | funcs.glEnable(pygl.GL_TEXTURE_2D) 282 | 283 | # create uniform values for shaders 284 | # deal with shaders 285 | 286 | # cube shader 287 | self.program = QOpenGLShaderProgram( 288 | self.context 289 | ) 290 | vshader = self.loadVertexShader("cube") 291 | fshader = self.loadFragmentShader("cube") 292 | self.program.addShader(vshader) # adding vertex shader 293 | self.program.addShader(fshader) # adding fragment shader 294 | self.program.bindAttributeLocation( 295 | "aPos", 0) 296 | self.program.bindAttributeLocation( 297 | "aTexCoord", 1) 298 | 299 | isLinked = self.program.link() 300 | print("cube shader program is linked: ", 301 | isLinked) 302 | # bind the program 303 | self.program.bind() 304 | 305 | self.program.setUniformValue('myTexture1', self.texUnit1) 306 | self.program.setUniformValue('myTexture2', self.texUnit2) 307 | # 308 | # deal with vaos and vbo 309 | # vbo 310 | isVbo = self.vbo.create() 311 | isVboBound = self.vbo.bind() 312 | 313 | floatSize = ctypes.sizeof(ctypes.c_float) 314 | 315 | # allocate space on vbo buffer 316 | self.vbo.allocate( 317 | self.cubeVertices.tobytes(), 318 | floatSize * self.cubeVertices.size) 319 | self.vao.create() 320 | vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao) 321 | funcs.glEnableVertexAttribArray(0) # viewport 322 | funcs.glVertexAttribPointer(0, 323 | 3, 324 | int(pygl.GL_FLOAT), 325 | int(pygl.GL_FALSE), 326 | 5 * floatSize, 327 | VoidPtr(0) 328 | ) 329 | funcs.glEnableVertexAttribArray(1) 330 | funcs.glVertexAttribPointer(1, 331 | 2, 332 | int(pygl.GL_FLOAT), 333 | int(pygl.GL_FALSE), 334 | 5 * floatSize, 335 | VoidPtr(3 * floatSize) 336 | ) 337 | # deal with textures 338 | # first texture 339 | self.texture1 = QOpenGLTexture( 340 | QOpenGLTexture.Target2D) 341 | self.texture1.create() 342 | self.texture1.bind(self.texUnit1) 343 | self.texture1.setData(self.image1) 344 | self.texture1.setMinMagFilters( 345 | QOpenGLTexture.Nearest, 346 | QOpenGLTexture.Nearest) 347 | self.texture1.setWrapMode( 348 | QOpenGLTexture.DirectionS, 349 | QOpenGLTexture.Repeat) 350 | self.texture1.setWrapMode( 351 | QOpenGLTexture.DirectionT, 352 | QOpenGLTexture.Repeat) 353 | 354 | # second texture 355 | self.texture2 = QOpenGLTexture( 356 | QOpenGLTexture.Target2D) 357 | self.texture2.create() 358 | self.texture2.bind(self.texUnit2) 359 | self.texture2.setData(self.image2) 360 | self.texture2.setMinMagFilters( 361 | QOpenGLTexture.Linear, 362 | QOpenGLTexture.Linear) 363 | self.texture2.setWrapMode( 364 | QOpenGLTexture.DirectionS, 365 | QOpenGLTexture.Repeat) 366 | self.texture2.setWrapMode( 367 | QOpenGLTexture.DirectionT, 368 | QOpenGLTexture.Repeat) 369 | 370 | self.vbo.release() 371 | vaoBinder = None 372 | print("gl initialized") 373 | 374 | def paintGL(self): 375 | "drawing loop" 376 | funcs = self.context.functions() 377 | 378 | # clean up what was drawn 379 | funcs.glClear( 380 | pygl.GL_COLOR_BUFFER_BIT | pygl.GL_DEPTH_BUFFER_BIT 381 | ) 382 | self.vao.bind() 383 | self.vbo.bind() 384 | 385 | # actual drawing 386 | self.program.bind() 387 | # set projection matrix 388 | projectionMatrix = QMatrix4x4() 389 | projectionMatrix.perspective( 390 | self.camera.zoom, 391 | self.width() / self.height(), 392 | 0.2, 100.0) 393 | 394 | self.program.setUniformValue('projection', 395 | projectionMatrix) 396 | 397 | # set view/camera matrix 398 | viewMatrix = self.camera.getViewMatrix() 399 | self.program.setUniformValue('view', 400 | viewMatrix) 401 | 402 | # bind textures 403 | for i, pos in enumerate(self.cubeCoords): 404 | # 405 | cubeModel = QMatrix4x4() 406 | cubeModel.translate(pos) 407 | angle = 30 * i 408 | cubeModel.rotate(angle, self.rotateVector) 409 | self.program.setUniformValue("model", 410 | cubeModel) 411 | self.texture1.bind(self.texUnit1) 412 | self.texture2.bind(self.texUnit2) 413 | funcs.glDrawArrays( 414 | pygl.GL_TRIANGLES, 415 | 0, 416 | 36 417 | ) 418 | self.vbo.release() 419 | self.program.release() 420 | self.texture1.release() 421 | self.texture2.release() -------------------------------------------------------------------------------- /tutorials/03-VaoVbo/VAOsVBOs.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Vertex Array Objects and Vertex Buffer Objects with PySide2" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "Welcome to VAO and VBO tutorial. \n", 15 | "Our goal in this tutorial is to show how to use more than 1 Vertex Array Object and Vertex Buffer Object in PySide2 while using the QtGui.QOpenGL* api.\n", 16 | "\n", 17 | "Our resulting application would look like the following." 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": null, 23 | "metadata": {}, 24 | "outputs": [], 25 | "source": [ 26 | "import subprocess\n", 27 | "\n", 28 | "subprocess.run([\"python\", \"app.py\"])" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": {}, 34 | "source": [ 35 | "You should see two triangles pointing towards opposite directions, one should be blue and the other one should be red.\n", 36 | "\n", 37 | "I assume that you have already followed through the first tutorial on drawing a triangle on opengl. So I won't be introducing all of helper functions that I have used there. \n", 38 | "Neither the application window which is basically the same window from that tutorial.\n", 39 | "\n", 40 | "Now let's see the constructor of our OpenGL widget." 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": null, 46 | "metadata": {}, 47 | "outputs": [], 48 | "source": [ 49 | "class TriangleGL(QOpenGLWidget):\n", 50 | " def __init__(self, parent=None):\n", 51 | " QOpenGLWidget.__init__(self, parent)\n", 52 | "\n", 53 | " # shaders etc\n", 54 | " triangleTutoDir = os.path.dirname(__file__)\n", 55 | " shaderDir = os.path.join(triangleTutoDir, \"shaders\")\n", 56 | " availableShaders = [\"triangle\", \"triangle2\"] # notice the use of 2 shaders\n", 57 | " self.shaders = {\n", 58 | " name: {\n", 59 | " \"fragment\": os.path.join(shaderDir, name + \".frag\"),\n", 60 | " \"vertex\": os.path.join(shaderDir, name + \".vert\")\n", 61 | " } for name in availableShaders\n", 62 | " }\n", 63 | " self.core = \"--coreprofile\" in QCoreApplication.arguments()\n", 64 | "\n", 65 | " # opengl data related\n", 66 | " self.context = QOpenGLContext()\n", 67 | " \n", 68 | " # each vertex array object has its own vertex buffer object\n", 69 | " self.vao1 = QOpenGLVertexArrayObject()\n", 70 | " self.vbo1 = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer)\n", 71 | " \n", 72 | " self.vao2 = QOpenGLVertexArrayObject()\n", 73 | " self.vbo2 = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer)\n", 74 | "\n", 75 | " # and each VAO-VBO couple has its own shader program \n", 76 | " # to which we can attach different shaders \n", 77 | " self.program1 = QOpenGLShaderProgram()\n", 78 | " \n", 79 | " self.program2 = QOpenGLShaderProgram()\n", 80 | "\n", 81 | " # some vertex data for corners of triangle\n", 82 | " # first triangle\n", 83 | " self.vertexData1 = np.array(\n", 84 | " [0.9, 0.9, 0.0, # x, y, z\n", 85 | " 0.9, 0.7, 0.0, # x, y, z\n", 86 | " 0.7, 0.9, 0.0], # x, y, z\n", 87 | " dtype=ctypes.c_float\n", 88 | " )\n", 89 | " # second triangle\n", 90 | " self.vertexData2 = np.array(\n", 91 | " [-0.9, -0.9, 0.0, # x, y, z\n", 92 | " -0.9, -0.7, 0.0, # x, y, z\n", 93 | " -0.7, -0.9, 0.0], # x, y, z\n", 94 | " dtype=ctypes.c_float\n", 95 | " )\n", 96 | " # triangle color\n", 97 | " self.triangleColor1 = QVector4D(1.0, 0.0, 0.0, 0.0) # yellow triangle\n", 98 | " self.triangleColor2 = QVector4D(\n", 99 | " 0.0, 0.0, 0.5, 0.0) # not yellow triangle" 100 | ] 101 | }, 102 | { 103 | "cell_type": "markdown", 104 | "metadata": {}, 105 | "source": [ 106 | "As you can see we simply duplicated some of the objects. Remember:\n", 107 | "\n", 108 | "- Each VAO uses its own VBO\n", 109 | "- Each VAO-VBO couple uses its own shader program\n", 110 | "\n", 111 | "How does this affect our initialization function `initializeGL` ? Let's see." 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": null, 117 | "metadata": {}, 118 | "outputs": [], 119 | "source": [ 120 | " print('gl initial')\n", 121 | " print(self.getGlInfo())\n", 122 | " # create context and make it current\n", 123 | " self.context.create()\n", 124 | " self.context.aboutToBeDestroyed.connect(self.cleanUpGl)\n", 125 | "\n", 126 | " # initialize functions\n", 127 | " funcs = self.context.functions()\n", 128 | " funcs.initializeOpenGLFunctions()\n", 129 | " funcs.glClearColor(1, 1, 1, 1)" 130 | ] 131 | }, 132 | { 133 | "cell_type": "markdown", 134 | "metadata": {}, 135 | "source": [ 136 | "This should all be familiar to you by now so we are skipping the explanation." 137 | ] 138 | }, 139 | { 140 | "cell_type": "code", 141 | "execution_count": null, 142 | "metadata": {}, 143 | "outputs": [], 144 | "source": [ 145 | " # deal with shaders\n", 146 | " # first shader\n", 147 | " shaderName = \"triangle\"\n", 148 | " vshader = self.loadVertexShader(shaderName)\n", 149 | " fshader = self.loadFragmentShader(shaderName)\n", 150 | "\n", 151 | " # creating shader program\n", 152 | " self.program1 = QOpenGLShaderProgram(self.context)\n", 153 | " self.program1.addShader(vshader) # adding vertex shader\n", 154 | " self.program1.addShader(fshader) # adding fragment shader\n", 155 | "\n", 156 | " # bind attribute to a location\n", 157 | " self.program1.bindAttributeLocation(\"aPos\", 0)\n", 158 | "\n", 159 | " # link shader program1\n", 160 | " isLinked = self.program1.link()\n", 161 | " print(\"shader program1 is linked: \", isLinked)\n", 162 | "\n", 163 | " # bind the program1\n", 164 | " self.program1.bind()\n", 165 | "\n", 166 | " # specify uniform value\n", 167 | " colorLoc = self.program1.uniformLocation(\"color\")\n", 168 | " self.program1.setUniformValue(colorLoc,\n", 169 | " self.triangleColor1)\n" 170 | ] 171 | }, 172 | { 173 | "cell_type": "markdown", 174 | "metadata": {}, 175 | "source": [ 176 | "This by itself should also be familiar." 177 | ] 178 | }, 179 | { 180 | "cell_type": "code", 181 | "execution_count": null, 182 | "metadata": {}, 183 | "outputs": [], 184 | "source": [ 185 | "\n", 186 | " # second shader\n", 187 | " shaderName = \"triangle2\"\n", 188 | " vshader = self.loadVertexShader(shaderName)\n", 189 | " fshader = self.loadFragmentShader(shaderName)\n", 190 | "\n", 191 | " #\n", 192 | " self.program2 = QOpenGLShaderProgram(self.context)\n", 193 | " self.program2.addShader(vshader) # adding vertex shader\n", 194 | " self.program2.addShader(fshader) # adding fragment shader\n", 195 | "\n", 196 | " # bind attribute to a location\n", 197 | " self.program2.bindAttributeLocation(\"aPos\", 0)\n", 198 | "\n", 199 | " # link shader program2\n", 200 | " isLinked = self.program2.link()\n", 201 | " print(\"shader program2 is linked: \", isLinked)\n", 202 | "\n", 203 | " # bind the program2\n", 204 | " self.program2.bind()\n", 205 | "\n", 206 | " # specify uniform value\n", 207 | " colorLoc = self.program2.uniformLocation(\"color\")\n", 208 | " self.program2.setUniformValue(colorLoc,\n", 209 | " self.triangleColor2)\n" 210 | ] 211 | }, 212 | { 213 | "cell_type": "markdown", 214 | "metadata": {}, 215 | "source": [ 216 | "Here is a difference. Before we pass on to dealing with specific vao-vbo related to shader program, we arrange the second shader program. Then deal with the vao-vbo, as we see below." 217 | ] 218 | }, 219 | { 220 | "cell_type": "code", 221 | "execution_count": null, 222 | "metadata": {}, 223 | "outputs": [], 224 | "source": [ 225 | "\n", 226 | " # vao\n", 227 | " isVao = self.vao1.create()\n", 228 | " vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao1)\n", 229 | "\n", 230 | " # vbo\n", 231 | " isVbo = self.vbo1.create()\n", 232 | " isBound = self.vbo1.bind()\n", 233 | "\n", 234 | " # check if vao and vbo are created\n", 235 | " print('vao created: ', isVao)\n", 236 | " print('vbo created: ', isVbo)\n", 237 | "\n", 238 | " floatSize = ctypes.sizeof(ctypes.c_float)\n", 239 | "\n", 240 | " # allocate space on buffer\n", 241 | " self.vbo1.allocate(self.vertexData1.tobytes(),\n", 242 | " floatSize * self.vertexData1.size)\n", 243 | " funcs.glEnableVertexAttribArray(0)\n", 244 | " nullptr = VoidPtr(0)\n", 245 | " funcs.glVertexAttribPointer(0,\n", 246 | " 3,\n", 247 | " int(pygl.GL_FLOAT),\n", 248 | " int(pygl.GL_FALSE),\n", 249 | " 3 * floatSize,\n", 250 | " nullptr)\n", 251 | " self.vbo1.release()\n", 252 | " vaoBinder = None\n" 253 | ] 254 | }, 255 | { 256 | "cell_type": "markdown", 257 | "metadata": {}, 258 | "source": [ 259 | "Notice that at the and we unbind the vao-vbo couple that concerned the first triangle data. \n", 260 | "\n", 261 | "Now we pass on to the second one." 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": null, 267 | "metadata": {}, 268 | "outputs": [], 269 | "source": [ 270 | "# second triangle vao vbo\n", 271 | " # vao\n", 272 | " isVao = self.vao2.create()\n", 273 | " vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao2)\n", 274 | "\n", 275 | " # vbo\n", 276 | " isVbo = self.vbo2.create()\n", 277 | " isBound = self.vbo2.bind()\n", 278 | "\n", 279 | " # check if vao and vbo are created\n", 280 | " print('vao created: ', isVao)\n", 281 | " print('vbo created: ', isVbo)\n", 282 | "\n", 283 | " floatSize = ctypes.sizeof(ctypes.c_float)\n", 284 | "\n", 285 | " # allocate space on buffer\n", 286 | " self.vbo2.allocate(self.vertexData2.tobytes(),\n", 287 | " floatSize * self.vertexData2.size)\n", 288 | " funcs.glEnableVertexAttribArray(0)\n", 289 | " nullptr = VoidPtr(0)\n", 290 | " funcs.glVertexAttribPointer(0,\n", 291 | " 3,\n", 292 | " int(pygl.GL_FLOAT),\n", 293 | " int(pygl.GL_FALSE),\n", 294 | " 3 * floatSize,\n", 295 | " nullptr)\n", 296 | " self.vbo2.release()\n", 297 | " self.program2.release()" 298 | ] 299 | }, 300 | { 301 | "cell_type": "markdown", 302 | "metadata": {}, 303 | "source": [ 304 | "As usual at the end we release the data we were dealing with.\n", 305 | "\n", 306 | "This concludes the initialization part. Let's see all of the function." 307 | ] 308 | }, 309 | { 310 | "cell_type": "code", 311 | "execution_count": null, 312 | "metadata": {}, 313 | "outputs": [], 314 | "source": [ 315 | "\n", 316 | " def initializeGL(self):\n", 317 | " print('gl initial')\n", 318 | " print(self.getGlInfo())\n", 319 | " # create context and make it current\n", 320 | " self.context.create()\n", 321 | " self.context.aboutToBeDestroyed.connect(self.cleanUpGl)\n", 322 | "\n", 323 | " # initialize functions\n", 324 | " funcs = self.context.functions()\n", 325 | " funcs.initializeOpenGLFunctions()\n", 326 | " funcs.glClearColor(1, 1, 1, 1)\n", 327 | "\n", 328 | " # deal with shaders\n", 329 | " # first shader\n", 330 | " shaderName = \"triangle\"\n", 331 | " vshader = self.loadVertexShader(shaderName)\n", 332 | " fshader = self.loadFragmentShader(shaderName)\n", 333 | "\n", 334 | " # creating shader program\n", 335 | " self.program1 = QOpenGLShaderProgram(self.context)\n", 336 | " self.program1.addShader(vshader) # adding vertex shader\n", 337 | " self.program1.addShader(fshader) # adding fragment shader\n", 338 | "\n", 339 | " # bind attribute to a location\n", 340 | " self.program1.bindAttributeLocation(\"aPos\", 0)\n", 341 | "\n", 342 | " # link shader program1\n", 343 | " isLinked = self.program1.link()\n", 344 | " print(\"shader program1 is linked: \", isLinked)\n", 345 | "\n", 346 | " # bind the program1\n", 347 | " self.program1.bind()\n", 348 | "\n", 349 | " # specify uniform value\n", 350 | " colorLoc = self.program1.uniformLocation(\"color\")\n", 351 | " self.program1.setUniformValue(colorLoc,\n", 352 | " self.triangleColor1)\n", 353 | "\n", 354 | " # second shader\n", 355 | " shaderName = \"triangle2\"\n", 356 | " vshader = self.loadVertexShader(shaderName)\n", 357 | " fshader = self.loadFragmentShader(shaderName)\n", 358 | "\n", 359 | " #\n", 360 | " self.program2 = QOpenGLShaderProgram(self.context)\n", 361 | " self.program2.addShader(vshader) # adding vertex shader\n", 362 | " self.program2.addShader(fshader) # adding fragment shader\n", 363 | "\n", 364 | " # bind attribute to a location\n", 365 | " self.program2.bindAttributeLocation(\"aPos\", 0)\n", 366 | "\n", 367 | " # link shader program2\n", 368 | " isLinked = self.program2.link()\n", 369 | " print(\"shader program2 is linked: \", isLinked)\n", 370 | "\n", 371 | " # bind the program2\n", 372 | " self.program2.bind()\n", 373 | "\n", 374 | " # specify uniform value\n", 375 | " colorLoc = self.program2.uniformLocation(\"color\")\n", 376 | " self.program2.setUniformValue(colorLoc,\n", 377 | " self.triangleColor2)\n", 378 | "\n", 379 | " # self.useShader(\"triangle\")\n", 380 | "\n", 381 | " # deal with vao and vbo\n", 382 | "\n", 383 | " # create vao and vbo\n", 384 | "\n", 385 | " # vao\n", 386 | " isVao = self.vao1.create()\n", 387 | " vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao1)\n", 388 | "\n", 389 | " # vbo\n", 390 | " isVbo = self.vbo1.create()\n", 391 | " isBound = self.vbo1.bind()\n", 392 | "\n", 393 | " # check if vao and vbo are created\n", 394 | " print('vao created: ', isVao)\n", 395 | " print('vbo created: ', isVbo)\n", 396 | "\n", 397 | " floatSize = ctypes.sizeof(ctypes.c_float)\n", 398 | "\n", 399 | " # allocate space on buffer\n", 400 | " self.vbo1.allocate(self.vertexData1.tobytes(),\n", 401 | " floatSize * self.vertexData1.size)\n", 402 | " funcs.glEnableVertexAttribArray(0)\n", 403 | " nullptr = VoidPtr(0)\n", 404 | " funcs.glVertexAttribPointer(0,\n", 405 | " 3,\n", 406 | " int(pygl.GL_FLOAT),\n", 407 | " int(pygl.GL_FALSE),\n", 408 | " 3 * floatSize,\n", 409 | " nullptr)\n", 410 | " self.vbo1.release()\n", 411 | " vaoBinder = None\n", 412 | "\n", 413 | " # second triangle vao vbo\n", 414 | " # vao\n", 415 | " isVao = self.vao2.create()\n", 416 | " vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao2)\n", 417 | "\n", 418 | " # vbo\n", 419 | " isVbo = self.vbo2.create()\n", 420 | " isBound = self.vbo2.bind()\n", 421 | "\n", 422 | " # check if vao and vbo are created\n", 423 | " print('vao created: ', isVao)\n", 424 | " print('vbo created: ', isVbo)\n", 425 | "\n", 426 | " floatSize = ctypes.sizeof(ctypes.c_float)\n", 427 | "\n", 428 | " # allocate space on buffer\n", 429 | " self.vbo2.allocate(self.vertexData2.tobytes(),\n", 430 | " floatSize * self.vertexData2.size)\n", 431 | " funcs.glEnableVertexAttribArray(0)\n", 432 | " nullptr = VoidPtr(0)\n", 433 | " funcs.glVertexAttribPointer(0,\n", 434 | " 3,\n", 435 | " int(pygl.GL_FLOAT),\n", 436 | " int(pygl.GL_FALSE),\n", 437 | " 3 * floatSize,\n", 438 | " nullptr)\n", 439 | " self.vbo2.release()\n", 440 | " self.program2.release()" 441 | ] 442 | }, 443 | { 444 | "cell_type": "markdown", 445 | "metadata": {}, 446 | "source": [ 447 | "Now let's see how the actual drawing occurs." 448 | ] 449 | }, 450 | { 451 | "cell_type": "code", 452 | "execution_count": null, 453 | "metadata": {}, 454 | "outputs": [], 455 | "source": [ 456 | " def paintGL(self):\n", 457 | " \"drawing loop\"\n", 458 | " funcs = self.context.functions()\n", 459 | "\n", 460 | " # clean up what was drawn\n", 461 | " funcs.glClear(pygl.GL_COLOR_BUFFER_BIT)\n", 462 | "\n", 463 | " # actual drawing\n", 464 | " \n", 465 | " # bind the object you want to draw\n", 466 | " vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao1)\n", 467 | " # activate its shader\n", 468 | " self.program1.bind()\n", 469 | " # presto\n", 470 | " funcs.glDrawArrays(pygl.GL_TRIANGLES, # mode\n", 471 | " 0, # first\n", 472 | " 3) # count\n", 473 | " # unbind the object you've just drawn\n", 474 | " vaoBinder = None\n", 475 | " # and release its shader program\n", 476 | " self.program1.release()\n", 477 | " \n", 478 | " # now bind the next object you would like to draw\n", 479 | " vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao2)\n", 480 | " \n", 481 | " # activate its shaders\n", 482 | " self.program2.bind()\n", 483 | " # presto!\n", 484 | " funcs.glDrawArrays(pygl.GL_TRIANGLES, # mode\n", 485 | " 0, # first\n", 486 | " 3) # count\n", 487 | " # unbind the object you've just drawn\n", 488 | " vaoBinder = None\n", 489 | " # release the program\n", 490 | " self.program2.release()\n" 491 | ] 492 | }, 493 | { 494 | "cell_type": "markdown", 495 | "metadata": {}, 496 | "source": [ 497 | "And that's it. Now you know what to do if you need multiple VAOs-VBOs in your code. In most cases, you would require such a thing when you need different shaped objects, like a rectangle and a circle at the same time for example." 498 | ] 499 | } 500 | ], 501 | "metadata": { 502 | "kernelspec": { 503 | "display_name": "Python 3", 504 | "language": "python", 505 | "name": "python3" 506 | }, 507 | "language_info": { 508 | "codemirror_mode": { 509 | "name": "ipython", 510 | "version": 3 511 | }, 512 | "file_extension": ".py", 513 | "mimetype": "text/x-python", 514 | "name": "python", 515 | "nbconvert_exporter": "python", 516 | "pygments_lexer": "ipython3", 517 | "version": "3.7.3" 518 | } 519 | }, 520 | "nbformat": 4, 521 | "nbformat_minor": 2 522 | } 523 | -------------------------------------------------------------------------------- /tutorials/05-cube/CubeTutorial.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Draw a Cube with PySide2 OpenGL" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "Welcome to PySide2 OpenGL cube tutorial. \n", 15 | "\n", 16 | "Why draw a cube ? So far we had seen only 2d rendering. \n", 17 | "A cube introduces us to 3d rendering in OpenGL. \n", 18 | "With respect to 2d rendering it introduces several additional configurations that need to be taken into account which are tied to the very nature of 3d objects. These are:\n", 19 | "\n", 20 | "- 3d objects are contained in a 3d world.\n", 21 | "- 3d objects are observed from somewhere inside the world.\n", 22 | "- Observation process transforms the 3d object to a 2d object.\n", 23 | "\n", 24 | "Now these three facts obliges to use three additional objects in shaders to render a 3d object:\n", 25 | "\n", 26 | "- **model** matrix 4x4: determines the position of the object in a 3d world\n", 27 | "- **view** matrix 4x4: transforms the coordinates of objects in a 3d world with respect to the camera/viewer position\n", 28 | "- **projection** matrix 4x4: determines how object(s) would appear with respect to the position and the direction of the viewer.\n", 29 | "\n", 30 | "It should be more or less clear that 3d rendering needs a little more consideration and effort. \n", 31 | "\n", 32 | "Let's see the final form of the application." 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": 2, 38 | "metadata": {}, 39 | "outputs": [ 40 | { 41 | "data": { 42 | "text/plain": [ 43 | "CompletedProcess(args=['python', 'app.py'], returncode=0)" 44 | ] 45 | }, 46 | "execution_count": 2, 47 | "metadata": {}, 48 | "output_type": "execute_result" 49 | } 50 | ], 51 | "source": [ 52 | "import subprocess\n", 53 | "\n", 54 | "subprocess.run([\"python\", \"app.py\"])" 55 | ] 56 | }, 57 | { 58 | "cell_type": "markdown", 59 | "metadata": {}, 60 | "source": [ 61 | "All right! As usual, I skip the window code and concentrate on the GL widget instead.\n", 62 | "\n", 63 | "Let's see the constructor of our widget." 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": null, 69 | "metadata": {}, 70 | "outputs": [], 71 | "source": [ 72 | "class CubeGL(QOpenGLWidget):\n", 73 | " \"Cube gl widget\"\n", 74 | "\n", 75 | " def __init__(self, parent=None):\n", 76 | " QOpenGLWidget.__init__(self, parent)\n", 77 | "\n", 78 | " ############# Diff ###############\n", 79 | " # We represent the viewer as a camera\n", 80 | " # The code can be a little strange\n", 81 | " # to those who are not used to graphics\n", 82 | " # programming. In our helper code,\n", 83 | " # we had provided a pure python \n", 84 | " # implementation and a Qt version\n", 85 | " # which uses qt objects.\n", 86 | " \n", 87 | " # The values we set here are important\n", 88 | " # for setting up the view matrix\n", 89 | " # camera\n", 90 | " self.camera = QtCamera()\n", 91 | " self.camera.position = QVector3D(0.0, 0.0, 3.0)\n", 92 | " self.camera.front = QVector3D(0.0, 0.0, -1.0)\n", 93 | " self.camera.up = QVector3D(0.0, 1.0, 0.0)\n", 94 | "\n", 95 | " # shaders etc\n", 96 | " tutoTutoDir = os.path.dirname(__file__)\n", 97 | " tutoPardir = os.path.join(tutoTutoDir, os.pardir)\n", 98 | " tutoPardir = os.path.realpath(tutoPardir)\n", 99 | " mediaDir = os.path.join(tutoPardir, \"media\")\n", 100 | " shaderDir = os.path.join(mediaDir, \"shaders\")\n", 101 | "\n", 102 | " availableShaders = [\"cube\"]\n", 103 | " self.shaders = {\n", 104 | " name: {\n", 105 | " \"fragment\": os.path.join(shaderDir, name + \".frag\"),\n", 106 | " \"vertex\": os.path.join(shaderDir, name + \".vert\")\n", 107 | " } for name in availableShaders\n", 108 | " }\n", 109 | " self.core = \"--coreprofile\" in QCoreApplication.arguments()\n", 110 | " imdir = os.path.join(mediaDir, \"images\")\n", 111 | " imFName = \"im\"\n", 112 | " imageFile1 = os.path.join(imdir, imFName + \"0.png\")\n", 113 | " self.image1 = QImage(imageFile1).mirrored()\n", 114 | " \n", 115 | " ################ Diff #################\n", 116 | " # We are going to use 2 textures.\n", 117 | " # we shall see usage differences\n", 118 | " # as we go along the code.\n", 119 | " imageFile2 = os.path.join(imdir, imFName + \"1.png\")\n", 120 | " self.image2 = QImage(imageFile2).mirrored()\n", 121 | "\n", 122 | " # opengl data related\n", 123 | " self.context = QOpenGLContext()\n", 124 | " self.vao = QOpenGLVertexArrayObject()\n", 125 | " self.vbo = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer)\n", 126 | " self.program = QOpenGLShaderProgram()\n", 127 | " self.texture1 = None\n", 128 | " self.texture2 = None\n", 129 | " self.texUnit1 = 0\n", 130 | " self.texUnit2 = 1\n", 131 | "\n", 132 | " ############## Diff ##############\n", 133 | " # cube is made up of 6 sides each side \n", 134 | " # is a square which is made up of 2\n", 135 | " # triangles and for each triangle we\n", 136 | " # specify 3 corners\n", 137 | " self.cubeVertices = np.array([\n", 138 | " # pos vec3 || texcoord vec2\n", 139 | " -0.5, -0.5, -0.5, 0.0, 0.0,\n", 140 | " 0.5, -0.5, -0.5, 1.0, 0.0,\n", 141 | " 0.5, 0.5, -0.5, 1.0, 1.0,\n", 142 | " 0.5, 0.5, -0.5, 1.0, 1.0,\n", 143 | " -0.5, 0.5, -0.5, 0.0, 1.0,\n", 144 | " -0.5, -0.5, -0.5, 0.0, 0.0,\n", 145 | "\n", 146 | " -0.5, -0.5, 0.5, 0.0, 0.0,\n", 147 | " 0.5, -0.5, 0.5, 1.0, 0.0,\n", 148 | " 0.5, 0.5, 0.5, 1.0, 1.0,\n", 149 | " 0.5, 0.5, 0.5, 1.0, 1.0,\n", 150 | " -0.5, 0.5, 0.5, 0.0, 1.0,\n", 151 | " -0.5, -0.5, 0.5, 0.0, 0.0,\n", 152 | "\n", 153 | " -0.5, 0.5, 0.5, 1.0, 0.0,\n", 154 | " -0.5, 0.5, -0.5, 1.0, 1.0,\n", 155 | " -0.5, -0.5, -0.5, 0.0, 1.0,\n", 156 | " -0.5, -0.5, -0.5, 0.0, 1.0,\n", 157 | " -0.5, -0.5, 0.5, 0.0, 0.0,\n", 158 | " -0.5, 0.5, 0.5, 1.0, 0.0,\n", 159 | "\n", 160 | " 0.5, 0.5, 0.5, 1.0, 0.0,\n", 161 | " 0.5, 0.5, -0.5, 1.0, 1.0,\n", 162 | " 0.5, -0.5, -0.5, 0.0, 1.0,\n", 163 | " 0.5, -0.5, -0.5, 0.0, 1.0,\n", 164 | " 0.5, -0.5, 0.5, 0.0, 0.0,\n", 165 | " 0.5, 0.5, 0.5, 1.0, 0.0,\n", 166 | "\n", 167 | " -0.5, -0.5, -0.5, 0.0, 1.0,\n", 168 | " 0.5, -0.5, -0.5, 1.0, 1.0,\n", 169 | " 0.5, -0.5, 0.5, 1.0, 0.0,\n", 170 | " 0.5, -0.5, 0.5, 1.0, 0.0,\n", 171 | " -0.5, -0.5, 0.5, 0.0, 0.0,\n", 172 | " -0.5, -0.5, -0.5, 0.0, 1.0,\n", 173 | "\n", 174 | " -0.5, 0.5, -0.5, 0.0, 1.0,\n", 175 | " 0.5, 0.5, -0.5, 1.0, 1.0,\n", 176 | " 0.5, 0.5, 0.5, 1.0, 0.0,\n", 177 | " 0.5, 0.5, 0.5, 1.0, 0.0,\n", 178 | " -0.5, 0.5, 0.5, 0.0, 0.0,\n", 179 | " -0.5, 0.5, -0.5, 0.0, 1.0\n", 180 | " ], dtype=ctypes.c_float\n", 181 | " )\n", 182 | " ############ Diff ##############\n", 183 | " # As we can see there are 10 cubes.\n", 184 | " # the cubes shape is described by the\n", 185 | " # cubeVertices.\n", 186 | " # We are going to render in the world.\n", 187 | " # These are their positions.\n", 188 | " self.cubeCoords = [\n", 189 | " QVector3D(0.0, 0.0, 0.0),\n", 190 | " QVector3D(2.0, 5.0, -15.0),\n", 191 | " QVector3D(-1.5, -2.2, -2.5),\n", 192 | " QVector3D(-3.8, -2.0, -12.3),\n", 193 | " QVector3D(2.4, -0.4, -3.5),\n", 194 | " QVector3D(-1.7, 3.0, -7.5),\n", 195 | " QVector3D(1.3, -2.0, -2.5),\n", 196 | " QVector3D(1.5, 2.0, -2.5),\n", 197 | " QVector3D(1.5, 0.2, -1.5),\n", 198 | " QVector3D(-1.3, 1.0, -1.5)\n", 199 | " ]" 200 | ] 201 | }, 202 | { 203 | "cell_type": "markdown", 204 | "metadata": {}, 205 | "source": [ 206 | "Please inspect the code of `camera.py` when you have the time.\n", 207 | "The pure implementation should give you a rough idea about how everything works.\n", 208 | "Qt implementation simply facilitates the operations defined in the pure one by using qt objects.\n", 209 | "\n", 210 | "You should note that it is not very feasible to draw anything that is not geometric by specifying the vertices by hand. \n", 211 | "If you are looking to render real objects you should think about using a 3d modelling software like blender for example.\n", 212 | "\n", 213 | "Now let's see the initialization code." 214 | ] 215 | }, 216 | { 217 | "cell_type": "code", 218 | "execution_count": null, 219 | "metadata": {}, 220 | "outputs": [], 221 | "source": [ 222 | " def initializeGL(self):\n", 223 | " print('gl initial')\n", 224 | " print(self.getGlInfo())\n", 225 | "\n", 226 | " # create context and make it current\n", 227 | " self.context.create()\n", 228 | " self.context.aboutToBeDestroyed.connect(\n", 229 | " self.cleanUpGl)\n", 230 | "\n", 231 | " # initialize functions\n", 232 | " funcs = self.context.functions()\n", 233 | " funcs.initializeOpenGLFunctions()\n", 234 | " funcs.glClearColor(0.0, 0.4, 0.4, 0)\n", 235 | " ################## Diff ####################\n", 236 | " # This readies opengl to render 3d graphics\n", 237 | " funcs.glEnable(pygl.GL_DEPTH_TEST)\n", 238 | " #\n", 239 | " funcs.glEnable(pygl.GL_TEXTURE_2D)\n", 240 | "\n", 241 | " # cube shader\n", 242 | " self.program = QOpenGLShaderProgram(\n", 243 | " self.context\n", 244 | " )\n", 245 | " vshader = self.loadVertexShader(\"cube\")\n", 246 | " fshader = self.loadFragmentShader(\"cube\")\n", 247 | " self.program.addShader(vshader) # adding vertex shader\n", 248 | " self.program.addShader(fshader) # adding fragment shader\n", 249 | " self.program.bindAttributeLocation(\n", 250 | " \"aPos\", 0)\n", 251 | " self.program.bindAttributeLocation(\n", 252 | " \"aTexCoord\", 1)\n", 253 | "\n", 254 | " isLinked = self.program.link()\n", 255 | " print(\"cube shader program is linked: \",\n", 256 | " isLinked)\n", 257 | " # bind the program\n", 258 | " self.program.bind()\n", 259 | "\n", 260 | " ############### Diff ###############\n", 261 | " # We define the projection matrix here\n", 262 | " # for its function see our introduction\n", 263 | " # set projection matrix. Please do note\n", 264 | " # that we are using a perspective \n", 265 | " # projection yet this is not the only\n", 266 | " # projection type that is available\n", 267 | " projectionMatrix = QMatrix4x4()\n", 268 | " projectionMatrix.perspective(\n", 269 | " self.camera.zoom,\n", 270 | " self.width() / self.height(),\n", 271 | " 0.2, 100.0)\n", 272 | " \n", 273 | " # we set its value just like any other\n", 274 | " # uniform\n", 275 | " self.program.setUniformValue('projection',\n", 276 | " projectionMatrix)\n", 277 | "\n", 278 | " ############## Diff ##################\n", 279 | " # As stated above, camera, being a fps\n", 280 | " # style camera, gives us the matrix\n", 281 | " # that help us to transform all the other\n", 282 | " # coordinates with respect to the viewer.\n", 283 | " # Meaning that the viewer is considered \n", 284 | " # as the center and all other coordinates\n", 285 | " # are redefined with respect to that coordinate\n", 286 | " # Notice that this does not mean we have to redefine\n", 287 | " # each object individually we just need to \n", 288 | " # have the matrix that would give us \n", 289 | " # the stated coordinate when we apply\n", 290 | " # the transformation.\n", 291 | " # set view/camera matrix\n", 292 | " viewMatrix = self.camera.getViewMatrix()\n", 293 | " self.program.setUniformValue('view',\n", 294 | " viewMatrix)\n", 295 | " \n", 296 | " ################# Diff ####################\n", 297 | " # The numbers set here are units for the samplers\n", 298 | " # they are going to be important when we are creating\n", 299 | " # the textures\n", 300 | " self.program.setUniformValue('myTexture1', self.texUnit1)\n", 301 | " self.program.setUniformValue('myTexture2', self.texUnit2)\n", 302 | " #\n", 303 | " # deal with vaos and vbo\n", 304 | " # vbo\n", 305 | " isVbo = self.vbo.create()\n", 306 | " isVboBound = self.vbo.bind()\n", 307 | "\n", 308 | " floatSize = ctypes.sizeof(ctypes.c_float)\n", 309 | "\n", 310 | " # allocate space on vbo buffer\n", 311 | " self.vbo.allocate(\n", 312 | " self.cubeVertices.tobytes(),\n", 313 | " floatSize * self.cubeVertices.size)\n", 314 | " \n", 315 | " # contary to texture tutorial\n", 316 | " # we are going to reuse the old method \n", 317 | " # for creating the vertex array objects\n", 318 | " self.vao.create()\n", 319 | " \n", 320 | " vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao)\n", 321 | " funcs.glEnableVertexAttribArray(0) # viewport\n", 322 | " funcs.glVertexAttribPointer(0,\n", 323 | " 3,\n", 324 | " int(pygl.GL_FLOAT),\n", 325 | " int(pygl.GL_FALSE),\n", 326 | " 5 * floatSize,\n", 327 | " VoidPtr(0)\n", 328 | " )\n", 329 | " funcs.glEnableVertexAttribArray(1)\n", 330 | " funcs.glVertexAttribPointer(1,\n", 331 | " 2,\n", 332 | " int(pygl.GL_FLOAT),\n", 333 | " int(pygl.GL_FALSE),\n", 334 | " 5 * floatSize,\n", 335 | " VoidPtr(3 * floatSize)\n", 336 | " )\n", 337 | " # deal with textures\n", 338 | " # first texture\n", 339 | " self.texture1 = QOpenGLTexture(\n", 340 | " QOpenGLTexture.Target2D)\n", 341 | " self.texture1.create()\n", 342 | " ################# Diff ##################\n", 343 | " # We bind the texture to a specific\n", 344 | " # unit. This is necessary for the\n", 345 | " # sampler. \n", 346 | " self.texture1.bind(self.texUnit1)\n", 347 | " self.texture1.setData(self.image1)\n", 348 | " self.texture1.setMinMagFilters(\n", 349 | " QOpenGLTexture.Nearest,\n", 350 | " QOpenGLTexture.Nearest)\n", 351 | " self.texture1.setWrapMode(\n", 352 | " QOpenGLTexture.DirectionS,\n", 353 | " QOpenGLTexture.Repeat)\n", 354 | " self.texture1.setWrapMode(\n", 355 | " QOpenGLTexture.DirectionT,\n", 356 | " QOpenGLTexture.Repeat)\n", 357 | "\n", 358 | " # second texture\n", 359 | " self.texture2 = QOpenGLTexture(\n", 360 | " QOpenGLTexture.Target2D)\n", 361 | " self.texture2.create()\n", 362 | " self.texture2.bind(self.texUnit2)\n", 363 | " self.texture2.setData(self.image2)\n", 364 | " self.texture2.setMinMagFilters(\n", 365 | " QOpenGLTexture.Linear,\n", 366 | " QOpenGLTexture.Linear)\n", 367 | " self.texture2.setWrapMode(\n", 368 | " QOpenGLTexture.DirectionS,\n", 369 | " QOpenGLTexture.Repeat)\n", 370 | " self.texture2.setWrapMode(\n", 371 | " QOpenGLTexture.DirectionT,\n", 372 | " QOpenGLTexture.Repeat)\n", 373 | "\n", 374 | " self.vbo.release()\n", 375 | " vaoBinder = None\n", 376 | " print(\"gl initialized\")" 377 | ] 378 | }, 379 | { 380 | "cell_type": "markdown", 381 | "metadata": {}, 382 | "source": [ 383 | "It might be a little daunting to take all that at once.\n", 384 | "But most of it should be familiar by now if you have followed previous tutorials.\n", 385 | "\n", 386 | "Now let's see the drawing loop." 387 | ] 388 | }, 389 | { 390 | "cell_type": "code", 391 | "execution_count": null, 392 | "metadata": {}, 393 | "outputs": [], 394 | "source": [ 395 | " def paintGL(self):\n", 396 | " \"drawing loop\"\n", 397 | " funcs = self.context.functions()\n", 398 | "\n", 399 | " # clean up what was drawn\n", 400 | " ############### Diff ##############\n", 401 | " # Notice we clear the depth buffer \n", 402 | " # as well\n", 403 | " funcs.glClear(\n", 404 | " pygl.GL_COLOR_BUFFER_BIT | pygl.GL_DEPTH_BUFFER_BIT\n", 405 | " )\n", 406 | " self.vao.bind()\n", 407 | " self.vbo.bind()\n", 408 | "\n", 409 | " # actual drawing\n", 410 | " self.program.bind()\n", 411 | " \n", 412 | " ################## Diff ###################\n", 413 | " # This is the first time we are drawing\n", 414 | " # several objects. So we are going to call \n", 415 | " # several glDrawArrays several times.\n", 416 | " # Notice also that we are not changing the\n", 417 | " # shape of the cube we are simply changing\n", 418 | " # its rotation. The translate function\n", 419 | " # simply multiplies the model matrix\n", 420 | " # with a translation 4x4 matrix constructed\n", 421 | " # from the position 3d vector. Translation\n", 422 | " # matrix is essentially same except for\n", 423 | " # its last column whose first three rows\n", 424 | " # are made up of vectors components\n", 425 | " rotvec = QVector3D(0.7, 0.2, 0.5)\n", 426 | " # bind textures\n", 427 | " for i, pos in enumerate(self.cubeCoords):\n", 428 | " #\n", 429 | " cubeModel = QMatrix4x4()\n", 430 | " cubeModel.translate(pos)\n", 431 | " angle = 30 * i\n", 432 | " cubeModel.rotate(angle, rotvec)\n", 433 | " self.program.setUniformValue(\"model\",\n", 434 | " cubeModel)\n", 435 | " self.texture1.bind(self.texUnit1)\n", 436 | " self.texture2.bind(self.texUnit2)\n", 437 | " funcs.glDrawArrays(\n", 438 | " pygl.GL_TRIANGLES,\n", 439 | " 0,\n", 440 | " self.cubeVertices.size\n", 441 | " )\n", 442 | " self.vbo.release()\n", 443 | " self.program.release()\n", 444 | " self.texture1.release()\n", 445 | " self.texture2.release()" 446 | ] 447 | }, 448 | { 449 | "cell_type": "markdown", 450 | "metadata": {}, 451 | "source": [ 452 | "That's it. \n", 453 | "\n", 454 | "We have covered a lot of grounds in this tutorial. \n", 455 | "It is normal if you are a bit lost.\n", 456 | "\n", 457 | "If you are not sure how all transformations work,\n", 458 | "checkout the section from LearnOpenGL. \n", 459 | "\n", 460 | "If you want to know more about how a camera works,\n", 461 | "checkout from the same." 462 | ] 463 | } 464 | ], 465 | "metadata": { 466 | "kernelspec": { 467 | "display_name": "Python 3", 468 | "language": "python", 469 | "name": "python3" 470 | }, 471 | "language_info": { 472 | "codemirror_mode": { 473 | "name": "ipython", 474 | "version": 3 475 | }, 476 | "file_extension": ".py", 477 | "mimetype": "text/x-python", 478 | "name": "python", 479 | "nbconvert_exporter": "python", 480 | "pygments_lexer": "ipython3", 481 | "version": "3.7.3" 482 | } 483 | }, 484 | "nbformat": 4, 485 | "nbformat_minor": 2 486 | } 487 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------