Writing Python C Extensions can be daunting; you have to cast aside the security and fluidity of Python and embrace C, not just C but Pythons C API, which is huge [1]. Not only do you have to worry about just your standard malloc() and free() cases but now you have to contend with how CPython’s does its memory management which is by reference counting.
I describe some of the pitfalls you (I am thinking of you as a savvy C coder) can encounter and some of the coding patterns that you can use to avoid them.
First up: understanding reference counts and Python’s terminology.
A PyObject can represent any Python object. It is a fairly minimal C struct consisting of a reference count and a pointer to the object proper:
typedef struct _object {
Py_ssize_t ob_refcnt;
struct _typeobject *ob_type;
} PyObject;
In Python C extensions you always create and deallocate these PyObjects indirectly. Creation is via Python’s C API and destruction is done by decrementing the reference count. If this count hits zero then CPython will free all the resources used by the object.
Here is an example of a normal PyObject creation and deallocation:
1 2 3 4 5 6 7 8 9 10 | #include "Python.h"
void print_hello_world(void) {
PyObject *pObj = NULL;
pObj = PyBytes_FromString("Hello world\n"); /* Object creation, ref count = 1. */
PyObject_Print(pLast, stdout, 0);
Py_DECREF(pObj); /* ref count becomes 0, object deallocated.
* Miss this step and you have a memory leak. */
}
|
The twin challenges in Python extensions are:
Here are some examples of where things can go wrong:
Taking the above example of a normal PyObject creation and deallocation then in the grand tradition of C memory management after the Py_DECREF the pObj is now referencing free’d memory:
1 2 3 4 5 6 7 8 9 10 | #include "Python.h"
void print_hello_world(void) {
PyObject *pObj = NULL:
pObj = PyBytes_FromString("Hello world\n"); /* Object creation, ref count = 1. */
PyObject_Print(pLast, stdout, 0);
Py_DECREF(pObj); /* ref count = 0 so object deallocated. */
/* Accidentally use pObj... */
}
|
Accessing pObj may or may not give you something that looks like the original object.
The corresponding issue is if you decrement the reference count without previously incrementing it then the caller might find their reference invalid:
1 2 3 4 5 6 7 8 | static PyObject *bad_incref(PyObject *pObj) {
/* Forgotten Py_INCREF(pObj); here... */
/* Use pObj... */
Py_DECREF(pObj); /* Might make reference count zero. */
Py_RETURN_NONE; /* On return caller might find their object free'd. */
}
|
After the function returns the caller might find the object they naively trusted you with but probably not. A classic access-after-free error.
Memory leaks occur with a PyObject if the reference count never reaches zero and there is no Python reference or C pointer to the object in scope. Here is where it can go wrong: in the middle of a great long function there is an early return on error. On that path this code has a memory leak:
1 2 3 4 5 6 7 8 9 10 11 | static PyObject *bad_incref(PyObject *pObj) {
Py_INCREF(pObj);
/* ... a metric ton of code here ... */
if (error) {
/* No matching Py_DECREF, pObj is leaked. */
return NULL;
}
/* ... more code here ... */
Py_DECREF(pObj);
Py_RETURN_NONE;
}
|
The problem is that the reference count was not decremented before the early return, if pObj was a 100 Mb string then that memory is lost. Here is some C code that demonstrates this:
static PyObject *bad_incref(PyObject *pModule, PyObject *pObj) {
Py_INCREF(pObj);
Py_RETURN_NONE;
}
And here is what happens to the memory if we use this function from Python (cPyRefs.incref(...) in Python calls bad_incref() in C):
1 2 3 4 5 6 7 8 9 10 11 | >>> import cPyRefs # Process uses about 1Mb
>>> s = ' ' * 100 * 1024**2 # Process uses about 101Mb
>>> del s # Process uses about 1Mb
>>> s = ' ' * 100 * 1024**2 # Process uses about 101Mb
>>> cPyRefs.incref(s) # Now do an increment without decrement
>>> del s # Process still uses about 101Mb - leaked
>>> s # Officially 's' does not exist
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 's' is not defined
>>> # But process still uses about 101Mb - 's' is leaked
|
Warning
Do not be tempted to read the reference count itself to determine if the object is alive. The reason is that if Py_DECREF sees a refcount of one it can free and then reuse the address of the refcount field for a completely different object which makes it highly unlikely that that field will have a zero in it. There are some examples of this later on.
The Python documentation uses the terminology “New”, “Stolen” and “Borrowed” references throughout. These terms identify who is the real owner of the reference and whose job it is to clean it up when it is no longer needed:
This is about programming by contract and the following sections describe the contracts for each reference type.
First up New references.
When you create a “New” PyObject from a Python C API then you own it and it is your job to either:
If neither of these things is done you have a memory leak in just like a malloc() without a corresponding free().
Here is an example of a well behaved C function that take two C longs, converts them to Python integers and, subtracts one from the other and returns the Python result:
1 2 3 4 5 6 7 8 9 10 | static PyObject *subtract_long(long a, long b) {
PyObject *pA, *pB, *r;
pA = PyLong_FromLong(a); /* pA: New reference. */
pB = PyLong_FromLong(b); /* pB: New reference. */
r = PyNumber_Subtract(pA, pB); /* r: New reference. */
Py_DECREF(pA); /* My responsibility to decref. */
Py_DECREF(pB); /* My responsibility to decref. */
return r; /* Callers responsibility to decref. */
}
|
PyLong_FromLong() returns a new reference which means we have to clean up ourselves by using Py_DECREF.
PyNumber_Subtract() also returns a new reference but we expect the caller to clean that up. If the caller doesn’t then there is a memory leak.
So far, so good but what would be really bad is this:
r = PyNumber_Subtract(PyLong_FromLong(a), PyLong_FromLong(b));
You have passed in two new references to PyNumber_Subtract() and that function has no idea that they have to be decref’d once used so the two PyLong objects are leaked.
The contract with new references is: either you decref it or give it to someone who will. If neither happens then you have a memory leak.
This is also to do with object creation but where another object takes responsibility for decref’ing (possibly freeing) the object. Typical examples are when you create a PyObject that is then inserted into an existing container such as a tuple list, dict etc.
The analogy with C code is malloc’ing some memory, populating it and then passing that pointer to a linked list which then takes on the responsibility to free the memory if that item in the list is removed.
Here is an example of creating a 3-tuple, the comments describe what is happening contractually:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | static PyObject *make_tuple(void) {
PyObject *r;
PyObject *v;
r = PyTuple_New(3); /* New reference. */
v = PyLong_FromLong(1L); /* New reference. */
/* PyTuple_SetItem "steals" the new reference v. */
PyTuple_SetItem(r, 0, v);
/* This is fine. */
v = PyLong_FromLong(2L);
PyTuple_SetItem(r, 1, v);
/* More common pattern. */
PyTuple_SetItem(r, 2, PyUnicode_FromString("three"));
return r; /* Callers responsibility to decref. */
}
|
Note line 10 where we are overwriting an existing pointer with a new value, this is fine as r has taken responsibility for the first pointer value. This pattern is somewhat alarming to dedicated C programmers so the more common pattern, without the assignment to v is shown in line 13.
What would be bad is this:
v = PyLong_FromLong(1L); /* New reference. */
PyTuple_SetItem(r, 0, v); /* r takes ownership of the reference. */
Py_DECREF(v); /* Now we are interfering with r's internals. */
Once v has been passed to PyTuple_SetItem then your v becomes a borrowed reference with all of their problems which is the subject of the next section.
The contract with stolen references is: the thief will take care of things so you don’t have to. If you try to the results are undefined.
When you obtain a reference to an existing PyObject in a container using a ‘getter’ you are given a borrowed reference and this is where things can get tricky. The most subtle bugs in Python C Extensions are usually because of the misuse of borrowed references.
The analogy in C is having two pointers to the same memory location: so who is responsible for freeing the memory and what happens if the other pointer tries to access that free’d memory?
Here is an example where we are accessing the last member of a list with a “borrowed” reference. This is the sequence of operations:
Here is a C function that borrows a reference to the last object in a list, prints out the object’s reference count, calls another C function do_something() with that list, prints out the reference count of the object again and finally prints out the Python representation of the object:
1 2 3 4 5 6 7 8 9 10 11 | static PyObject *pop_and_print_BAD(PyObject *pList) {
PyObject *pLast;
pLast = PyList_GetItem(pList, PyList_Size(pList) - 1);
fprintf(stdout, "Ref count was: %zd\n", pLast->ob_refcnt);
do_something(pList);
fprintf(stdout, "Ref count now: %zd\n", pLast->ob_refcnt);
PyObject_Print(pLast, stdout, 0);
fprintf(stdout, "\n");
Py_RETURN_NONE;
}
|
The problem is that if do_something() mutates the list it might invalidate the item that we have a pointer to.
Suppose do_something() ‘removes’ every item in the list [3]. Then whether reference pLast is still “valid” depends on what other references to it exist and you have no control over that. Here are some examples of what might go wrong in that case (C pop_and_print_BAD is mapped to the Python cPyRefs.popBAD):
>>> l = ["Hello", "World"]
>>> cPyRefs.popBAD(l) # l will become empty
Ref count was: 1
Ref count now:<PHONE_NUMBER>
'World'
The reference count is bogus, however the memory has not been completely overwritten so the object (the string “World”) appears to be OK.
If we try a different string:
>>> l = ['abc' * 200]
>>> cPyRefs.popBAD(l)
Ref count was: 1
Ref count now:<PHONE_NUMBER>213693952
Segmentation fault: 11
At least this will get your attention!
Note
Incidentially from Python 3.3 onwards there is a module faulthandler that can give useful debugging information (file FaultHandlerExample.py):
1 2 3 4 5 6 7 | import faulthandler
faulthandler.enable()
import cPyRefs
l = ['abc' * 200]
cPyRefs.popBAD(l)
|
And this is what you get:
$ python3 FaultHandlerExample.py
Ref count was: 1
Ref count now:<PHONE_NUMBER>213693952
Fatal Python error: Segmentation fault
Current thread 0x00007fff73c88310:
File "FaultHandlerExample.py", line 7 in <module>
Segmentation fault: 11
There is a more subtle issue; suppose that in your Python code there is a reference to the last item in the list, then the problem suddenly “goes away”:
>>> l = ["Hello", "World"]
>>> a = l[-1]
>>> cPyRefs.popBAD(l)
Ref count was: 2
Ref count now: 1
'World'
The reference count does not go to zero so the object is preserved. The problem is that the correct behaviour of your C function depends entirely on that caller code having a extra reference.
This can happen implicitly as well:
>>> l = list(range(8))
>>> cPyRefs.popBAD(l)
Ref count was: 20
Ref count now: 19
7
The reason for this is that (for efficiency) CPython maintains the integers -5 to 255 permanently so they never go out of scope. If you use different integers we are back to the same access-after-free problem:
>>> l = list(range(800,808))
>>> cPyRefs.popBAD(l)
Ref count was: 1
Ref count now:<PHONE_NUMBER>
807
The problem with detecting these errors is that the bug is data dependent so your code might run fine for a while but some change in user data could cause it to fail. And it will fail in a manner that is not easily detectable.
Fortunately the solution is easy: with borrowed references you should increment the reference count whilst you have an interest in the object, then decrement it when you no longer want to do anything with it:
1 2 3 4 5 6 7 8 9 10 11 12 13 | static PyObject *pop_and_print_BAD(PyObject *pList) {
PyObject *pLast;
pLast = PyList_GetItem(pList, PyList_Size(pList) - 1);
Py_INCREF(pLast); /* Prevent pLast being deallocated. */
/* ... */
do_something(pList);
/* ... */
Py_DECREF(pLast); /* No longer interested in pLast, it might */
pLast = NULL; /* get deallocated here but we shouldn't care. */
/* ... */
Py_RETURN_NONE;
}
|
The pLast = NULL; line is not necessary but is good coding style as it will cause any subsequent acesses to pLast to fail.
An important takeaway here is that incrementing and decrementing reference counts is a cheap operation but the consequences of getting it wrong can be expensive. A precautionary approach in your code might be to always increment borrowed references when they are instantiated and then always decrement them before they go out of scope. That way you incur two cheap operations but eliminate a vastly more expensive one.
The contracts you enter into with these three reference types are:
| Type | Contract |
|---|---|
| New | Either you decref it or give it to someone who will, otherwise you have a memory leak. |
| Stolen | The thief will take of things so you don’t have to. If you try to the results are undefined. |
| Borrowed | The lender can invalidate the reference at any time without telling you. Bad news. So increment a borrowed reference whilst you need it and decrement it when you are finished. |
Footnotes
| [1] | Huge, but pretty consistent once mastered. |
| [2] | To be picky we just need to decrement the use of our reference to it. Other code that has incremented the same reference is responsible for decrementing their use of the reference. |
| [3] | Of course we never remove items in a list we merely decrement their reference count (and if that hits zero then they are deleted). Such as: |
void do_something(PyObject *pList) {
while (PyList_Size(pList) > 0) {
PySequence_DelItem(pList, 0);
}
}


This is link 6e71f89e-8271-4a3a-94c3-35befff3eb96 This is text 1ed092fa-4774-4d05-bd3a-4122f70adce4 This is text 45497233-2511-4fde-9b8e-c26a1fa4b6e5
This is paragraph 1ea8b2f9-0c47-42bd-be9e-790f09acc62c
This is paragraph a694dd02-b1dc-4961-8a40-de924478b313


| Title | Crew | Items | Percentage |
|---|---|---|---|
Instructor |
Chih-Jen Huang | Website instructor Technique instructor Opinion Provider |
15% |
| Chi-Hua Tsai | Leader of visiting Content instructor Opinion Provider |
||
Members of the Team |
Yi-Chen Chou | Items assigning, Investigating, Text editing, Video editing and recirding | 75% |
| Sheng-Han Su | Investigating, Text editing, Video editing and recirding | ||
| Cian-Yun Wang | Investigating, Text editing | ||
| Sih-Chi Chung | Investigating, Text editing | ||
| Ting-Kai Jhang | Investigating, Text editing | ||
| Kai-Cyuan Young | Website making | ||
| Tian-Yo Lin | Website making | ||
| Chang-Pei Shih | Translation | ||
| Bing-Rong Ni | Translation | ||
| Yi-Chin Jheng | Translation | ||
| Students in Hui-Wen | Member of canoe team | Suggestion giving and assisting. Providing Information of Cambridge district (history, text, photos) |
10% |
| Director of canoe association | Lin, Wan-Ru | ||
| Assistant ofCity Councilman Chang, Yao-Zong | Chang, Yo-Yu | ||
| Chief of Yong-long district | Lin, Shih-Yuan | ||
| Director of third river, water resources agency | Yang, Ren-Jie |


There are three main reasons why to prefer alias-declarations over typedefs:
1. They look clearer and better.
2. ^ especially for function pointers:
typedef void (*pointer) (std::string, bool);
vs.
using pointer = void (*) (std::string, bool);
(Note how the name is no longer nested as horribly).
3. Alias declarations can be templated!
template<typename T>
using Map = std::unordered_map<std::string, T>;
Previously, you would have had to nest that in a struct:
template<typename T>
struct Map
{
typedef std::unordered_map<std::string, t> type;
}
Meaning you would not only have had to access it using Map<T>::type, but also you would have had to use typename everywhere:
typename Map<T>::type map;
Because the compiler could not know if there were still a specialization of Map where type were not actually a type, but for example a static variable. This is not the case for alias declarations, as alias declarations must alias a type, meaning there is no need for either the ::type nor for the typename:
Map<T> map; // using alias-declarations
Much better!
One last thing to note is that for all the type_traits operations in the <type_traits> header which use a typedef and a struct, there is also a corresponding version using alias declarations. These alias-declaration versions are accessible by appending a ‘_t’ at the end of e.g. std::remove_reference (making it std::remove_reference_t):
// C++98
typename std::remove_const<T>::type object;
// C++14
std::remove_const_t<T> object;


|
Jetson Inference
DNN Vision Library
|
OpenGL textures and display window (X11/GLX). More...
Classes | |
| class | glBuffer |
| OpenGL buffer with CUDA interoperability. More... | |
| class | glCamera |
| OpenGL perspective camera supporting Look-At, Yaw/Pitch/Roll, and Ortho modes. More... | |
| class | glDisplay |
| OpenGL display window and image/video renderer with CUDA interoperability. More... | |
| class | glTexture |
| OpenGL texture with CUDA interoperability. More... | |
| class | glWidget |
| OpenGL graphics widget for rendering moveable/resizable shapes. More... | |
Macros | |
| #define | GL_VERTEX_BUFFER GL_ARRAY_BUFFER |
| Alias for vertex buffers. More... | |
| #define | GL_INDEX_BUFFER GL_ELEMENT_ARRAY_BUFFER |
| Alias for index buffers. More... | |
| #define | GL_MAP_CPU 0x1 |
| Map the buffer to CPU address space. More... | |
| #define | GL_MAP_CUDA 0x2 |
| Map the buffer to CUDA address space. More... | |
| #define | GL_FROM_CPU 0x3 |
| Copy the buffer from CPU to OpenGL. More... | |
| #define | GL_FROM_CUDA 0x4 |
| Copy the buffer from CUDA to OpenGL. More... | |
| #define | GL_TO_CPU 0x5 |
| Copy the buffer to CPU from OpenGL. More... | |
| #define | GL_TO_CUDA 0x6 |
| Copy the buffer to CUDA from OpenGL. More... | |
| #define | GL_WRITE_DISCARD (GL_READ_WRITE + 0xff) |
| Map the buffer as write-only and discard previous contents. More... | |
| #define | GL_WRITE_ONLY GL_WRITE_ONLY_ARB |
| Map the buffer with write-only access. More... | |
| #define | GL_READ_ONLY GL_READ_ONLY_ARB |
| Map the buffer with read-only access. More... | |
| #define | GL_READ_WRITE GL_READ_WRITE_ARB |
| Map the buffer with read/write access. More... | |
| #define | KEY_PRESSED 1 |
| Define for KEY_STATE and KEY_RAW events when key is pressed. More... | |
| #define | KEY_RELEASED 0 |
| Define for KEY_STATE and KEY_RAW events when key is released. More... | |
| #define | MOUSE_PRESSED 1 |
| Define for MOUSE_BUTTON event when button is pressed. More... | |
| #define | MOUSE_RELEASED 0 |
| Define for MOUSE_BUTTON event when button is released. More... | |
| #define | MOUSE_LEFT 1 |
| Define for the left mouse button number. More... | |
| #define | MOUSE_MIDDLE 2 |
| Define for the middle mouse button (or scroll wheel button) More... | |
| #define | MOUSE_RIGHT 3 |
| Define for the right mouse button number. More... | |
| #define | MOUSE_WHEEL_UP 4 |
| Define for the mouse wheel scroll up button number. More... | |
| #define | MOUSE_WHEEL_DOWN 5 |
| Define for the mouse wheel scroll down button number. More... | |
| #define | GL_RGB32F GL_RGB32F_ARB |
| Alias for GL_RGB32F. More... | |
| #define | GL_RGBA32F GL_RGBA32F_ARB |
| Alias for GL_RGBA32F. More... | |
| #define | LOG_GL "[OpenGL] " |
| OpenGL logging prefix. More... | |
| #define | GL(x) { x; glCheckError( #x, __FILE__, __LINE__ ); } |
| OpenGL error-checking macro. More... | |
| #define | GL_VERIFY(x) { x; if(glCheckError( #x, __FILE__, __LINE__ )) return false; } |
| Return false on OpenGL error. More... | |
| #define | GL_VERIFYN(x) { x; if(glCheckError( #x, __FILE__, __LINE__ )) return NULL; } |
| OpenGL NULL on OpenGL error. More... | |
| #define | GL_CHECK(msg) { glCheckError(msg, __FILE__, __LINE__); } |
| Print a message on OpenGL error. More... | |
Typedefs | |
| typedef bool(* | glEventHandler) (uint16_t event, int a, int b, void *user) |
| Event message handler callback for recieving UI messages from a window. More... | |
Enumerations | |
| enum | glEventType { MOUSE_MOVE = 0, MOUSE_ABSOLUTE, MOUSE_BUTTON, MOUSE_DRAG, MOUSE_WHEEL, KEY_STATE, KEY_MODIFIED, KEY_CHAR, WIDGET_CREATED, WIDGET_SELECTED, WIDGET_MOVED, WIDGET_RESIZED, WINDOW_RESIZED, WINDOW_CLOSED } |
| User interface event message types. More... | |
Functions | |
| glDisplay * | glGetDisplay (uint32_t display=0) |
| Retrieve a display window object. More... | |
| uint32_t | glGetNumDisplays () |
| Return the number of created glDisplay windows. More... | |
| bool | glCheckError (const char *msg, const char *file, int line) |
| OpenGL error-checking messsage function. More... | |
| bool | glCheckError (const char *msg) |
| OpenGL error check + logging. More... | |
| void | glPrintFreeMem () |
| Print the amount of free GPU memory. More... | |
| void | glDrawLine (float x1, float y1, float x2, float y2, float r, float g, float b, float a=1.0f, float thickness=2.0f) |
| Render a line in screen coordinates with the specified color. More... | |
| void | glDrawOutline (float x, float y, float width, float height, float r, float g, float b, float a=1.0f, float thickness=2.0f) |
| Render the outline of a rect in screen coordinates with the specified color. More... | |
| void | glDrawRect (float x, float y, float width, float height, float r, float g, float b, float a=1.0f) |
| Render a filled rect in screen coordinates with the specified color. More... | |
OpenGL textures and display window (X11/GLX).
| class glBuffer |
OpenGL buffer with CUDA interoperability.
Public Member Functions | |
| ~glBuffer () | |
| Free the buffer. More... | |
| bool | Bind () |
| Activate using the buffer. More... | |
| void | Unbind () |
| Deactivate using the buffer. More... | |
| uint32_t | GetID () const |
| Retrieve the OpenGL resource handle of the buffer. More... | |
| uint32_t | GetType () const |
| Retrieve the buffer type (GL_VERTEX_BUFFER or GL_INDEX_BUFFER) More... | |
| uint32_t | GetSize () const |
| Retrieve the total size in bytes of the buffer. More... | |
| uint32_t | GetNumElements () const |
| Retrieve the number of elements (i.e. More... | |
| uint32_t | GetElementSize () const |
| Retrieve the size in bytes of each element. More... | |
| void * | Map (uint32_t device, uint32_t flags) |
| Map the buffer for accessing from the CPU or CUDA. More... | |
| void | Unmap () |
| Unmap the buffer from CPU/CUDA access. More... | |
| bool | Copy (void *ptr, uint32_t flags) |
| Copy entire contents of the buffer to/from CPU or CUDA memory. More... | |
| bool | Copy (void *ptr, uint32_t size, uint32_t flags) |
| Copy contents of the buffer to/from CPU or CUDA memory. More... | |
| bool | Copy (void *ptr, uint32_t offset, uint32_t size, uint32_t flags) |
| Copy contents of the buffer to/from CPU or CUDA memory. More... | |
Static Public Member Functions | |
| static glBuffer * | Create (uint32_t type, uint32_t size, void *data=NULL, uint32_t usage=GL_STATIC_DRAW) |
| Allocate an OpenGL buffer. More... | |
| static glBuffer * | Create (uint32_t type, uint32_t numElements, uint32_t elementSize, void *data=NULL, uint32_t usage=GL_STATIC_DRAW) |
| Allocate an OpenGL buffer. More... | |
| glBuffer::~glBuffer | ( | ) |
Free the buffer.
| bool glBuffer::Bind | ( | ) |
Activate using the buffer.
| bool glBuffer::Copy | ( | void * | ptr, |
| uint32_t | flags | ||
| ) |
Copy entire contents of the buffer to/from CPU or CUDA memory.
| ptr | the memory pointer to copy to/from, either in CPU or CUDA address space depending on flags. It's assumed that the size of the memory from this pointer is equal to GetSize(), and the entire contents of the buffer will be copied. |
| flags | should be one of the following:
|
| bool glBuffer::Copy | ( | void * | ptr, |
| uint32_t | offset, | ||
| uint32_t | size, | ||
| uint32_t | flags | ||
| ) |
Copy contents of the buffer to/from CPU or CUDA memory.
| ptr | the memory buffer to copy to/from, either in CPU or CUDA address space depending on flags |
| offset | the offset into the OpenGL buffer to copy. It is assumed any offset to the CPU/CUDA pointer argument has already been applied. |
| size | the number of bytes to copy |
| flags | should be one of the following:
|
| bool glBuffer::Copy | ( | void * | ptr, |
| uint32_t | size, | ||
| uint32_t | flags | ||
| ) |
Copy contents of the buffer to/from CPU or CUDA memory.
| ptr | the memory pointer to copy to/from, either in CPU or CUDA address space depending on flags. |
| size | the number of bytes to copy |
| flags | should be one of the following:
|
|
static |
Allocate an OpenGL buffer.
| type | either GL_VERTEX_BUFFER for a vertex buffer, or GL_INDEX_BUFFER for an index buffer |
| numElements | the number of elements (i.e. vertices or indices) in the buffer |
| elementSize | the size in bytes of each element |
| data | pointer to the initial memory of this buffer |
| usage | GL_STATIC_DRAW (never updated), GL_STREAM_DRAW (occasional updates), or GL_DYNAMIC_DRAW (per-frame updates) |
|
static |
Allocate an OpenGL buffer.
| type | either GL_VERTEX_BUFFER for a vertex buffer, or GL_INDEX_BUFFER for an index buffer |
| size | the size in bytes to allocated for the buffer |
| data | pointer to the initial memory of this buffer |
| usage | GL_STATIC_DRAW (never updated), GL_STREAM_DRAW (occasional updates), or GL_DYNAMIC_DRAW (per-frame updates) |
|
inline |
Retrieve the size in bytes of each element.
|
inline |
Retrieve the OpenGL resource handle of the buffer.
|
inline |
Retrieve the number of elements (i.e.
vertices or indices)
|
inline |
Retrieve the total size in bytes of the buffer.
|
inline |
Retrieve the buffer type (GL_VERTEX_BUFFER or GL_INDEX_BUFFER)
| void* glBuffer::Map | ( | uint32_t | device, |
| uint32_t | flags | ||
| ) |
Map the buffer for accessing from the CPU or CUDA.
| device | either GL_MAP_CPU or GL_MAP_CUDA |
| flags | should be one of the following:
|
| void glBuffer::Unbind | ( | ) |
Deactivate using the buffer.
| void glBuffer::Unmap | ( | ) |
Unmap the buffer from CPU/CUDA access.
| class glCamera |
OpenGL perspective camera supporting Look-At, Yaw/Pitch/Roll, and Ortho modes.
Public Types | |
| enum | CameraMode { LookAt, YawPitchRoll, Ortho } |
| Enum specifying the camera mode. More... | |
Public Member Functions | |
| ~glCamera () | |
| Free the camera. More... | |
| void | Activate () |
| Activate GL_PROJECTION and GL_MODELVIEW matrices. More... | |
| void | Activate (CameraMode mode) |
| Activate GL_PROJECTION and GL_MODELVIEW matrices. More... | |
| void | Deactivate () |
| Restore previous GL_PROJECTION and GL_MODELVIEW matrices. More... | |
| CameraMode | GetCameraMode () const |
| Get the camera mode. More... | |
| void | SetCameraMode (CameraMode mode) |
| Set the camera mode. More... | |
| void | SetFOV (float fov) |
| Set the field of view (FOV), in degrees. More... | |
| void | SetClippingPlane (float near, float far) |
| Set the near/far z-clipping plane. More... | |
| void | SetNear (float near) |
| Set the distance to the near clipping plane. More... | |
| void | SetFar (float far) |
| Set the distance to the far clipping plane. More... | |
| void | SetEye (float x, float y, float z) |
| Set the eye position. More... | |
| void | SetLookAt (float x, float y, float z) |
| Set the look-at point. More... | |
| void | SetRotation (float yaw, float pitch, float roll) |
| Set the yaw/pitch/roll angles, in radians. More... | |
| void | SetYaw (float yaw) |
| Set the yaw angle, in radians. More... | |
| void | SetPitch (float pitch) |
| Set the pitch angle, in radians. More... | |
| void | SetRoll (float roll) |
| Set the roll angle, in radians. More... | |
| void | SetMovementSpeed (float speed) |
| Set the movement speed (in world units) More... | |
| void | SetMovementEnabled (bool enabled) |
| Enable or disable movement from user input. More... | |
| void | StoreDefaults () |
| Store the current configuration as defaults. More... | |
| void | Reset () |
| Reset camera orientation to defaults. More... | |
| void | RegisterEvents (uint32_t display=0) |
| Register to recieve input events (enable movement) More... | |
Static Public Member Functions | |
| static glCamera * | Create (CameraMode mode, int registerEvents=0) |
| Create OpenGL camera object with the specified CameraMode. More... | |
| static glCamera * | Create (int registerEvents=0) |
| Create OpenGL camera object. More... | |
| enum glCamera::CameraMode |
| glCamera::~glCamera | ( | ) |
Free the camera.
| void glCamera::Activate | ( | ) |
Activate GL_PROJECTION and GL_MODELVIEW matrices.
| void glCamera::Activate | ( | CameraMode | mode | ) |
Activate GL_PROJECTION and GL_MODELVIEW matrices.
|
static |
Create OpenGL camera object with the specified CameraMode.
| registerEvents | the ID of the glDisplay window to register with to recieve input events (for moving the camera around with keyboard/mouse), or -1 to not register for input events. |
|
static |
Create OpenGL camera object.
| registerEvents | the ID of the glDisplay window to register with to recieve input events (for moving the camera around with keyboard/mouse), or -1 to not register for input events. |
| void glCamera::Deactivate | ( | ) |
Restore previous GL_PROJECTION and GL_MODELVIEW matrices.
|
inline |
Get the camera mode.
| void glCamera::RegisterEvents | ( | uint32_t | display = 0 | ) |
Register to recieve input events (enable movement)
| void glCamera::Reset | ( | ) |
Reset camera orientation to defaults.
|
inline |
Set the camera mode.
|
inline |
Set the near/far z-clipping plane.
|
inline |
Set the eye position.
|
inline |
Set the distance to the far clipping plane.
|
inline |
Set the field of view (FOV), in degrees.
|
inline |
Set the look-at point.
|
inline |
Enable or disable movement from user input.
|
inline |
Set the movement speed (in world units)
|
inline |
Set the distance to the near clipping plane.
|
inline |
Set the pitch angle, in radians.
|
inline |
Set the roll angle, in radians.
|
inline |
Set the yaw/pitch/roll angles, in radians.
|
inline |
Set the yaw angle, in radians.
| void glCamera::StoreDefaults | ( | ) |
Store the current configuration as defaults.
| class glDisplay |
OpenGL display window and image/video renderer with CUDA interoperability.
Public Member Functions | |
| ~glDisplay () | |
| Destroy window. More... | |
| virtual bool | Open () |
| Open the window. More... | |
| bool | IsOpen () const |
| Returns true if the window is open. More... | |
| bool | IsClosed () const |
| Returns true if the window has been closed. More... | |
| bool | IsRendering () const |
| Returns true if between BeginRender() and EndRender() More... | |
| float | GetFPS () const |
| Get the average frame time (in milliseconds). More... | |
| uint32_t | GetID () const |
| Get the ID of this display instance into glGetDisplay() More... | |
| virtual uint32_t | GetType () const |
| Return the interface type (glDisplay::Type) More... | |
Frame Begin + End | |
| void | BeginRender (bool processEvents=true) |
| Clear window and begin rendering a frame. More... | |
| void | EndRender () |
| Finish rendering and refresh / flip the backbuffer. More... | |
Image Rendering | |
| void | Render (glTexture *texture, float x=5.0f, float y=30.0f) |
| Render an OpenGL texture. More... | |
| void | Render (float *image, uint32_t width, uint32_t height, float x=0.0f, float y=30.0f, bool normalize=true) |
| Render a CUDA float4 image using OpenGL interop If normalize is true, the image's pixel values will be rescaled from the range of [0-255] to [0-1] If normalize is false, the image's pixel values are assumed to already be in the range of [0-1] Note that if normalization is selected to be performed, it will be done in-place on the image. More... | |
| template<typename T > | |
| bool | Render (T *image, uint32_t width, uint32_t height) |
| Render a CUDA image (uchar3, uchar4, float3, float4) using OpenGL interop. More... | |
| virtual bool | Render (void *image, uint32_t width, uint32_t height, imageFormat format) |
| Render a CUDA image (uchar3, uchar4, float3, float4) using OpenGL interop. More... | |
| void | RenderImage (void *image, uint32_t width, uint32_t height, imageFormat format, float x=0.0f, float y=30.0f, bool normalize=true) |
| Render a CUDA image (uchar3, uchar4, float3, float4) using OpenGL interop. More... | |
| void | RenderOnce (void *image, uint32_t width, uint32_t height, imageFormat format, float x=5.0f, float y=30.0f, bool normalize=true) |
| Begin the frame, render one CUDA image using OpenGL interop, and end the frame. More... | |
| void | RenderOnce (float *image, uint32_t width, uint32_t height, float x=5.0f, float y=30.0f, bool normalize=true) |
| Begin the frame, render one CUDA float4 image using OpenGL interop, and end the frame. More... | |
Vector Rendering | |
| void | RenderLine (float x1, float y1, float x2, float y2, float r, float g, float b, float a=1.0f, float thickness=2.0f) |
| Render a line in screen coordinates with the specified color. More... | |
| void | RenderOutline (float x, float y, float width, float height, float r, float g, float b, float a=1.0f, float thickness=2.0f) |
| Render the outline of a rect in screen coordinates with the specified color. More... | |
| void | RenderRect (float x, float y, float width, float height, float r, float g, float b, float a=1.0f) |
| Render a filled rect in screen coordinates with the specified color. More... | |
| void | RenderRect (float r, float g, float b, float a=1.0f) |
| Render a filled rect covering the current viewport with the specified color. More... | |
Window Resizing | |
| void | SetSize (uint32_t width, uint32_t height) |
| Set the window's size. More... | |
| void | SetMaximized (bool maximized) |
| Maximize or un-maximize the window. More... | |
| bool | IsMaximized () |
| Determine if the window is maximized or not. More... | |
| void | SetFullscreen (bool fullscreen) |
| Set the window to fullscreen mode or not. More... | |
| bool | IsFullscreen () |
| Determine if the window is fullscreen or not. More... | |
Viewport Options | |
| void | GetBackgroundColor (float *r, float *g, float *b, float *a=NULL) |
| Retrieve the window's background color. More... | |
| void | SetBackgroundColor (float r, float g, float b, float a=1.0f) |
| Set the window's background color. More... | |
| void | SetViewport (int left, int top, int right, int bottom) |
| Set the active viewport being rendered to. More... | |
| void | ResetViewport () |
| Reset to the full viewport (and change back GL_PROJECTION) More... | |
Event Handling | |
| void | ProcessEvents () |
| Process UI event messages. More... | |
| void | AddEventHandler (glEventHandler callback, void *user=NULL) |
| Register an event message handler that will be called by ProcessEvents() More... | |
| void | RemoveEventHandler (glEventHandler callback, void *user=NULL) |
| Remove an event message handler from being called by ProcessEvents() RemoveEventHandler() will search for previously registered event handlers that have the same function pointer and/or user pointer, and remove them for being called again in the future. More... | |
Mouse + Keyboard State | |
| const int * | GetMousePosition () const |
| Get the mouse position. More... | |
| void | GetMousePosition (int *x, int *y) const |
| Get the mouse position. More... | |
| bool | GetMouseButton (uint32_t button) const |
| Get the mouse button state. More... | |
| bool | GetKey (uint32_t key) const |
| Get the state of a key (lowercase, without modifiers applied) More... | |
Mouse Cursor | |
| void | SetCursor (uint32_t cursor) |
| Set the active mouse cursor. More... | |
| void | SetDefaultCursor (uint32_t cursor, bool activate=true) |
| Set the default mouse cursor that gets used by ResetCursor() More... | |
| void | ResetCursor () |
| Reset the mouse cursor back to it's default. More... | |
| void | ResetDefaultCursor (bool activate=true) |
| Reset the default cursor back to it's original, the arrow. More... | |
Widgets | |
| glWidget * | AddWidget (glWidget *widget) |
| Add a widget to the window that recieves events and is rendered. More... | |
| void | RemoveWidget (glWidget *widget, bool deleteWidget=true) |
| Remove a widget from the window (and optionally delete it) More... | |
| void | RemoveWidget (uint32_t index, bool deleteWidget=true) |
| Remove a widget from the window (and optionally delete it) More... | |
| void | RemoveAllWidgets (bool deleteWidgets=true) |
| Remove all widgets from the window (and optionally delete them) More... | |
| uint32_t | GetNumWidgets () const |
| Retrieve the number of widgets. More... | |
| glWidget * | GetWidget (const uint32_t index) const |
| Retrieve a widget. More... | |
| int | GetWidgetIndex (const glWidget *widget) const |
| Retrieve the index of a widget (or -1 if not found) More... | |
| glWidget * | FindWidget (int x, int y) |
| Find first widget by coordinate, or NULL if no widget overlaps with that coordinate. More... | |
| std::vector< glWidget * > | FindWidgets (int x, int y) |
| Find all widgets by coordinate, or NULL if no widget overlaps with that coordinate. More... | |
| Public Member Functions inherited from videoOutput | |
| virtual | ~videoOutput () |
| Destroy interface and release all resources. More... | |
| template<typename T > | |
| bool | Render (T *image, uint32_t width, uint32_t height) |
| Render and output the next frame to the stream. More... | |
| virtual void | Close () |
| Stop streaming the device. More... | |
| bool | IsStreaming () const |
| Check if the device is actively streaming or not. More... | |
| uint32_t | GetWidth () const |
| Return the width of the stream, in pixels. More... | |
| uint32_t | GetHeight () const |
| Return the height of the stream, in pixels. More... | |
| float | GetFrameRate () const |
| Return the framerate, in Hz or FPS. More... | |
| uint64_t | GetFrameCount () const |
| Return the number of frames output. More... | |
| const URI & | GetResource () const |
| Return the resource URI of the stream. More... | |
| const videoOptions & | GetOptions () const |
| Return the videoOptions of the stream. More... | |
| void | AddOutput (videoOutput *output) |
| Add an output sub-stream. More... | |
| uint32_t | GetNumOutputs () const |
| Return the number of sub-streams. More... | |
| videoOutput * | GetOutput (uint32_t index) const |
| Return a sub-stream. More... | |
| bool | IsType (uint32_t type) const |
| Check if this stream is of a particular type. More... | |
| template<typename T > | |
| bool | IsType () const |
| Check if a this stream is of a particular type. More... | |
| const char * | TypeToStr () const |
| Convert this stream's class type to string. More... | |
Static Public Member Functions | |
| static glDisplay * | Create (const char *title=NULL, int width=-1, int height=-1, float r=0.05f, float g=0.05f, float b=0.05f, float a=1.0f) |
| Create a new OpenGL display window with the specified options. More... | |
| static glDisplay * | Create (const videoOptions &options) |
| Create a new OpenGL display window with the specified options. More... | |
| Static Public Member Functions inherited from videoOutput | |
| static videoOutput * | Create (const videoOptions &options) |
| Create videoOutput interface from a videoOptions struct that's already been filled out. More... | |
| static videoOutput * | Create (const char *URI, const videoOptions &options=videoOptions()) |
| Create videoOutput interface from a resource URI string and optional videoOptions. More... | |
| static videoOutput * | Create (const char *URI, const commandLine &cmdLine) |
| Create videoOutput interface from a resource URI string and parsing command line arguments. More... | |
| static videoOutput * | Create (const char *URI, const int argc, char **argv) |
| Create videoOutput interface from a resource URI string and parsing command line arguments. More... | |
| static videoOutput * | Create (const int argc, char **argv, int positionArg=-1) |
| Create videoOutput interface by parsing command line arguments, including the resource URI. More... | |
| static videoOutput * | Create (const commandLine &cmdLine, int positionArg=-1) |
| Create videoOutput interface by parsing command line arguments, including the resource URI. More... | |
| static videoOutput * | CreateNullOutput () |
| Create videoOutput interface that acts as a NULL output and does nothing with incoming frames. More... | |
| static const char * | Usage () |
| Usage string for command line arguments to Create() More... | |
| static const char * | TypeToStr (uint32_t type) |
| Convert a class type to a string. More... | |
Static Public Attributes | |
| static const uint32_t | Type = (1 << 3) |
| Unique type identifier of glDisplay class. More... | |
Protected Member Functions | |
| glDisplay (const videoOptions &options) | |
| bool | initWindow () |
| bool | initGL () |
| glTexture * | allocTexture (uint32_t width, uint32_t height, imageFormat format) |
| void | activateViewport () |
| void | dispatchEvent (uint16_t msg, int a, int b) |
| Protected Member Functions inherited from videoOutput | |
| videoOutput (const videoOptions &options) | |
Static Protected Member Functions | |
| static bool | onEvent (uint16_t msg, int a, int b, void *user) |
Protected Attributes | |
| Display * | mDisplayX |
| Screen * | mScreenX |
| XVisualInfo * | mVisualX |
| Window | mWindowX |
| GLXContext | mContextGL |
| Cursor | mCursors [256] |
| int | mActiveCursor |
| int | mDefaultCursor |
| bool | mInitialShow |
| bool | mRendering |
| bool | mResizedToFeed |
| Atom | mWindowClosedMsg |
| DragMode | mDragMode |
| uint32_t | mID |
| uint32_t | mScreenWidth |
| uint32_t | mScreenHeight |
| timespec | mLastTime |
| float | mAvgTime |
| float | mBgColor [4] |
| int | mViewport [4] |
| int | mMousePos [2] |
| int | mMouseDrag [2] |
| int | mMouseDragOrigin [2] |
| bool | mMouseButtons [16] |
| bool | mKeyStates [1024] |
| float * | mNormalizedCUDA |
| uint32_t | mNormalizedWidth |
| uint32_t | mNormalizedHeight |
| std::vector< glWidget * > | mWidgets |
| std::vector< glTexture * > | mTextures |
| std::vector< eventHandler > | mEventHandlers |
| Protected Attributes inherited from videoOutput | |
| bool | mStreaming |
| videoOptions | mOptions |
| std::vector< videoOutput * > | mOutputs |
Static Protected Attributes | |
| static const int | screenIdx = 0 |
Status Bar Text | |
| static const char * | DEFAULT_TITLE |
| Default title bar name. More... | |
| virtual void | SetStatus (const char *str) |
| Set the window title string. More... | |
| void | SetTitle (const char *str) |
| Set the window title string. More... | |
Mouse Dragging | |
| enum | DragMode { DragDefault, DragDisabled, DragSelect, DragCreate } |
| Drag behavior enum. More... | |
| DragMode | GetDragMode () const |
| Get the dragging behavior mode. More... | |
| void | SetDragMode (DragMode mode) |
| Set the dragging behavior mode. More... | |
| bool | IsDragging (DragMode mode=DragDefault) const |
| Is the mouse currently dragging in the specified mode? More... | |
| bool | GetDragRect (int *x, int *y, int *width, int *height) |
| Get the current dragging rectangle, or return false if not dragging. More... | |
| bool | GetDragCoords (int *x1, int *y1, int *x2, int *y2) |
| Get the current dragging coordinates, or return false if not dragging. More... | |
| enum glDisplay::DragMode |
Drag behavior enum.
| glDisplay::~glDisplay | ( | ) |
Destroy window.
|
protected |
|
protected |
| void glDisplay::AddEventHandler | ( | glEventHandler | callback, |
| void * | user = NULL |
||
| ) |
Register an event message handler that will be called by ProcessEvents()
| callback | function pointer to the event message handler callback |
| user | optional user-specified pointer that will be passed to all invocations of this event handler (typically an object) |
Add a widget to the window that recieves events and is rendered.
|
protected |
| void glDisplay::BeginRender | ( | bool | processEvents = true | ) |
Clear window and begin rendering a frame.
If processEvents is true, ProcessEvents() will automatically be called.
|
static |
Create a new OpenGL display window with the specified options.
| title | window title bar string, or NULL for a default title |
| width | desired width of the window, or -1 to be maximized |
| height | desired height of the window, or -1 to be maximized |
| r | default background RGBA color, red component (0.0-1.0f) |
| g | default background RGBA color, green component (0.0-1.0f) |
| b | default background RGBA color, blue component (0.0-1.0f) |
| a | default background RGBA color, alpha component (0.0-1.0f) |
|
static |
Create a new OpenGL display window with the specified options.
|
protected |
| void glDisplay::EndRender | ( | ) |
Finish rendering and refresh / flip the backbuffer.
| glWidget* glDisplay::FindWidget | ( | int | x, |
| int | y | ||
| ) |
Find first widget by coordinate, or NULL if no widget overlaps with that coordinate.
| std::vector<glWidget*> glDisplay::FindWidgets | ( | int | x, |
| int | y | ||
| ) |
Find all widgets by coordinate, or NULL if no widget overlaps with that coordinate.
| void glDisplay::GetBackgroundColor | ( | float * | r, |
| float * | g, | ||
| float * | b, | ||
| float * | a = NULL |
||
| ) |
Retrieve the window's background color.
| bool glDisplay::GetDragCoords | ( | int * | x1, |
| int * | y1, | ||
| int * | x2, | ||
| int * | y2 | ||
| ) |
Get the current dragging coordinates, or return false if not dragging.
|
inline |
Get the dragging behavior mode.
| bool glDisplay::GetDragRect | ( | int * | x, |
| int * | y, | ||
| int * | width, | ||
| int * | height | ||
| ) |
Get the current dragging rectangle, or return false if not dragging.
|
inline |
Get the average frame time (in milliseconds).
|
inline |
Get the ID of this display instance into glGetDisplay()
|
inline |
Get the state of a key (lowercase, without modifiers applied)
Similar to glEvent::KEY_STATE, GetKey() queries the raw key state without being translated by modifier keys such as Shift, CapsLock, NumLock, ect. Alphanumeric keys will be left as lowercase, so query lowercase keys - uppercase keys will always return false.
| key | the XK_ key symbol (see /usr/include/X11/keysymdef.h ) Uppercase keys like XK_A or XK_plus will always return false. Instead, query the lowercase keys such as XK_a, XK_1, ect. Other keys like F1-F12, shift, tab, ctrl/alt, arrow keys, backspace, delete, escape, and enter can all be queried. GetKey() caches the first 1024 key symbols. Other keys will return false, but can be subscribed to through a glEventHander. |
|
inline |
Get the mouse button state.
| button | the button number, starting with 1. In X11, the left mouse button is 1. Here are the mouse button numbers: |
2 MOUSE_MIDDLE (middle button / scroll wheel button)
|
inline |
Get the mouse position.
|
inline |
Get the mouse position.
|
inline |
Retrieve the number of widgets.
|
inlinevirtual |
Return the interface type (glDisplay::Type)
Reimplemented from videoOutput.
|
inline |
Retrieve a widget.
| int glDisplay::GetWidgetIndex | ( | const glWidget * | widget | ) | const |
Retrieve the index of a widget (or -1 if not found)
|
protected |
|
protected |
|
inline |
Returns true if the window has been closed.
|
inline |
Is the mouse currently dragging in the specified mode?
| bool glDisplay::IsFullscreen | ( | ) |
Determine if the window is fullscreen or not.
| bool glDisplay::IsMaximized | ( | ) |
Determine if the window is maximized or not.
|
inline |
Returns true if the window is open.
|
inline |
Returns true if between BeginRender() and EndRender()
|
staticprotected |
|
virtual |
| void glDisplay::ProcessEvents | ( | ) |
Process UI event messages.
Any queued events will be dispatched to the event message handlers that were registered with RegisterEventHandler()
ProcessEvents() usually gets called automatically by BeginFrame(), so it is not typically necessary to explicitly call it unless you passed false
to BeginFrame() and wish to process events at another time of your choosing.
| void glDisplay::RemoveAllWidgets | ( | bool | deleteWidgets = true | ) |
Remove all widgets from the window (and optionally delete them)
| void glDisplay::RemoveEventHandler | ( | glEventHandler | callback, |
| void * | user = NULL |
||
| ) |
Remove an event message handler from being called by ProcessEvents() RemoveEventHandler() will search for previously registered event handlers that have the same function pointer and/or user pointer, and remove them for being called again in the future.
| void glDisplay::RemoveWidget | ( | glWidget * | widget, |
| bool | deleteWidget = true |
||
| ) |
Remove a widget from the window (and optionally delete it)
| void glDisplay::RemoveWidget | ( | uint32_t | index, |
| bool | deleteWidget = true |
||
| ) |
Remove a widget from the window (and optionally delete it)
| void glDisplay::Render | ( | float * | image, |
| uint32_t | width, | ||
| uint32_t | height, | ||
| float | x = 0.0f , |
||
| float | y = 30.0f , |
||
| bool | normalize = true |
||
| ) |
Render a CUDA float4 image using OpenGL interop If normalize is true, the image's pixel values will be rescaled from the range of [0-255] to [0-1] If normalize is false, the image's pixel values are assumed to already be in the range of [0-1] Note that if normalization is selected to be performed, it will be done in-place on the image.
| void glDisplay::Render | ( | glTexture * | texture, |
| float | x = 5.0f , |
||
| float | y = 30.0f |
||
| ) |
|
inline |
Render a CUDA image (uchar3, uchar4, float3, float4) using OpenGL interop.
This is similar to RenderOnce(), in that it will begin/end the frame also.
|
virtual |
Render a CUDA image (uchar3, uchar4, float3, float4) using OpenGL interop.
This is similar to RenderOnce(), in that it will begin/end the frame also.
Reimplemented from videoOutput.
| void glDisplay::RenderImage | ( | void * | image, |
| uint32_t | width, | ||
| uint32_t | height, | ||
| imageFormat | format, | ||
| float | x = 0.0f , |
||
| float | y = 30.0f , |
||
| bool | normalize = true |
||
| ) |
Render a CUDA image (uchar3, uchar4, float3, float4) using OpenGL interop.
If normalize is true, the image's pixel values will be rescaled from the range of [0-255] to [0-1] If normalize is false, the image's pixel values are assumed to already be in the range of [0-1] Note that if normalization is selected to be performed, it will be done in-place on the image
| void glDisplay::RenderLine | ( | float | x1, |
| float | y1, | ||
| float | x2, | ||
| float | y2, | ||
| float | r, | ||
| float | g, | ||
| float | b, | ||
| float | a = 1.0f , |
||
| float | thickness = 2.0f |
||
| ) |
Render a line in screen coordinates with the specified color.
| void glDisplay::RenderOnce | ( | float * | image, |
| uint32_t | width, | ||
| uint32_t | height, | ||
| float | x = 5.0f , |
||
| float | y = 30.0f , |
||
| bool | normalize = true |
||
| ) |
Begin the frame, render one CUDA float4 image using OpenGL interop, and end the frame.
Note that this function is only useful if you are rendering a single texture per frame. If normalize is true, the image's pixel values will be rescaled from the range of [0-255] to [0-1] If normalize is false, the image's pixel values are assumed to already be in the range of [0-1] Note that if normalization is selected to be performed, it will be done in-place on the image
| void glDisplay::RenderOnce | ( | void * | image, |
| uint32_t | width, | ||
| uint32_t | height, | ||
| imageFormat | format, | ||
| float | x = 5.0f , |
||
| float | y = 30.0f , |
||
| bool | normalize = true |
||
| ) |
Begin the frame, render one CUDA image using OpenGL interop, and end the frame.
Note that this function is only useful if you are rendering a single texture per frame. If normalize is true, the image's pixel values will be rescaled from the range of [0-255] to [0-1] If normalize is false, the image's pixel values are assumed to already be in the range of [0-1] Note that if normalization is selected to be performed, it will be done in-place on the image
| void glDisplay::RenderOutline | ( | float | x, |
| float | y, | ||
| float | width, | ||
| float | height, | ||
| float | r, | ||
| float | g, | ||
| float | b, | ||
| float | a = 1.0f , |
||
| float | thickness = 2.0f |
||
| ) |
Render the outline of a rect in screen coordinates with the specified color.
| void glDisplay::RenderRect | ( | float | r, |
| float | g, | ||
| float | b, | ||
| float | a = 1.0f |
||
| ) |
Render a filled rect covering the current viewport with the specified color.
| void glDisplay::RenderRect | ( | float | x, |
| float | y, | ||
| float | width, | ||
| float | height, | ||
| float | r, | ||
| float | g, | ||
| float | b, | ||
| float | a = 1.0f |
||
| ) |
Render a filled rect in screen coordinates with the specified color.
| void glDisplay::ResetCursor | ( | ) |
Reset the mouse cursor back to it's default.
The default mouse cursor is defined by SetDefaultCursor().
| void glDisplay::ResetDefaultCursor | ( | bool | activate = true | ) |
Reset the default cursor back to it's original, the arrow.
| activate | if true (default), the active cursor will be changed to this new default cursor immediately. If false , the active cursor will stay the same until ResetCursor() gets called in the future. |
| void glDisplay::ResetViewport | ( | ) |
Reset to the full viewport (and change back GL_PROJECTION)
| void glDisplay::SetBackgroundColor | ( | float | r, |
| float | g, | ||
| float | b, | ||
| float | a = 1.0f |
||
| ) |
Set the window's background color.
| r | background RGBA color, red component (0.0-1.0f) |
| g | background RGBA color, green component (0.0-1.0f) |
| b | background RGBA color, blue component (0.0-1.0f) |
| a | background RGBA color, alpha component (0.0-1.0f) |
| void glDisplay::SetCursor | ( | uint32_t | cursor | ) |
Set the active mouse cursor.
| cursor | one of the cursor ID's from X11/cursorfont.h |
| void glDisplay::SetDefaultCursor | ( | uint32_t | cursor, |
| bool | activate = true |
||
| ) |
Set the default mouse cursor that gets used by ResetCursor()
| cursor | one of the cursor ID's from X11/cursorfont.h . This will be the default cursor that gets set when ResetCursor() is called. |
| activate | if true (default), the active cursor will be changed to this new default cursor immediately. If false , the active cursor will stay the same until ResetCursor() gets called in the future. |
|
inline |
Set the dragging behavior mode.
| void glDisplay::SetFullscreen | ( | bool | fullscreen | ) |
Set the window to fullscreen mode or not.
| void glDisplay::SetMaximized | ( | bool | maximized | ) |
Maximize or un-maximize the window.
| void glDisplay::SetSize | ( | uint32_t | width, |
| uint32_t | height | ||
| ) |
Set the window's size.
| width | the desired width of the window, in pixels. |
| height | the desired height of the window, in pixels. |
|
virtual |
Set the window title string.
Reimplemented from videoOutput.
| void glDisplay::SetTitle | ( | const char * | str | ) |
Set the window title string.
| void glDisplay::SetViewport | ( | int | left, |
| int | top, | ||
| int | right, | ||
| int | bottom | ||
| ) |
Set the active viewport being rendered to.
SetViewport() will update the GL_PROJECTION matrix with a new ortho matrix to reflect these changes.
After done rendering to this viewport, you should reset it back to it's original with ResetViewport()
|
static |
Default title bar name.
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
staticprotected |
|
static |
Unique type identifier of glDisplay class.
| class glTexture |
OpenGL texture with CUDA interoperability.
Public Member Functions | |
| ~glTexture () | |
| Free the texture. More... | |
| bool | Bind () |
| Activate using the texture. More... | |
| void | Unbind () |
| Deactivate using the texture. More... | |
| void | Render (float x, float y) |
| Render the texture at the specified window coordinates. More... | |
| void | Render (float x, float y, float width, float height) |
| Render the texture with the specified position and size. More... | |
| void | Render (const float4 &rect) |
| Render the texture to the specific screen rectangle. More... | |
| uint32_t | GetID () const |
| Retrieve the OpenGL resource handle of the texture. More... | |
| uint32_t | GetWidth () const |
| Retrieve the width in pixels of the texture. More... | |
| uint32_t | GetHeight () const |
| Retrieve the height in pixels of the texture. More... | |
| uint32_t | GetFormat () const |
| Retrieve the texture's format (e.g. More... | |
| uint32_t | GetSize () const |
| Retrieve the size in bytes of the texture. More... | |
| void * | Map (uint32_t device, uint32_t flags) |
| Map the texture for accessing from the CPU or CUDA. More... | |
| void | Unmap () |
| Unmap the texture from CPU/CUDA access. More... | |
| bool | Copy (void *ptr, uint32_t flags) |
| Copy entire contents of the texture to/from CPU or CUDA memory. More... | |
| bool | Copy (void *ptr, uint32_t size, uint32_t flags) |
| Copy contents of the texture to/from CPU or CUDA memory. More... | |
| bool | Copy (void *ptr, uint32_t offset, uint32_t size, uint32_t flags) |
| Copy contents of the texture to/from CPU or CUDA memory. More... | |
Static Public Member Functions | |
| static glTexture * | Create (uint32_t width, uint32_t height, uint32_t format, void *data=NULL) |
| Allocate an OpenGL texture. More... | |
| glTexture::~glTexture | ( | ) |
Free the texture.
| bool glTexture::Bind | ( | ) |
Activate using the texture.
| bool glTexture::Copy | ( | void * | ptr, |
| uint32_t | flags | ||
| ) |
Copy entire contents of the texture to/from CPU or CUDA memory.
| ptr | the memory pointer to copy to/from, either in CPU or CUDA address space depending on flags. It's assumed that the size of the memory from this pointer is equal to GetSize(), and the entire contents of the buffer will be copied. |
| flags | should be one of the following:
|
| bool glTexture::Copy | ( | void * | ptr, |
| uint32_t | offset, | ||
| uint32_t | size, | ||
| uint32_t | flags | ||
| ) |
Copy contents of the texture to/from CPU or CUDA memory.
| ptr | the memory buffer to copy to/from, either in CPU or CUDA address space depending on flags |
| offset | the offset into the OpenGL buffer to copy. It is assumed any offset to the CPU/CUDA pointer argument has already been applied. |
| size | the number of bytes to copy |
| flags | should be one of the following:
|
| bool glTexture::Copy | ( | void * | ptr, |
| uint32_t | size, | ||
| uint32_t | flags | ||
| ) |
Copy contents of the texture to/from CPU or CUDA memory.
| ptr | the memory pointer to copy to/from, either in CPU or CUDA address space depending on flags. |
| size | the number of bytes to copy |
| flags | should be one of the following:
|
|
static |
Allocate an OpenGL texture.
| width | the width of the texture in pixels |
| height | the height of the texture in pixels |
| format | GL_RGBA8, GL_RGBA32F, ect. |
| data | initialize the texture's memory with this CPU pointer, size is width*height*bpp |
|
inline |
Retrieve the texture's format (e.g.
GL_RGBA8, GL_RGBA32F, ect.)
|
inline |
Retrieve the height in pixels of the texture.
|
inline |
Retrieve the OpenGL resource handle of the texture.
|
inline |
Retrieve the size in bytes of the texture.
|
inline |
Retrieve the width in pixels of the texture.
| void* glTexture::Map | ( | uint32_t | device, |
| uint32_t | flags | ||
| ) |
Map the texture for accessing from the CPU or CUDA.
| device | either GL_MAP_CPU or GL_MAP_CUDA |
| flags | should be one of the following:
|
| void glTexture::Render | ( | const float4 & | rect | ) |
Render the texture to the specific screen rectangle.
| void glTexture::Render | ( | float | x, |
| float | y | ||
| ) |
Render the texture at the specified window coordinates.
| void glTexture::Render | ( | float | x, |
| float | y, | ||
| float | width, | ||
| float | height | ||
| ) |
Render the texture with the specified position and size.
| void glTexture::Unbind | ( | ) |
Deactivate using the texture.
| void glTexture::Unmap | ( | ) |
Unmap the texture from CPU/CUDA access.
| class glWidget |
OpenGL graphics widget for rendering moveable/resizable shapes.
Public Types | |
| enum | Shape { Rect, Line, Ellipse } |
| Shape enum. More... | |
| typedef bool(* | glWidgetEventHandler) (glWidget *widget, uint16_t event, int a, int b, void *user) |
| Event message handler callback for recieving UI messages from widgets. More... | |
Public Member Functions | |
| glWidget (Shape shape=Rect) | |
| Constructor. More... | |
| glWidget (float x, float y, float width, float height, Shape shape=Rect) | |
| Constructor. More... | |
| virtual | ~glWidget () |
| Destructor. More... | |
| bool | Contains (float x, float y) const |
| Test if the point is inside the widget. More... | |
| void | Move (float x, float y) |
| Move the widget's position by the specified offset. More... | |
| float | X () const |
| Get the widget's X coordinate. More... | |
| float | Y () const |
| Get the widget's Y coordinate. More... | |
| void | SetX (float x) |
| Set the widget's X coordinate. More... | |
| void | SetY (float y) |
| Set the widget's Y coordinate. More... | |
| float | Width () const |
| Get the widget's width. More... | |
| float | Height () const |
| Get the widget's height. More... | |
| void | SetWidth (float width) |
| Set the widget's width. More... | |
| void | SetHeight (float height) |
| Set the widget's height. More... | |
| void | GetPosition (float *x, float *y) const |
| Get position of widget in global window coordinates. More... | |
| void | SetPosition (float x, float y) |
| Set position of widget in global window coordinates. More... | |
| void | GetCoords (float *x1, float *y1, float *x2, float *y2) const |
| Get the bounding coordinates of the widget. More... | |
| void | SetCoords (float x1, float y1, float x2, float y2) |
| Set the bounding coordinates of the widget. More... | |
| void | GetSize (float *width, float *height) const |
| Get the widget's size. More... | |
| void | SetSize (float width, float height) |
| Set the widget's size. More... | |
| Shape | GetShape () const |
| Get the shape. More... | |
| void | SetShape (Shape shape) |
| Set the shape. More... | |
| void | SetFillAlpha (float a) |
| Set fill alpha. More... | |
| void | SetLineAlpha (float a) |
| Set outline alpha. More... | |
| void | SetLineWidth (float width) |
| Set outline width. More... | |
| void | SetFillColor (float r, float g, float b, float a=1.0f) |
| Set fill color. More... | |
| void | SetLineColor (float r, float g, float b, float a=1.0f) |
| Set outline color. More... | |
| void | SetSelectedFillColor (float r, float g, float b, float a=1.0f) |
| Set selected fill color. More... | |
| void | SetSelectedLineColor (float r, float g, float b, float a=1.0f) |
| Set selected outline color. More... | |
| bool | IsMoveable () const |
| Is the widget moveable/draggable by the user? More... | |
| void | SetMoveable (bool moveable) |
| Toggle if the user can move/drag the widget. More... | |
| bool | IsResizeable () const |
| Is the widget resizeable by the user? More... | |
| void | SetResizeable (bool resizeable) |
| Toggle if the user can resize the widget. More... | |
| bool | IsSelected () const |
| Is the widget selected? More... | |
| void | SetSelected (bool selected) |
| Select/de-select the widget. More... | |
| bool | IsVisible () const |
| Is the widget visible. More... | |
| void | SetVisible (bool visible) |
| Show/hide the widget. More... | |
| void * | GetUserData () const |
| Retrieve user data. More... | |
| void | SetUserData (void *user) |
| Set user-defined data. More... | |
| glDisplay * | GetDisplay () const |
| Get the root window of the widget. More... | |
| int | GetIndex () const |
| Get the index of the widget in the window (or -1 if none) More... | |
| void | Render () |
| Render (automatically called by parent) More... | |
| void | GlobalToLocal (float x, float y, float *x_out, float *y_out) const |
| Convert from global window coordinates to local widget offset. More... | |
| void | LocalToGlobal (float x, float y, float *x_out, float *y_out) const |
| Convert from local widget offset to global window coordinates. More... | |
| void | AddEventHandler (glWidgetEventHandler callback, void *user=NULL) |
| Register an event message handler the widget will send events to. More... | |
| void | RemoveEventHandler (glWidgetEventHandler callback, void *user=NULL) |
| Remove an event message handler from being called by the widget. More... | |
| bool | OnEvent (uint16_t event, int a, int b, void *user) |
Protected Types | |
| enum | DragState { DragNone, DragMove, DragResizeN, DragResizeNW, DragResizeNE, DragResizeS, DragResizeSW, DragResizeSE, DragResizeW, DragResizeE } |
Protected Member Functions | |
| void | initDefaults () |
| void | setCursor (DragState cursor) |
| void | setDisplay (glDisplay *display) |
| void | dispatchEvent (uint16_t msg, int a, int b) |
| DragState | coordToBorder (float x, float y, float max_distance=10.0f) |
Protected Attributes | |
| float | mX |
| float | mY |
| float | mWidth |
| float | mHeight |
| float | mSelectedFillColor [4] |
| float | mSelectedLineColor [4] |
| float | mFillColor [4] |
| float | mLineColor [4] |
| float | mLineWidth |
| bool | mMoveable |
| bool | mResizeable |
| bool | mSelected |
| bool | mVisible |
| Shape | mShape |
| void * | mUserData |
| glDisplay * | mDisplay |
| DragState | mDragState |
| std::vector< eventHandler > | mEventHandlers |
Friends | |
| class | glDisplay |
| typedef bool(* glWidget::glWidgetEventHandler) (glWidget *widget, uint16_t event, int a, int b, void *user) |
Event message handler callback for recieving UI messages from widgets.
Recieves 4 parameters - the widget that sent the event, the event type, a & b message values (
Event message handlers should return true
if the message was handled, or false
if the message was skipped or not handled.
|
protected |
| enum glWidget::Shape |
|
virtual |
Destructor.
| void glWidget::AddEventHandler | ( | glWidgetEventHandler | callback, |
| void * | user = NULL |
||
| ) |
Register an event message handler the widget will send events to.
| callback | function pointer to the event message handler callback |
| user | optional user-specified pointer that will be passed to all invocations of this event handler (typically an object) |
| bool glWidget::Contains | ( | float | x, |
| float | y | ||
| ) | const |
Test if the point is inside the widget.
|
protected |
|
protected |
|
inline |
Get the bounding coordinates of the widget.
|
inline |
Get the root window of the widget.
| int glWidget::GetIndex | ( | ) | const |
Get the index of the widget in the window (or -1 if none)
|
inline |
Get position of widget in global window coordinates.
|
inline |
Get the shape.
|
inline |
Get the widget's size.
|
inline |
Retrieve user data.
| void glWidget::GlobalToLocal | ( | float | x, |
| float | y, | ||
| float * | x_out, | ||
| float * | y_out | ||
| ) | const |
Convert from global window coordinates to local widget offset.
|
inline |
Get the widget's height.
|
protected |
|
inline |
Is the widget moveable/draggable by the user?
|
inline |
Is the widget resizeable by the user?
|
inline |
Is the widget selected?
|
inline |
Is the widget visible.
| void glWidget::LocalToGlobal | ( | float | x, |
| float | y, | ||
| float * | x_out, | ||
| float * | y_out | ||
| ) | const |
Convert from local widget offset to global window coordinates.
|
inline |
Move the widget's position by the specified offset.
| bool glWidget::OnEvent | ( | uint16_t | event, |
| int | a, | ||
| int | b, | ||
| void * | user | ||
| ) |
| void glWidget::RemoveEventHandler | ( | glWidgetEventHandler | callback, |
| void * | user = NULL |
||
| ) |
Remove an event message handler from being called by the widget.
RemoveEventHandler() will search for previously registered event handlers that have the same function pointer and/or user pointer, and remove them for being called again in the future.
| void glWidget::Render | ( | ) |
Render (automatically called by parent)
|
inline |
Set the bounding coordinates of the widget.
|
protected |
|
protected |
|
inline |
Set fill alpha.
|
inline |
Set fill color.
|
inline |
Set the widget's height.
|
inline |
Set outline alpha.
|
inline |
Set outline color.
|
inline |
Set outline width.
|
inline |
Toggle if the user can move/drag the widget.
|
inline |
Set position of widget in global window coordinates.
|
inline |
Toggle if the user can resize the widget.
|
inline |
Select/de-select the widget.
|
inline |
Set selected fill color.
|
inline |
Set selected outline color.
|
inline |
Set the shape.
|
inline |
Set the widget's size.
|
inline |
Set user-defined data.
|
inline |
Show/hide the widget.
|
inline |
Set the widget's width.
|
inline |
Set the widget's X coordinate.
|
inline |
Set the widget's Y coordinate.
|
inline |
Get the widget's width.
|
inline |
Get the widget's X coordinate.
|
inline |
Get the widget's Y coordinate.
|
friend |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
| #define GL | ( | x | ) | { x; glCheckError( #x, __FILE__, __LINE__ ); } |
OpenGL error-checking macro.
| #define GL_CHECK | ( | msg | ) | { glCheckError(msg, __FILE__, __LINE__); } |
Print a message on OpenGL error.
| #define GL_FROM_CPU 0x3 |
Copy the buffer from CPU to OpenGL.
| #define GL_FROM_CUDA 0x4 |
Copy the buffer from CUDA to OpenGL.
| #define GL_INDEX_BUFFER GL_ELEMENT_ARRAY_BUFFER |
Alias for index buffers.
| #define GL_MAP_CPU 0x1 |
Map the buffer to CPU address space.
| #define GL_MAP_CUDA 0x2 |
Map the buffer to CUDA address space.
| #define GL_READ_ONLY GL_READ_ONLY_ARB |
Map the buffer with read-only access.
| #define GL_READ_WRITE GL_READ_WRITE_ARB |
Map the buffer with read/write access.
| #define GL_RGB32F GL_RGB32F_ARB |
Alias for GL_RGB32F.
| #define GL_RGBA32F GL_RGBA32F_ARB |
Alias for GL_RGBA32F.
| #define GL_TO_CPU 0x5 |
Copy the buffer to CPU from OpenGL.
| #define GL_TO_CUDA 0x6 |
Copy the buffer to CUDA from OpenGL.
| #define GL_VERIFY | ( | x | ) | { x; if(glCheckError( #x, __FILE__, __LINE__ )) return false; } |
Return false on OpenGL error.
| #define GL_VERIFYN | ( | x | ) | { x; if(glCheckError( #x, __FILE__, __LINE__ )) return NULL; } |
OpenGL NULL on OpenGL error.
| #define GL_VERTEX_BUFFER GL_ARRAY_BUFFER |
Alias for vertex buffers.
| #define GL_WRITE_DISCARD (GL_READ_WRITE + 0xff) |
Map the buffer as write-only and discard previous contents.
| #define GL_WRITE_ONLY GL_WRITE_ONLY_ARB |
Map the buffer with write-only access.
| #define KEY_PRESSED 1 |
Define for KEY_STATE and KEY_RAW events when key is pressed.
| #define KEY_RELEASED 0 |
Define for KEY_STATE and KEY_RAW events when key is released.
| #define LOG_GL "[OpenGL] " |
OpenGL logging prefix.
| #define MOUSE_LEFT 1 |
Define for the left mouse button number.
| #define MOUSE_MIDDLE 2 |
Define for the middle mouse button (or scroll wheel button)
| #define MOUSE_PRESSED 1 |
Define for MOUSE_BUTTON event when button is pressed.
| #define MOUSE_RELEASED 0 |
Define for MOUSE_BUTTON event when button is released.
| #define MOUSE_RIGHT 3 |
Define for the right mouse button number.
| #define MOUSE_WHEEL_DOWN 5 |
Define for the mouse wheel scroll down button number.
| #define MOUSE_WHEEL_UP 4 |
Define for the mouse wheel scroll up button number.
| typedef bool(* glEventHandler) (uint16_t event, int a, int b, void *user) |
Event message handler callback for recieving UI messages from a window.
Recieves 4 parameters - the event type, a & b message values (see above), and a user-specified pointer from registration.
Event message handlers should return true
if the message was handled, or false
if the message was skipped or not handled.
| enum glEventType |
User interface event message types.
Each event message consists of the event type, a & b message values, and a user-specified pointer. The event types and message values are desribed below for each type of message.
These event messages are dispatched at runtime to glEventHandler callbacks that have been registered via glRegisterEvents()
| Enumerator | |
|---|---|
| MOUSE_MOVE | Message when the mouse has moved (relative coordinates) a = x position, relative to window top-left b = y position, relative to window top-left
|
| MOUSE_ABSOLUTE | Message when the mouse has moved (absolute coordinates) a = x position, in absolute screen coordinates b = y position, in absolute screen coordinates
|
| MOUSE_BUTTON | Message when a mouse button has been pressed/released. a = button ID b = MOUSE_PRESSED or MOUSE_RELEASED Here is the mapping of the mouse buttons to their ID: - 1 MOUSE_LEFT (left button)
|
| MOUSE_DRAG | Message when the left mouse button has been dragged. a = x delta (change in position) b = y delta (change in position)
|
| MOUSE_WHEEL | Message when the mouse wheel has been scrolled a = -1 for scrolled up, or +1 for scrolled down. |
| KEY_STATE | Message when a key state has changed (raw, without modifiers applied) a = raw key symbol (without modifier translation) b = KEY_PRESSED or KEY_RELEASED These raw symbols are left unmodified, so they won't be changed by keys like Shift, CapsLock, NumLock, ect. Letters will always be reported as lowercase. For example if you press Shift + a, it will still be reported as XK_a (a)
|
| KEY_MODIFIED | Message when a key has been pressed or released (with modifiers applied) a = key symbol (with modifier translations) b = KEY_PRESSED or KEY_RELEASED These symbols have modifiers applied (Shift, CapsLock, NumLock, ect), so for example if you press Shift + a, it will be reported as XK_A (A)
|
| KEY_CHAR | Message when a keyboard ASCII character (0-255) was entered. a = ASCII character (0-9, a-Z, !-?, ect.) These will have modifiers applied (Shift, CapsLock, NumLock, ect), so for example if you press Shift + a, it will be reported as 'A'. |
| WIDGET_CREATED | Message indicating that a widget has been created (e.g. from dragging) a = widget index into glDisplay::GetWidget() or glWidget::GetIndex()
|
| WIDGET_SELECTED | Message indicating that a widget has been selected (e.g. from dragging) a = widget index into glDisplay::GetWidget() or glWidget::GetIndex()
|
| WIDGET_MOVED | Message from a widget indicating that it's been moved by the user. This event is only sent if the user moved the widget in the GUI (i.e. if glWidget::IsMoveable() was set), and not if the widget was moved programatically via glWidget::Move(), glWidget::SetPosition(), glWidget::SetX(), glWidget::SetY(), ect. a = new X coordinate b = new Y coordinate
|
| WIDGET_RESIZED | Message from a widget indicating that it's been resized. This event is only sent if the user resized the widget in the GUI (i.e. if glWidget::IsResizable() was set), and not if the widget was resized programatically via glWidget::SetSize(), glWidget::SetWidth(), or glWidget::SetHeight(). a = new width b = new height
|
| WINDOW_RESIZED | Message indicating that the window has been resized. a = new width (in pixels) b = new height (in pixels) |
| WINDOW_CLOSED | Message indicating that the window is closing. (no parameters) |
|
inline |
OpenGL error check + logging.
|
inline |
OpenGL error-checking messsage function.
|
inline |
Render a line in screen coordinates with the specified color.
|
inline |
Render the outline of a rect in screen coordinates with the specified color.
|
inline |
Render a filled rect in screen coordinates with the specified color.
| glDisplay* glGetDisplay | ( | uint32_t | display = 0 | ) |
Retrieve a display window object.
| uint32_t glGetNumDisplays | ( | ) |
Return the number of created glDisplay windows.
|
inline |
Print the amount of free GPU memory.


Safe Numerics |
A safe<T, PP , EP>
can be used anywhere a type T
can be used. Any expression which uses this type is guaranteed to return
an arithmetically correct value or to trap in some way.
PP |
A type which specifies the result type of an expression using safe types. |
EP |
A type containing members which are called when a correct result cannot be returned |
| Parameter | Type Requirements | Description |
|---|---|---|
T |
Integer<T> | The underlying type. Currently only integer types are supported |
PP |
PromotionPolicy<PP> | Default value is |
EP |
Exception Policy<EP> | Default value is |
See examples below.
Implements all expressions and only those expressions defined by the SafeNumeric type requirements. Thus, the result type of such an expression will be another safe type. The actual type of the result of such an expression will depend upon the specific promotion policy template parameter.
The most common usage would be safe<T> which uses the default promotion and exception policies. This type is meant to be a "drop-in" replacement of the intrinsic integer types. That is, expressions involving these types will be evaluated into result types which reflect the standard rules for evaluation of C++ expressions. Should it occur that such evaluation cannot return a correct result, an exception will be thrown.
There are two aspects of the operation of this type which can be customized with a policy. The first is the result type of an arithmetic operation. C++ defines the rules which define this result type in terms of the constituent types of the operation. Here we refer to these rules as "type promotion" rules. These rules will sometimes result in a type which cannot hold the actual arithmetic result of the operation. This is the main motivation for making this library in the first place. One way to deal with this problem is to substitute our own type promotion rules for the C++ ones.
The following program will throw an exception and emit an error message at runtime if any of several events result in an incorrect arithmetic type. Behavior of this program could vary according to the machine architecture in question.
#include <exception> #include <iostream> #include <boost/numeric/safe.hpp> void f(){ using namespace boost::numeric; safe<int> j; try { safe<int> i; std::cin >> i; // could overflow ! j = i * i; // could overflow } catch(std::exception & e){ std::cout << e.what() << std::endl; } std::cout << j; }
The term "drop-in replacement" reveals the aspiration of this library. In most cases, this aspiration is realized. But in some cases it isn't and can't be. Consider:
void f(int); int main(){ long x; f(x); // OK - builtin implicit version safe<long> y; f(y); // compile time error return 0; }
The built-in integer types are freely and silently converted to other integer types in order to permit passing of integer arguments to other function types. Our view is that this is bad practice and creates the possibility of subtle bugs. It conflicts with the purpose of the library in a fundamental way. The library specifies that these conversions are errors that are to be invoked at compile time. If one wants to switch between safe and built-in types via an alias, this type of code will have to be fixed so that implicit conversions to built-in types do not occur. In our view, this will be a net improvement to the code in any case.
In some instances, catching an error at run time is not
sufficient. We want to be sure that the program can never fail. To
achieve this, use the loose_trap_policy
rather than the default_exception_policy
.
The following program will emit a compile error at any statement which might possibly result in incorrect behavior.
This is because there is no way to guarantee that the expression i * i will return an arithmetically correct result. Since we know that the program cannot compile if there is any possibility of arithmetic error, we can dispense with the exception handling used above.
#include <iostream> #include <boost/numeric/safe.hpp> void f(){ using safe_int = safe<int, boost::numeric::native, boost::numeric::trap_exception>; safe_int i; std::cin >> i; // could throw exception here !!! safe_int j; j = i * i; // could throw exception here !!! }
Another way to avoid arithmetic errors like overflow is to promote types to larger sizes before doing the arithmetic.
Stepping back, we can see that many of the cases of invalid
arithmetic wouldn't exist if the result types were larger. So we can
avoid these problems by replacing the C++ type promotion rules for
expressions with our own rules. This can be done by specifying a
non-default type promotion policy automatic
. The policy
stores the result of an expression in the smallest size that can
accommodate the largest value that an expression can yield. All the work
is done at compile time - no checking for exceptions is necessary (input
is of course an exception). The following example illustrates
this.
#include <boost/numeric/safe.hpp> #include <iostream> void f(){ using safe_int = safe< int, boost::numeric::automatic, boost::numeric::default_exception_policy >; safe_int i; std::cin >> i; // might throw exception auto j = i * i; // won't ever trap - result type can hold the maximum value of i * i static_assert(boost::numeric::is_safe<decltype(j)>::value); // result is another safe type static_assert( std::numeric_limits<decltype(i * i)>::max() >= std::numeric_limits<safe_int>::max() * std::numeric_limits<safe_int>::max() ); // always true }


Torque 2D - Collisions Tutorial
In this tutorial, you'll learn how to set up collisions and collision detection in Torque 2D (T2D). You'll need to use the collision detection system any time you want to check if one of your game objects hits another. This can be used for all sorts of things, from making balls bounce, to making missiles explode, to opening doors when the player reaches them.
To prepare for this tutorial, run Torque 2D and load the TutorialBase
project (if it's not already loaded) by choosing Open Project... from the
file menu and selecting games/TutorialBase/project.t2dProj. Next, create a new scene by
selecting New Scene from the file menu. Finally,
choose Save As
from the file menu to save this
new scene. Also, be sure to save your scene with the name
"CollisionTutorial".
Now that we've got a blank slate, it's time to bring some objects into the scene so we can make them collide. Select the Create tab in the Scene Editor and open the Static Sprites section. Drag an asteroid and a block (from the tileMapImageMap) into the scene as shown below.
Finally, we're going give the asteroid some gravity so later we can make it collide with the other objects. To do this, select the asteroid by clicking on it, then choose the Edit tab on the right side of the Scene Editor. Scroll down until you see the Physics section, then expand it by clicking on the arrow. In order to make the asteroid fall downward, change the Constant Force Y property to "40" and press Enter. Save your scene as "CollisionTutorial" and preview the scene by pressing the Play Scene button in the toolbar. For now, the asteroid just falls down over the crate. We're going to just set up a few basic kinds of collision in the upcoming sections.
Select the asteroid sprite in the Scene View and open the Collision section in the Edit tab. All the collision properties that we are going to use are in this section. For now, just turn on the asteroid's collision detection by selecting Send Collision and Receive Collision. Next, select the crate and check only Receive Collision. Save the scene and press Play Scene to watch the action.
Okay, admittedly that wasn't much in the way of action; the asteroid just stops when it hits the crate. However, the main thing to note is that they are reacting to each other. Let's see what other effects we can set up for collisions...
Now that the block and the asteroids respond to each other, we can play with some of our other options. The Response Mode dropdown contains the possible responses that objects can have to collisions. Select the asteroid and take a look at the Response Mode options. Notice that we were using CLAMP. Here is a brief description of the possibilities:
BOUNCE: A simple, pong-style bouncing effect.
CLAMP: The colliding object slides along the surface it hits. This is good for surfaces that the player moves along.
STICKY: The colliding object completely stops.
KILL: The colliding object is deleted.
RIGID: The colliding object will react using built-in rigid body physics.
Let's create examples for a few of our response options. Change the crate's response mode to KILL and preview the scene. Now it disappears when the asteroid hits it. Now, change the asteroid's response mode to BOUNCE and preview again. The crate still disappears, only this time, the asteroid bounces. Make sure to set the crate back to CLAMP when you're done.
Deselect all the objects on the screen by clicking on a blank area in the Scene View. In the Edit tab, you'll now see the Debug Rendering section. Open it and select Collision Bounds as shown below.
You can now see the collision bounds (in green) for all the objects on the screen. Specifically, 'collision bounds' are the shapes that Torque uses to check if an object collides with another object. Notice that currently they are all squares. Thankfully, there is an easy way to make our objects collide more realistically: custom collision polygons!
We'll set up the asteroid to use polygon collision. What we want to do is change its 'collision polygon'. An object's collision polygon is the shape that is used to determine if it collided with something. Select the asteroid. Notice that in the Edit tab the Detection Mode for it is already set to POLYGON. Move your mouse over the asteroid's sprite in the Scene View, and click on the far left widget that appears above it - Edit this object's collision polygon as shown below. From here, you will want to use the collision editor to modify your scene object's collision polygon. If you're unsure on how to do this click here.If you're unsure on how to do this click here.
For game purposes, something similar to what you see below will work fine:
Now if you place your box slightly to the left of the the asteroid as shown below, it should bounce off at an angle when you run the game.
Finally, if you want to give the asteroid some space to bounce around, you can copy and paste more blocks and even stretch and rotate them to make an environment for the asteroid to bounce in as shown below. To change scale and rotation, modify the the Size and Rotation values under the Edit tab with the object selected.
Usually, you don't want every object in your game colliding with every other object. For instance, you probably don't want a player's ship to collide with its own missiles, and likewise you might not want objects in the foreground to collide with objects in the background. That's what the Collision Layers and Collision Groups properties are for.
As far as collisions go, Collision Layers and Collision Groups operate in a very similar way. They work together to determine which objects can collide with each other. By default, an object collides with objects in all layers and in all groups. By default, all objects start on layer zero and in group zero. To see Collision Layers and Collision Groups in action, we're going to make the asteroid not collide with objects in layer 1 or objects in group 2. Select the asteroid then, in the Edit tab, click the 1 button in its Collision Layers property to turn it off and then click on the 2 in its Collision Groups.
Now, select the block object and go to the Scene Object section in the Edit tab. In there, change the Layer to "1". Now it is on layer one, and the asteroid will not collide with objects on layer one. The last thing we have to do is make a block not collide with objects on layer zero.  Press Play Scene to see the asteroid and the block not collide.
To see Collision Groups in action, change another block's group to "2" in Scene Object properties and turn off the 0 in its Collision Groups. Notice that when one object touches a second object, the second object must be in the correct layer and group to cause a collision... just one or the other isn't enough.
The four check boxes at the top of an object's collision properties, Send/Receive Collisions and Send/Receive Physics define the object's participation in the collision system.
Using these properties individually (for example, turning Send on but leaving Receive off) can have some unpredictable effects. Often it will be necessary for you to experiment to get these settings right. Here's a basic explanation...
Objects that have "send collision" active can be thought of as active colliders while objects that have "receive collision" active can be thought of as passive colliders. A collision will only be detected between objects if one of the objects is an active collider and the other is a passive collider. Keep in mind that an object can both send and receive collisions.
Send and receive physics are treated slightly differently. Send physics dictates whether or not the object's default physics response will be used when it is sending the collision. Receive physics dictates whether or not the object's default physics response will be used when it is receiving the collision.
This tutorial has covered some of the basics of collisions in T2D. Collisions can still be quite complicated; you will probably have a fair amount of experimenting to do in order to set them up properly in your game. Generally, a completed game will do a lot of collision handling in script. The features here are good for setting up prototypes and can often be used in your finished product; however, you will almost certainly have to handle some part of your collisions outside the Scene Editor.


Sketch Pad
New
Etch OFF
Turning
Etch ON
will enable drawing using the device's accelerometer by tilting the device in any direction.


Registration
*
indicate required information
Please fill in the details
First Name*
Middle Name
Last Name*
Owner Name*
Shop Name*
Shop License Number*
Address*
Phone Number*
City*
State*
Country*
Email*
User Name*
Password*
Confirm Password*
Gender*
Select
Male
Female
Other
How do u know about us?
I agree to the Privacy Policy and Terms & Conditions


{% block beforehead %}{% endblock %}
Powered by Awesome Python Webapp. Copyright © 2016. [Manage]
github.com/ianzhengnan. All rights reserved.


PlayStation 5 concept video gives hint at what Sony's 2020 console could look like
The video includes several animated 3D renders of the console based on rumours, as well as the minimal details already revealed by Sony
by Shivali Best, https://www.facebook.com/shivalibestjournalist/There’s still well over a year to go before Sony finally unveils its PlayStation 5 console, but a new concept video gives us a hint of what to expect.
The video, created by TURN ON, includes several animated 3D renders of the console based on rumours, as well as the minimal details already revealed by Sony.
Key features highlighted in the video, which was first reported by LetsGoDigital , include an 8K resolution, 3D audio, and an SSD, rather than an HDD.
The video also gives us a glimpse at the PlayStation 5 controller, which Sony has already revealed several details on.
The controller will have haptic feedback and adaptive triggers, giving gamers real-time feedback during games.
This was confirmed in a blog by CEO, Jim Ryan, back in October.
He said: “There are two key innovations with the PlayStation 5’s new controller. First, we’re adopting haptic feedback to replace the “rumble” technology found in controllers since the 5th generation of consoles.
“With haptics, you truly feel a broader range of feedback, so crashing into a wall in a race car feels much different than making a tackle on the football field. You can even get a sense for a variety of textures when running through fields of grass or plodding through mud.
“The second innovation is something we call adaptive triggers, which have been incorporated into the trigger buttons (L2/R2).
“Developers can program the resistance of the triggers so that you feel the tactile sensation of drawing a bow and arrow or accelerating an off-road vehicle through rocky terrain. In combination with the haptics, this can produce a powerful experience that better simulates various actions.”
Unfortunately, there’s still a bit of a wait before the PlayStation 5 is finally unveiled - Sony has confirmed a launch date of ‘Holiday 2020’.


Nicholas's Assignments
Sprint 1
My Favorite Hobby
Sprint 2
Dice Roller
Modified Syllabus
Regular Expression Tester
Sprint 3
Coming soon
Sprint 4
Coming soon
Sprint 5
Coming soon
Sprint 6
Coming soon
Sprint 7
Coming soon
Sprint 8
Coming soon