Coder Social home page Coder Social logo

rougier / python-opengl Goto Github PK

View Code? Open in Web Editor NEW
596.0 26.0 138.0 67.08 MB

An open access book on Python, OpenGL and Scientific Visualization, Nicolas P. Rougier, 2018

Home Page: http://www.labri.fr/perso/nrougier/python-opengl

License: Other

CSS 1.78% HTML 64.53% Python 32.81% TeX 0.82% Shell 0.03% GLSL 0.04%
book python opengl dataviz open-access gpu shaders

python-opengl's Introduction

Python & OpenGL for Scientific Visualization

Copyright (c) 2018 Nicolas P. Rougier
License: Creative Commons Attribution 4.0 International (CC BY-NC-SA 4.0)
Website: http://www.labri.fr/perso/nrougier/python-opengl

Python and OpenGL have a long but complicated story. It used to be really easy to program something using the fixed-pipeline and libraries such as Pyglet but things became more difficult with the introduction of the dynamic graphic pipeline in 2004. The goal of this book is to reconciliate Python programmers with OpenGL, providing both an introduction to modern OpenGL and a set of basic and advanced techniques in order to achieve both fast, scalable & beautiful scientific visualizations. The book uses the GLES 2.0 API which is the most simple API for accessing the programmable graphic pipeline. It does not cover up-to-date OpenGL techniques but it is sufficient to achieve great visualisation. In fact, modern OpenGL allows to control pretty much everything in the pipeline and the goal of this book is to explain several techniques dedicated to scientific visualisation such as isolines, markers, colormaps, arbitrary transformations but there are actually many more techniques to be discovered and explained in this open-access book. And of course, everything will be fast and beautiful.

image

This book is open-access (i.e. it's free to read at this address) because I believe knowledge should be free. However, if you think the book is worth a few dollars (5€ or 10€), you can use Paypal to make payment. This money will help me to travel to Python conferences and to write other books as well. If you don't have money, it's fine. Just enjoy the book and spread the word about it.

python-opengl's People

Contributors

a-anjos avatar abey79 avatar bluebarnacles avatar borelconstruction avatar d-v-b avatar dankolbman avatar dbarbier avatar encukou avatar gcalmettes avatar jackvdm avatar jeremyfix avatar nsrahmad avatar pelegs avatar plops avatar rasql avatar rougier avatar silktown-software avatar stuaxo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-opengl's Issues

linestrip-3d.py

Hi,

In linestrip-3d.py, when I changed n=2048 to n=3, that is, two jointed segments spinning in 3D space, I get the following "faded", tapered ends.
Peek 2021-03-23 16-04

Looking at the code, I suspect it is because linelength was calculated in model space but it is used like a screen space quantity in the shader.

For example, in the vertex shader, the code:
"v_uv.x = linelength+w;"
sums together a model space and a screen space quantity (w). As a result, v_uv.x doesn't interpolate exactly to the start/end of the polyline.

Any suggestion on how to fix it?

code error in chapter 9 linestrip

It seems to draw nothing if points at [[10., 4.], [20., 4.], [15., 4.]]

The code is in below.

uniform vec2 resolution;
uniform float antialias, thickness, linelength;
attribute vec4 prev, curr, next;
varying vec2 v_uv;

void main() {
    float w = thickness/2.0 + antialias;
    vec2 p;
    vec2 t0 = normalize(curr.xy - prev.xy);
    vec2 t1 = normalize(next.xy - curr.xy);
    vec2 n0 = vec2(-t0.y, t0.x);
    vec2 n1 = vec2(-t1.y, t1.x);

    // Cap at start
    if (prev.xy == curr.xy) {
        v_uv = vec2(-w, curr.z*w);
        p = curr.xy - w*t1 + curr.z*w*n1;
    // Cap at end
    } else if (curr.xy == next.xy) {
        v_uv = vec2(linelength+w, curr.z*w);
        p = curr.xy + w*t0 + curr.z*w*n0;
    // Body
    } else {
        vec2 miter = normalize(n0 + n1);
        float dy = w / dot(miter, n1);
        v_uv = vec2(curr.w, curr.z*w);
        p = curr.xy + dy*curr.z*miter;
    }
    gl_Position = vec4(2.0*p/resolution-1.0, 0.0, 1.0);
}

I guess it happened when points previous, current, next are collinear and the next point's x or y less than current point.

Another case: The drawing of points [[453, 138], [647, 137], [453, 139]] is weird. And points [[453, 138], [647, 137], [453, 138]] draw nothing.

As many --> as much

In 2.2.2 (Buffers): "[...] free to use as many information you may need [...]", should probably be "[...] free to use as much information you may need".

Typo section 3.1.3

In the second paragraph, might is spelled incorrectly and using is written twice.

Transparent cube surface, it is a bug?

Hi,
I'm a newbie of OpenGL and glumpy. When I try to run the code in chapter5, such as outlined-cube.py and textured-cube.py, I found that my cube looks like different to the images in the tutorial. It looks like has transparent surface. I do n’t know what went wrong

Here is my screenshot gif:
ezgif-6-53614f765a5c

My environment:

Windows10 WSL Ubuntu 16.04
Display with Xming X11

Python: 3.7.6
glumpy: 1.0.6
pyopengl: 3.1.5
triangle: 20200404

numpy --> np

In 2.2.2. (Buffers), python code snippet:

data = numpy.zeros(4, dtype = [ ("position", np.float32, 3),
                                ("color",    np.float32, 4)] )

The first time a numpy structure is used, it is called with the name numpy (numpy.zeros), while later numpy structures are called with the abbreviation np (np.float32, specifically).

These calls should all be uniform. As the preface states that numpy is imported as import numpy as np, numpy.zeros should be changed to np.zeros.

Edit: this also repeats in 2.2.3 (Variables).

typos

5.1: wpuld->would
...you should also realize there is no way to organize our vertices into a triangle strip that wpuld describe our cube...

Thanks for this wonderful book!

Suggestion: don't use `import scipy as sp` as a convention.

Nicolas, this looks like a fantastic book. Thanks for sharing it.

I have one suggestion. In the "Conventions" section of the Preface, you include

import scipy as sp

as one of the imports. In fact, there is almost never a good reason to do this. All the "good stuff" in scipy is in the subpackages, and these must be explicitly imported (e.g. import scipy.ndimage, or common variations such as from scipy import ndimage, import scipy.ndimage as ndi, etc.).

The top level scipy namespace imports names from numpy, so you could use names such as sp.array and sp.linspace, but a better style is to just use the numpy namespace for that. I think many SciPy and NumPy developers now think that importing all of numpy into the scipy namespace was an API mistake, and using the scipy namespace that way should be discouraged. The only reason I can think of for ever importing just the top level name scipy is to access the version as scipy.__version__, and that's not a sufficient reason for including its import in the conventions for your book. So you could (and probably should) drop the line import scipy as sp from your list of conventions.

Non-compiling example GLSL code section 3.2.6 (fix included)

In section 3.2.6, in the second code section the GLSL for the fragment shader:

varying vec4 v_color;
void main()
{
  gl_FragColor = color;
}

I think it should be gl_FragColor = v_color
I'm 100% new to opengl, and kinda new to python, this tripped me up for a while.

I think I have a slightly better sense of declaring input and output arguments to shaders look like (not exactly though) after having fiddled with that code until it worked.

I would have been able to proceed if the code worked though. :)

GLError(err = 1282, description = b'invalid operation', baseOperation = glPixelStorei, cArguments = (GL_UNPACK_ALIGNMENT, 1))

The page code with no content just a glumpy import and an "app.run":


from glumpy import app

Run the app

app.run()


The error:
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.

=== RESTART: C:\Users\jeff5\Desktop\Python\OpenGL_Exercises\Example1-2.py ===
[i] Running at 60 frames/second
Traceback (most recent call last):
File "C:\Users\jeff5\Desktop\Python\OpenGL_Exercises\Example1-2.py", line 11, in
app.run()
File "C:\Users\jeff5\AppData\Roaming\Python\Python36\site-packages\glumpy\app_init_.py", line 302, in run
clock = init(clock=clock, framerate=framerate, backend=backend)
File "C:\Users\jeff5\AppData\Roaming\Python\Python36\site-packages\glumpy\app_init_.py", line 241, in init
gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1)
File "C:\Users\jeff5\AppData\Roaming\Python\Python36\site-packages\OpenGL\platform\baseplatform.py", line 405, in call
return self( *args, **named )
File "C:\Users\jeff5\AppData\Roaming\Python\Python36\site-packages\OpenGL\error.py", line 232, in glCheckError
baseOperation = baseOperation,
OpenGL.error.GLError: GLError(
err = 1282,
description = b'invalid operation',
baseOperation = glPixelStorei,
cArguments = (GL_UNPACK_ALIGNMENT, 1)
)

The offending code section:
240 # OpenGL Initialization
241 gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1)
242 gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, 1)
243 gl.glEnable(gl.GL_VERTEX_PROGRAM_POINT_SIZE)
244 gl.glEnable(gl.GL_POINT_SPRITE)
245 gl.glEnable(gl.GL_BLEND)
246 gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

If 241 is commented out then 242 errors out and so on. The "gl" library is loading as a simple print statement at the top of the library successfully displayed.

Code for Keyboard Escape close doesn't work in Section 3.8

I've been following through your python book this morning and the following code doesn't work correctly:

def keyboard( key, x, y ):
    if key == b'\x1b':
        sys.exit()

It produces an error (show below) and leaves the window open:

/home/lrobbins/git/silktown/py_opengl/venv/bin/python /home/lrobbins/git/silktown/py_opengl/main.py
Exception ignored on calling ctypes callback function: <function keyboard at 0x7f474a4ad430>
Traceback (most recent call last):
  File "/home/lrobbins/git/silktown/py_opengl/main.py", line 19, in keyboard
    sys.exit()
SystemExit: 

From doing a web search it appears that you need to call glutDestroyWindow with a reference to the window itself.

I modified the example code in section 3.8 to the following:

import OpenGL.GL as gl
import OpenGL.GLUT as glut

window = None


def display():
    glut.glutSwapBuffers()


def reshape(width, height):
    gl.glViewport(0, 0, width, height)


def keyboard(key, x, y):
    if key == b'\x1b':
        glut.glutDestroyWindow(window)


if __name__ == '__main__':
    glut.glutInit()
    glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA)
    window = glut.glutCreateWindow('Hello World')
    glut.glutReshapeWindow(512, 512)
    glut.glutReshapeFunc(reshape)
    glut.glutDisplayFunc(display)
    glut.glutKeyboardFunc(keyboard)
    glut.glutMainLoop()

Which works correctly.

3.2 The hard way

Hi Nicolas, I just noticed that the byte string in the if statement of the demo code should be if key == b'\x1b':rather than if key == 'b'\x1b':.

GPU or CPU?

I believe that, instead of:
"The idea of modern GL is that vertices are stored on the GPU and need to be uploaded to the GPU before rendering."
you might mean:
"The idea of modern GL is that vertices are stored on the CPU and need to be uploaded to the GPU before rendering."

Mirror on github pages?

Excellent work, and thank you for sharing it! The hosted version at http://www.labri.fr/perso/nrougier/python-opengl seems to be getting a lot of traffic, such that loading the pages from the U.S. can take 15 sec+. Since the HTML and assets are part of your repo, have you considered using Github Pages to host it? The default setting – Use the master branch for Github pages – would host the book at:

https://rougier.github.io/python-opengl/book.html

Just to test it out, I forked your repo and enabled Github Pages, and this is what it looks like:

https://blahs555.github.io/python-opengl/book.html

Assuming you want Google's crawler to give your original domain the SEO credit for your work, you can always add a link canonical meta tag to the book.html:

<link rel="canonical" href="https://www.labri.fr/perso/nrougier/python-opengl/" />

X-axis rotation

Hello Nicolas,

I have the feeling the cos/sin terms should be shifted by one column to the left.
For d=0 we should obtain the identity matrix.

┌                    ┐   ┌   ┐   ┌                                 ┐
│   1       0    0 0 │ * │ x │ = │      1*x      + 0*y + 0*z + 0*0 │
│ cos(d) -sin(d) 0 0 │   │ y │   │ cos(d)*x - sin(d)*y + 0*z + 0*0 │
│ sin(d)  cos(d) 0 0 │   │ z │   │ sin(d)*x + cos(d)*y + 0*z + 0*0 │
│   0       0    0 1 │   │ 1 │   │      0*x      + 0*y + 0*z + 1*1 │
└                    ┘   └   ┘   └                                 ┘

should be like this
┌                      ┐   ┌   ┐ 
│   1       0    0   0 │ * │ x │ =
│   0 cos(d) -sin(d) 0 │   │ y │  
│   0 sin(d) cos(d)  0 │   │ z │  
│   0       0    0   1 │   │ 1 │   │    
└                      ┘   └   ┘   

The rest of the book

I didn't mean to be intrusive, but I was just wondering if you plan to continue working on the book to finish the rest of the chapters. I really enjoy it, and I would definitely love to see the continuation.

In any case, love you work!

2.3.3 - english issue on note

Hi,
Where it reads:
"Even though glumpy and vispy shares a number of concept, they are different."
I believe it should read:
"Even though glumpy and vispy share a number of concepts, they are different."
Cheers,

from glumpy.ext import freetype - RuntimeError('Freetype library not found')

Hi,
I am new to Python programming. I am trying to work through this online book:
http://www.labri.fr/perso/nrougier/python-opengl/
I have installed the libraries it recommends.
Python 3.6.0
Numpy 1.12.0
Scipy 0.18.1
Cython 0.25.2
Triangle 20170106
Glumpy 1.0.6

My Versions:
Python 3.6.5
numpy (1.14.5)
scipy (1.1.0)
Cython (0.28.3)
triangle (20170429)
glumpy (1.0.6)

I am getting a lot of errors from the glumpy library. It started with freeType. An example error:

File "C:\Users\jeff5\AppData\Roaming\Python\Python36\site-packages\glumpy\ext\freetype\__init__.py", line 49, in <module>
    raise RuntimeError('Freetype library not found')
RuntimeError: Freetype library not found

The code was breaking on the line:

from glumpy.ext import freetype

This error is occurring for all imported libraries loading by way of:

from glumpy.ext import LIBRARY 

The libraries appear to be in the “glumpy/ext” folder but Python is not finding them.

I’m stuck and can’t get beyond this. Any help would be appreciated.

Windows 10 Pro
64 bit OS and processor
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32

Thanks,
Jeff

Code:

# -----------------------------------------------------------------------------
# Python & OpenGL for Scientific Visualization
# www.labri.fr/perso/nrougier/python+opengl
# Copyright (c) 2017, Nicolas P. Rougier
# Distributed under the 2-Clause BSD License.
# -----------------------------------------------------------------------------
from glumpy import app, gloo, gl

vertex = """
    attribute vec2 position;
    void main(){ gl_Position = vec4(position, 0.0, 1.0); } """

fragment = """
    void main() { gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); } """

# Create a window with a valid GL context
window = app.Window()

# Build the program and corresponding buffers (with 4 vertices)
quad = gloo.Program(vertex, fragment, count=4)

# Upload data into GPU
quad['position'] = (-1,+1), (+1,+1), (-1,-1), (+1,-1)

# Tell glumpy what needs to be done at each redraw
@window.event
def on_draw(dt):
    window.clear()
    quad.draw(gl.GL_TRIANGLE_STRIP)

# Run the app
app.run()

Present perfect/past in the abstract

In the abstract, it says "[...] but things have became more difficult with the introduction [...]".
The present perfect form is have become, while the past form is simply became. AFAIK have became is incorrect.

Typo

known instead of know should be there. Just search for this(below in double courts) in your book and change 'know' to 'known'
inside the brackets

''Of course, we also need to upload a color to this new uniform location and this is easier than for attribute because the memory has already been allocated on the GPU (since the size is know and does not depend on the number of vertices).''

linestrip-dotted.py

Hi,

When I copied the Star geometry from linestrip.py into linestrip-dotted.py, I get distorted dots like so:
Peek 2021-03-23 05-31

Am I doing something wrong or is this a bug?
Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.