add and update samples for CUDA 11.6

This commit is contained in:
Rutwik Choughule
2022-01-13 11:35:24 +05:30
parent 11de19f00c
commit 2e41896e1b
4615 changed files with 178150 additions and 181350 deletions

View File

@@ -0,0 +1,18 @@
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"${workspaceFolder}/../../../Common"
],
"defines": [],
"compilerPath": "/usr/local/cuda/bin/nvcc",
"cStandard": "gnu17",
"cppStandard": "gnu++14",
"intelliSenseMode": "linux-gcc-x64",
"configurationProvider": "ms-vscode.makefile-tools"
}
],
"version": 4
}

View File

@@ -0,0 +1,7 @@
{
"recommendations": [
"nvidia.nsight-vscode-edition",
"ms-vscode.cpptools",
"ms-vscode.makefile-tools"
]
}

View File

@@ -0,0 +1,10 @@
{
"configurations": [
{
"name": "CUDA C++: Launch",
"type": "cuda-gdb",
"request": "launch",
"program": "${workspaceFolder}/EGLSync_CUDAEvent_Interop"
}
]
}

View File

@@ -0,0 +1,15 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "sample",
"type": "shell",
"command": "make dbg=1",
"problemMatcher": ["$nvcc"],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

View File

@@ -0,0 +1,783 @@
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Simple interop app demonstrating EGLImage + EGLSync interop with CUDA.
// Using EGLSync - CUDA Event interop one can achieve synchronization on GPU
// itself for GL-EGL-CUDA operations instead of blocking CPU for
// synchronization. This app requires GLES 3.2 or higher
//---------------------------INCLUDES---------------------------------//
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "graphics_interface.h"
#include <cuda.h>
#include <helper_cuda_drvapi.h>
#include <cudaEGL.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES3/gl32.h>
#include "egl_common.h"
//---------------------------DEFINES---------------------------------//
#define MAX_ITR 100
#define FAILURE 0
#define SUCCESS 1
#define WAIVED 2
#define BLOCK_SIZE 16
#define GL_READ 0
#define GL_WRITE 1
//---------------------------MACROS---------------------------------//
// Error-checking wrapper around GL calls
#define GL_SAFE_CALL(call) \
{ \
GLenum err; \
call; \
err = glGetError(); \
if (err != GL_NO_ERROR) { \
fprintf(stderr, "%s:%d GL error: %d\n", __FILE__, __LINE__, err); \
cleanup(FAILURE); \
} \
}
#define GL_SAFE_CALL_NO_CLEANUP(call, err) \
{ \
GLenum status; \
call; \
status = glGetError(); \
if (status != GL_NO_ERROR) { \
fprintf(stderr, "%s:%d GL error: %d\n", __FILE__, __LINE__, status); \
err = status; \
} \
}
// Error-checking wrapper around CUDA calls (taken from cutil.h)
#define CUDA_SAFE_CALL(call) \
do { \
cudaError err = call; \
if (cudaSuccess != err) { \
fprintf(stderr, "Cuda error in file '%s' in line %i : %s.\n", __FILE__, \
__LINE__, cudaGetErrorString(err)); \
cleanup(FAILURE); \
} \
} while (0)
#define CUDA_SAFE_CALL_NO_CLEANUP(call, err) \
do { \
cudaError status = call; \
if (cudaSuccess != status) { \
fprintf(stderr, "Cuda error in file '%s' in line %i : %s.\n", __FILE__, \
__LINE__, cudaGetErrorString(status)); \
err = status; \
} \
} while (0)
#if defined(EXTENSION_LIST)
EXTENSION_LIST(EXTLST_DECL)
typedef void (*extlst_fnptr_t)(void);
static struct {
extlst_fnptr_t *fnptr;
char const *name;
} extensionList[] = {EXTENSION_LIST(EXTLST_ENTRY)};
int eglSetupExtensions(void) {
unsigned int i;
for (i = 0; i < (sizeof(extensionList) / sizeof(*extensionList)); i++) {
*extensionList[i].fnptr = eglGetProcAddress(extensionList[i].name);
if (*extensionList[i].fnptr == NULL) {
printf("Couldn't get address of %s()\n", extensionList[i].name);
return 0;
}
}
return 1;
}
#endif
#if defined(EXTENSION_LIST)
EXTENSION_LIST(EXTLST_EXTERN)
#endif
//------------------------GLOBAL VARIABLES--------------------------//
// GL texture
GLuint tex[2] = {0};
// Used to catch unexpected termination from GLUT
int cleanExit = 0;
// Use CPU Sync or GPU sync; Default GPU
int useGpu = 1;
// CUDA Resource
CUgraphicsResource writeResource = NULL;
CUgraphicsResource readResource = NULL;
CUarray writeArray, readArray;
CUdevice device;
CUcontext context;
// Which device to run on
unsigned int dev = 0;
// Default width, height, and iterations value
int width = 2048;
int height = 2048;
int itr = MAX_ITR;
// Error check variable
__device__ static unsigned int numErrors = 0;
//-----------------------FUNCTION PROTOTYPES------------------------//
void checkSync(int argc, char **argv);
int parseCmdLine(int argc, char **argv);
void printUsage(void);
void cleanup(int status);
void exitHandler(void);
void printStatus(int status);
void checkSyncOnCPU(void);
void checkSyncOnGPU(EGLDisplay dpy);
__global__ void verify_and_update_kernel(CUsurfObject write, CUsurfObject read,
char expected, char newval, int width,
int height);
extern "C" cudaError_t cudaGetValueMismatch();
//-----------------------FUNCTION DEFINITIONS------------------------//
int main(int argc, char *argv[]) {
#if defined(__linux__)
setenv("DISPLAY", ":0", 0);
#endif
parseCmdLine(argc, argv);
atexit(exitHandler);
checkSync(argc, argv);
return 0;
}
int parseCmdLine(int argc, char **argv) {
int i;
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "-cpu") == 0) {
useGpu = 0;
}
if (strcmp(argv[i], "-h") == 0) {
printUsage();
cleanup(SUCCESS);
}
if (strcmp(argv[i], "-width") == 0) {
++i;
if (i == argc) {
printf("width option must be followed by value\n");
return FAILURE;
}
if (sscanf(argv[i], "%d", &width) != 1) {
printf("Error: invalid width value\n");
return FAILURE;
}
}
if (strcmp(argv[i], "-height") == 0) {
++i;
if (i == argc) {
printf("height option must be followed by value\n");
return FAILURE;
}
if (sscanf(argv[i], "%d", &height) != 1) {
printf("Error: invalid height value\n");
return FAILURE;
}
}
if (strcmp(argv[i], "-itr") == 0) {
++i;
if (i == argc) {
printf("itr option must be followed by iteration value\n");
return FAILURE;
}
if (sscanf(argv[i], "%d", &itr) != 1) {
printf("Error: invalid iteration value\n");
return FAILURE;
}
}
}
return SUCCESS;
}
void printUsage(void) {
printf("Usage:\n");
printf("\t-h\tPrint command line options\n");
printf("\t-cpu\tSync on the CPU instead of the GPU\n");
printf("\t-width w\tSet the width to w\n");
printf("\t-height h\tSet the height to h\n");
printf("\t-itr i\tSet number of iterations to i\n");
}
void checkSync(int argc, char **argv) {
int x, y;
int bufferSize = width * height * 4;
unsigned char *pSurf_read = NULL, *pSurf_write = NULL;
int integrated;
CUresult status = CUDA_SUCCESS;
// Init values for variables
x = y = 0;
if (CUDA_SUCCESS != (status = cuInit(0))) {
printf("Failed to initialize CUDA\n");
}
device = findCudaDeviceDRV(argc, (const char **)argv);
if (CUDA_SUCCESS != (status = cuCtxCreate(&context, 0, device))) {
printf("failed to create CUDA context\n");
}
cuCtxPushCurrent(context);
status =
cuDeviceGetAttribute(&integrated, CU_DEVICE_ATTRIBUTE_INTEGRATED, device);
if (status != CUDA_SUCCESS) {
printf("Failed to get device attribute CU_DEVICE_ATTRIBUTE_INTEGRATED\n");
cleanup(FAILURE);
}
if (integrated != 1) {
printf(
"EGLSync_CUDAEvent_Interop does not support dGPU. Waiving sample.\n");
cleanup(WAIVED);
}
#if (defined(__arm__) || defined(__aarch64__)) && defined(__linux__)
graphics_setup_window(0, 0, width, height, "EGLSync_CUDA_Interop");
#endif
pSurf_read = (unsigned char *)malloc(bufferSize);
pSurf_write = (unsigned char *)malloc(bufferSize);
if (pSurf_read == NULL || pSurf_write == NULL) {
printf("malloc failed\n");
cleanup(FAILURE);
}
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
pSurf_read[(y * width + x) * 4] = 1;
pSurf_read[(y * width + x) * 4 + 1] = 1;
pSurf_read[(y * width + x) * 4 + 2] = 1;
pSurf_read[(y * width + x) * 4 + 3] = 1;
pSurf_write[(y * width + x) * 4] = 0;
pSurf_write[(y * width + x) * 4 + 1] = 0;
pSurf_write[(y * width + x) * 4 + 2] = 0;
pSurf_write[(y * width + x) * 4 + 3] = 0;
}
}
// NOP call to error-check the above glut calls
GL_SAFE_CALL({});
// Init texture
GL_SAFE_CALL(glGenTextures(2, tex));
GL_SAFE_CALL(glBindTexture(GL_TEXTURE_2D, tex[GL_READ]));
GL_SAFE_CALL(
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
GL_SAFE_CALL(
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
GL_SAFE_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0,
GL_RGBA, GL_UNSIGNED_BYTE, pSurf_read));
GL_SAFE_CALL(glBindTexture(GL_TEXTURE_2D, 0));
GL_SAFE_CALL(glBindTexture(GL_TEXTURE_2D, tex[GL_WRITE]));
GL_SAFE_CALL(
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
GL_SAFE_CALL(
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
GL_SAFE_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0,
GL_RGBA, GL_UNSIGNED_BYTE, pSurf_write));
GL_SAFE_CALL(glBindTexture(GL_TEXTURE_2D, 0));
glFinish();
EGLDisplay eglDisplayHandle = eglGetCurrentDisplay();
if (eglDisplayHandle == EGL_NO_DISPLAY) {
printf("eglDisplayHandle failed \n");
cleanup(FAILURE);
} else {
printf("eglDisplay Handle created \n");
}
if (!eglSetupExtensions()) {
printf("SetupExtentions failed \n");
cleanup(FAILURE);
}
EGLContext eglCtx = eglGetCurrentContext();
if (eglCtx == EGL_NO_CONTEXT) {
printf("Context1 create failed with error %d\n", eglGetError());
cleanup(FAILURE);
}
// Create the EGL_Image
EGLint eglImgAttrs[] = {EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE,
EGL_NONE};
EGLImageKHR eglImage1 =
eglCreateImageKHR(eglDisplayHandle, eglCtx, EGL_GL_TEXTURE_2D_KHR,
(EGLClientBuffer)(intptr_t)tex[GL_READ], eglImgAttrs);
if (eglImage1 == EGL_NO_IMAGE_KHR) {
printf("EGLImage create failed for read texture with error %d\n",
eglGetError());
cleanup(FAILURE);
} else {
printf("EGLImage1 created \n");
}
EGLImageKHR eglImage2 =
eglCreateImageKHR(eglDisplayHandle, eglCtx, EGL_GL_TEXTURE_2D_KHR,
(EGLClientBuffer)(intptr_t)tex[GL_WRITE], eglImgAttrs);
if (eglImage2 == EGL_NO_IMAGE_KHR) {
printf("EGLImage create failed for write texture with error %d\n",
eglGetError());
cleanup(FAILURE);
} else {
printf("EGLImage2 created \n");
}
glFinish();
status = cuGraphicsEGLRegisterImage(&writeResource, eglImage1,
CU_GRAPHICS_REGISTER_FLAGS_NONE);
if (status != CUDA_SUCCESS) {
printf("cuGraphicsEGLRegisterImage failed with Texture 1\n");
cleanup(FAILURE);
} else {
printf(
"cuGraphicsEGLRegisterImage Passed, writeResource created with texture "
"1\n");
}
status =
cuGraphicsSubResourceGetMappedArray(&writeArray, writeResource, 0, 0);
if (status != CUDA_SUCCESS) {
printf(
"cuGraphicsSubResourceGetMappedArray failed for writeResource with "
"texture 1\n");
cleanup(FAILURE);
}
status = cuGraphicsEGLRegisterImage(&readResource, eglImage2,
CU_GRAPHICS_REGISTER_FLAGS_NONE);
if (status != CUDA_SUCCESS) {
printf(
"cuGraphicsEGLRegisterImage failed for readResource with Texture 2\n");
cleanup(FAILURE);
} else {
printf(
"cuGraphicsEGLRegisterImage Passed, readResource created with texture "
"2\n");
}
status = cuGraphicsSubResourceGetMappedArray(&readArray, readResource, 0, 0);
if (status != CUDA_SUCCESS) {
printf("cuGraphicsSubResourceGetMappedArray failed for texture 2\n");
cleanup(FAILURE);
}
if (useGpu) {
printf("Using GPU Sync path\n");
checkSyncOnGPU(eglDisplayHandle);
} else {
printf("Using CPU Sync path\n");
checkSyncOnCPU();
}
free(pSurf_read);
free(pSurf_write);
cleanup(SUCCESS);
}
void checkSyncOnCPU(void) {
int z = 0;
unsigned char expectedData, newData;
CUresult status = CUDA_SUCCESS;
CUDA_RESOURCE_DESC wdsc, rdsc;
memset(&wdsc, 0, sizeof(wdsc));
memset(&rdsc, 0, sizeof(rdsc));
expectedData = 0;
newData = 1;
wdsc.resType = CU_RESOURCE_TYPE_ARRAY;
wdsc.res.array.hArray = writeArray;
CUsurfObject writeSurface;
rdsc.resType = CU_RESOURCE_TYPE_ARRAY;
rdsc.res.array.hArray = readArray;
CUsurfObject readSurface;
status = cuSurfObjectCreate(&writeSurface, &wdsc);
if (status != CUDA_SUCCESS) {
printf("Surface bounding failed with status %d\n", status);
cleanup(FAILURE);
}
status = cuSurfObjectCreate(&readSurface, &rdsc);
if (status != CUDA_SUCCESS) {
printf("Surface bounding failed\n");
cleanup(FAILURE);
}
for (z = 0; z < itr; z++) {
// GL call to copy from read texture to write texture
GL_SAFE_CALL(glCopyImageSubData(tex[GL_READ], GL_TEXTURE_2D, 0, 0, 0, 0,
tex[GL_WRITE], GL_TEXTURE_2D, 0, 0, 0, 0,
width, height, 1));
glFinish();
newData++;
expectedData++;
verify_and_update_kernel<<<(width * height) / 256, 256>>>(
writeSurface, readSurface, expectedData, newData, width, height);
status = cuCtxSynchronize();
if (status != CUDA_SUCCESS) {
printf("cuCtxSynchronize failed \n");
}
}
cudaError_t err = cudaGetValueMismatch();
if (err != cudaSuccess) {
printf("Value mismatch seen when using CPU sync\n");
cleanup(FAILURE);
}
// Clean up CUDA writeResource
status = cuGraphicsUnregisterResource(writeResource);
if (status != CUDA_SUCCESS) {
printf("Failed to unregister %d", status);
cleanup(FAILURE);
} else {
printf("Unregistered writeResource. \n");
}
// Clean up CUDA readResource
status = cuGraphicsUnregisterResource(readResource);
if (status != CUDA_SUCCESS) {
printf("Failed to unregister %d", status);
cleanup(FAILURE);
} else {
printf("Unregistered readResource. \n");
}
}
/*
Performs same function as checkSyncOnCPU
Here instead of glFinish() and cuCtxSynchronize like in checkSyncOnCPU,
we make use of EGLSync, CUDA Event and cuStreamWaitEvent, eglWaitSyncKHR to
achieve the synchronization due to this CPU is not blocked for any
synchronization needed between GL-EGL & CUDA operations all synchronizations
happens on the GPU only.
*/
void checkSyncOnGPU(EGLDisplay dpy) {
int z = 0;
unsigned char expectedData, newData;
cudaError_t err;
CUresult status = CUDA_SUCCESS;
CUstream stream;
CUevent timingDisabledEvent;
CUDA_RESOURCE_DESC wdsc, rdsc;
memset(&wdsc, 0, sizeof(wdsc));
memset(&rdsc, 0, sizeof(rdsc));
expectedData = 0;
newData = 1;
wdsc.resType = CU_RESOURCE_TYPE_ARRAY;
wdsc.res.array.hArray = writeArray;
CUsurfObject writeSurface;
rdsc.resType = CU_RESOURCE_TYPE_ARRAY;
rdsc.res.array.hArray = readArray;
CUsurfObject readSurface;
status = cuSurfObjectCreate(&writeSurface, &wdsc);
if (status != CUDA_SUCCESS) {
printf("Surface bounding failed with status %d\n", status);
cleanup(FAILURE);
}
status = cuSurfObjectCreate(&readSurface, &rdsc);
if (status != CUDA_SUCCESS) {
printf("Surface bounding failed\n");
cleanup(FAILURE);
}
status = cuStreamCreate(&stream, CU_STREAM_DEFAULT);
if (status != CUDA_SUCCESS) {
printf("Stream creation failed\n");
cleanup(FAILURE);
}
// Creates timing disabled event which uses non-blocking synchronization
status = cuEventCreate(&timingDisabledEvent, CU_EVENT_DISABLE_TIMING);
if (status != CUDA_SUCCESS) {
printf("Default event creation failed\n");
cleanup(FAILURE);
}
/*
1. We perform texture-to-texture copy in GLES which is async function
2. Followed by creating EGLSync and a CUDA Event from that EGLSync object
3. Using cuStreamWaitEvent() we wait in GPU for the GLES to finish texture
copy.
4. CUDA kernel verfiy_and_update_kernel verifies if the copied data by
GLES is correct, and it updates the buffer with new values.
5. This is followed by eglWaitSyncKHR() which waits for the cuda kernel to
finish, so that in the next iteration GLES can perform the copying of the
updated buffer to write texture,
*/
for (z = 0; z < itr; z++) {
// GL call to copy from read texture to write texture
GL_SAFE_CALL(glCopyImageSubData(tex[GL_READ], GL_TEXTURE_2D, 0, 0, 0, 0,
tex[GL_WRITE], GL_TEXTURE_2D, 0, 0, 0, 0,
width, height, 1));
EGLSyncKHR eglSyncForGL, eglSyncForCuda;
EGLBoolean egl_status = EGL_TRUE;
EGLAttribKHR eglattrib[] = {EGL_CUDA_EVENT_HANDLE_NV,
(EGLAttrib)timingDisabledEvent, EGL_NONE};
CUevent cudaEGLSyncEvent;
eglSyncForGL = eglCreateSyncKHR(dpy, EGL_SYNC_FENCE_KHR, NULL);
if (eglSyncForGL == EGL_NO_SYNC_KHR) {
printf(" EGL Sync creation failed\n");
cleanup(FAILURE);
}
status = cuEventCreateFromEGLSync(&cudaEGLSyncEvent, eglSyncForGL,
CU_EVENT_DEFAULT);
if (status != CUDA_SUCCESS) {
printf("CUDA event creation from EGLSync failed\n");
cleanup(FAILURE);
}
// We wait from CUDA in GPU for GL-EGL operation completion
status = cuStreamWaitEvent(stream, cudaEGLSyncEvent, 0);
if (status != CUDA_SUCCESS) {
printf("Stream wait for event created from EGLSync failed\n");
cleanup(FAILURE);
}
egl_status = eglDestroySyncKHR(dpy, eglSyncForGL);
if (egl_status != EGL_TRUE) {
printf("EGL sync object destruction failed\n");
cleanup(FAILURE);
}
newData++;
expectedData++;
// Verifies the values in readSurface which is copied by
// glCopyImageSubData() And writes value of newData into writeSurface
verify_and_update_kernel<<<(width * height) / 256, 256, 0, stream>>>(
writeSurface, readSurface, expectedData, newData, width, height);
status = cuEventDestroy(cudaEGLSyncEvent);
if (status != CUDA_SUCCESS) {
printf("Event Destroy failed\n");
cleanup(FAILURE);
}
status = cuEventRecord(timingDisabledEvent, stream);
if (status != CUDA_SUCCESS) {
printf("Event Record failed\n");
cleanup(FAILURE);
}
// creating an EGL sync object linked to a CUDA event object
eglSyncForCuda = eglCreateSync64KHR(dpy, EGL_SYNC_CUDA_EVENT_NV, eglattrib);
// We wait from EGL for CUDA operation completion
egl_status = eglWaitSyncKHR(dpy, eglSyncForCuda, 0);
if (egl_status != EGL_TRUE) {
printf("eglWaitSyncKHR failed\n");
cleanup(FAILURE);
}
egl_status = eglDestroySyncKHR(dpy, eglSyncForCuda);
if (egl_status != EGL_TRUE) {
printf("EGL sync object destruction failed\n");
cleanup(FAILURE);
}
}
err = cudaGetValueMismatch();
if (err != cudaSuccess) {
printf("Value mismatch seen when using GPU sync\n");
cleanup(FAILURE);
}
// Clean up CUDA writeResource
status = cuGraphicsUnregisterResource(writeResource);
if (status != CUDA_SUCCESS) {
printf("Failed to unregister %d", status);
cleanup(FAILURE);
} else {
printf("Unregistered writeResource. \n");
}
// Clean up CUDA readResource
status = cuGraphicsUnregisterResource(readResource);
if (status != CUDA_SUCCESS) {
printf("Failed to unregister %d", status);
cleanup(FAILURE);
} else {
printf("Unregistered readResource. \n");
}
}
// Verifies the values in readSurface whether they are expected ones
// And writes value of newData into writeSurface
__global__ void verify_and_update_kernel(CUsurfObject write, CUsurfObject read,
char expected, char newval, int width,
int height) {
unsigned int x = blockDim.x * blockIdx.x + threadIdx.x;
unsigned int y = blockDim.y * blockIdx.y + threadIdx.y;
if (x < width && y < height) {
uchar4 check;
surf2Dread(&check, read, x * 4, y);
if (check.x != expected || check.y != expected || check.z != expected ||
check.w != expected) {
printf(
"Mismatch found in values read[0]= %u read[1]= %u read[2]= %u "
"read[3]= %u expected is %u\n",
check.x, check.y, check.z, check.w, expected);
numErrors++;
return;
}
uchar4 data = make_uchar4(newval, newval, newval, newval);
surf2Dwrite(data, write, x * 4, y);
}
}
__global__ void getNumErrors(int *numErr) { *numErr = numErrors; }
extern "C" cudaError_t cudaGetValueMismatch() {
int numErr_h;
int *numErr_d = NULL;
cudaError_t err = cudaSuccess;
err = cudaMalloc(&numErr_d, sizeof(int));
if (err != cudaSuccess) {
printf("Cuda Main: cudaMemcpy failed with %s\n", cudaGetErrorString(err));
cudaFree(numErr_d);
return err;
}
getNumErrors<<<1, 1>>>(numErr_d);
err = cudaDeviceSynchronize();
if (err != cudaSuccess) {
printf("Cuda Main: cudaDeviceSynchronize failed with %s\n",
cudaGetErrorString(err));
}
err = cudaMemcpy(&numErr_h, numErr_d, sizeof(int), cudaMemcpyDeviceToHost);
if (err != cudaSuccess) {
printf("Cuda Main: cudaMemcpy failed with %s\n", cudaGetErrorString(err));
cudaFree(numErr_d);
return err;
}
err = cudaFree(numErr_d);
if (err != cudaSuccess) {
printf("Cuda Main: cudaFree failed with %s\n", cudaGetErrorString(err));
return err;
}
if (numErr_h > 0) {
return cudaErrorUnknown;
}
return cudaSuccess;
}
// Clean up state and exit. If status is SUCCESS, regression success is printed
// to stdout. This will happen if the glut timer is triggered. If status is
// anything else, the regression failure message is printed.
void cleanup(int status) {
GLenum glErr = GL_NO_ERROR;
cudaError cudaErr = cudaSuccess;
int exitStatus = status;
// Clean up GL
if (*tex) {
GL_SAFE_CALL_NO_CLEANUP(glDeleteTextures(2, tex), glErr);
}
// Print test status and exit
if (glErr != GL_NO_ERROR || cudaErr != cudaSuccess) exitStatus = FAILURE;
printStatus(exitStatus);
cleanExit = 1;
graphics_close_window();
if (exitStatus == FAILURE) exit(EXIT_FAILURE);
if (exitStatus == WAIVED) exit(EXIT_WAIVED);
exit(0);
}
void exitHandler(void) {
if (!cleanExit) {
printf("&&&& EGLSync_CUDAEvent_Interop unexpected failure \n");
printStatus(FAILURE);
}
}
// Print test success or fail for regression testing
void printStatus(int status) {
switch (status) {
case SUCCESS:
printf("&&&& EGLSync_CUDAEvent_Interop PASSED\n");
break;
case WAIVED:
printf("&&&& EGLSync_CUDAEvent_Interop WAIVED\n");
break;
default:
printf("&&&& EGLSync_CUDAEvent_Interop FAILED\n");
break;
}
fflush(stdout);
}

View File

@@ -0,0 +1,442 @@
################################################################################
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
################################################################################
#
# Makefile project only supported on Mac OS X and Linux Platforms)
#
################################################################################
# Location of the CUDA Toolkit
CUDA_PATH ?= /usr/local/cuda
##############################
# start deprecated interface #
##############################
ifeq ($(x86_64),1)
$(info WARNING - x86_64 variable has been deprecated)
$(info WARNING - please use TARGET_ARCH=x86_64 instead)
TARGET_ARCH ?= x86_64
endif
ifeq ($(ARMv7),1)
$(info WARNING - ARMv7 variable has been deprecated)
$(info WARNING - please use TARGET_ARCH=armv7l instead)
TARGET_ARCH ?= armv7l
endif
ifeq ($(aarch64),1)
$(info WARNING - aarch64 variable has been deprecated)
$(info WARNING - please use TARGET_ARCH=aarch64 instead)
TARGET_ARCH ?= aarch64
endif
ifeq ($(ppc64le),1)
$(info WARNING - ppc64le variable has been deprecated)
$(info WARNING - please use TARGET_ARCH=ppc64le instead)
TARGET_ARCH ?= ppc64le
endif
ifneq ($(GCC),)
$(info WARNING - GCC variable has been deprecated)
$(info WARNING - please use HOST_COMPILER=$(GCC) instead)
HOST_COMPILER ?= $(GCC)
endif
ifneq ($(abi),)
$(error ERROR - abi variable has been removed)
endif
############################
# end deprecated interface #
############################
# architecture
HOST_ARCH := $(shell uname -m)
TARGET_ARCH ?= $(HOST_ARCH)
ifneq (,$(filter $(TARGET_ARCH),x86_64 aarch64 sbsa ppc64le armv7l))
ifneq ($(TARGET_ARCH),$(HOST_ARCH))
ifneq (,$(filter $(TARGET_ARCH),x86_64 aarch64 sbsa ppc64le))
TARGET_SIZE := 64
else ifneq (,$(filter $(TARGET_ARCH),armv7l))
TARGET_SIZE := 32
endif
else
TARGET_SIZE := $(shell getconf LONG_BIT)
endif
else
$(error ERROR - unsupported value $(TARGET_ARCH) for TARGET_ARCH!)
endif
# sbsa and aarch64 systems look similar. Need to differentiate them at host level for now.
ifeq ($(HOST_ARCH),aarch64)
ifeq ($(CUDA_PATH)/targets/sbsa-linux,$(shell ls -1d $(CUDA_PATH)/targets/sbsa-linux 2>/dev/null))
HOST_ARCH := sbsa
TARGET_ARCH := sbsa
endif
endif
ifneq ($(TARGET_ARCH),$(HOST_ARCH))
ifeq (,$(filter $(HOST_ARCH)-$(TARGET_ARCH),aarch64-armv7l x86_64-armv7l x86_64-aarch64 x86_64-sbsa x86_64-ppc64le))
$(error ERROR - cross compiling from $(HOST_ARCH) to $(TARGET_ARCH) is not supported!)
endif
endif
# When on native aarch64 system with userspace of 32-bit, change TARGET_ARCH to armv7l
ifeq ($(HOST_ARCH)-$(TARGET_ARCH)-$(TARGET_SIZE),aarch64-aarch64-32)
TARGET_ARCH = armv7l
endif
# operating system
HOST_OS := $(shell uname -s 2>/dev/null | tr "[:upper:]" "[:lower:]")
TARGET_OS ?= $(HOST_OS)
ifeq (,$(filter $(TARGET_OS),linux darwin qnx android))
$(error ERROR - unsupported value $(TARGET_OS) for TARGET_OS!)
endif
# host compiler
ifeq ($(TARGET_OS),darwin)
ifeq ($(shell expr `xcodebuild -version | grep -i xcode | awk '{print $$2}' | cut -d'.' -f1` \>= 5),1)
HOST_COMPILER ?= clang++
endif
else ifneq ($(TARGET_ARCH),$(HOST_ARCH))
ifeq ($(HOST_ARCH)-$(TARGET_ARCH),x86_64-armv7l)
ifeq ($(TARGET_OS),linux)
HOST_COMPILER ?= arm-linux-gnueabihf-g++
else ifeq ($(TARGET_OS),qnx)
ifeq ($(QNX_HOST),)
$(error ERROR - QNX_HOST must be passed to the QNX host toolchain)
endif
ifeq ($(QNX_TARGET),)
$(error ERROR - QNX_TARGET must be passed to the QNX target toolchain)
endif
export QNX_HOST
export QNX_TARGET
HOST_COMPILER ?= $(QNX_HOST)/usr/bin/arm-unknown-nto-qnx6.6.0eabi-g++
else ifeq ($(TARGET_OS),android)
HOST_COMPILER ?= arm-linux-androideabi-g++
endif
else ifeq ($(TARGET_ARCH),aarch64)
ifeq ($(TARGET_OS), linux)
HOST_COMPILER ?= aarch64-linux-gnu-g++
else ifeq ($(TARGET_OS),qnx)
ifeq ($(QNX_HOST),)
$(error ERROR - QNX_HOST must be passed to the QNX host toolchain)
endif
ifeq ($(QNX_TARGET),)
$(error ERROR - QNX_TARGET must be passed to the QNX target toolchain)
endif
export QNX_HOST
export QNX_TARGET
HOST_COMPILER ?= $(QNX_HOST)/usr/bin/q++
else ifeq ($(TARGET_OS), android)
HOST_COMPILER ?= aarch64-linux-android-clang++
endif
else ifeq ($(TARGET_ARCH),sbsa)
HOST_COMPILER ?= aarch64-linux-gnu-g++
else ifeq ($(TARGET_ARCH),ppc64le)
HOST_COMPILER ?= powerpc64le-linux-gnu-g++
endif
endif
HOST_COMPILER ?= g++
NVCC := $(CUDA_PATH)/bin/nvcc -ccbin $(HOST_COMPILER)
# internal flags
NVCCFLAGS := -m${TARGET_SIZE}
CCFLAGS :=
LDFLAGS :=
# build flags
ifeq ($(TARGET_OS),darwin)
LDFLAGS += -rpath $(CUDA_PATH)/lib
CCFLAGS += -arch $(HOST_ARCH)
else ifeq ($(HOST_ARCH)-$(TARGET_ARCH)-$(TARGET_OS),x86_64-armv7l-linux)
LDFLAGS += --dynamic-linker=/lib/ld-linux-armhf.so.3
CCFLAGS += -mfloat-abi=hard
else ifeq ($(TARGET_OS),android)
LDFLAGS += -pie
CCFLAGS += -fpie -fpic -fexceptions
endif
ifneq ($(TARGET_ARCH),$(HOST_ARCH))
ifeq ($(TARGET_ARCH)-$(TARGET_OS),armv7l-linux)
ifneq ($(TARGET_FS),)
GCCVERSIONLTEQ46 := $(shell expr `$(HOST_COMPILER) -dumpversion` \<= 4.6)
ifeq ($(GCCVERSIONLTEQ46),1)
CCFLAGS += --sysroot=$(TARGET_FS)
endif
LDFLAGS += --sysroot=$(TARGET_FS)
LDFLAGS += -rpath-link=$(TARGET_FS)/lib
LDFLAGS += -rpath-link=$(TARGET_FS)/usr/lib
LDFLAGS += -rpath-link=$(TARGET_FS)/usr/lib/arm-linux-gnueabihf
endif
endif
ifeq ($(TARGET_ARCH)-$(TARGET_OS),aarch64-linux)
ifneq ($(TARGET_FS),)
GCCVERSIONLTEQ46 := $(shell expr `$(HOST_COMPILER) -dumpversion` \<= 4.6)
ifeq ($(GCCVERSIONLTEQ46),1)
CCFLAGS += --sysroot=$(TARGET_FS)
endif
LDFLAGS += --sysroot=$(TARGET_FS)
LDFLAGS += -rpath-link=$(TARGET_FS)/lib -L$(TARGET_FS)/lib
LDFLAGS += -rpath-link=$(TARGET_FS)/lib/aarch64-linux-gnu -L$(TARGET_FS)/lib/aarch64-linux-gnu
LDFLAGS += -rpath-link=$(TARGET_FS)/usr/lib -L$(TARGET_FS)/usr/lib
LDFLAGS += -rpath-link=$(TARGET_FS)/usr/lib/aarch64-linux-gnu -L$(TARGET_FS)/usr/lib/aarch64-linux-gnu
LDFLAGS += --unresolved-symbols=ignore-in-shared-libs
CCFLAGS += -isystem=$(TARGET_FS)/usr/include -I$(TARGET_FS)/usr/include -I$(TARGET_FS)/usr/include/libdrm
CCFLAGS += -isystem=$(TARGET_FS)/usr/include/aarch64-linux-gnu -I$(TARGET_FS)/usr/include/aarch64-linux-gnu
endif
endif
ifeq ($(TARGET_ARCH)-$(TARGET_OS),aarch64-qnx)
NVCCFLAGS += -D_QNX_SOURCE
NVCCFLAGS += --qpp-config 8.3.0,gcc_ntoaarch64le
CCFLAGS += -DWIN_INTERFACE_CUSTOM -I/usr/include/aarch64-qnx-gnu
LDFLAGS += -lsocket
LDFLAGS += -L/usr/lib/aarch64-qnx-gnu
CCFLAGS += "-Wl\,-rpath-link\,/usr/lib/aarch64-qnx-gnu"
ifdef TARGET_OVERRIDE
LDFLAGS += -lslog2
endif
ifneq ($(TARGET_FS),)
LDFLAGS += -L$(TARGET_FS)/usr/lib
CCFLAGS += "-Wl\,-rpath-link\,$(TARGET_FS)/usr/lib"
LDFLAGS += -L$(TARGET_FS)/usr/libnvidia
CCFLAGS += "-Wl\,-rpath-link\,$(TARGET_FS)/usr/libnvidia"
CCFLAGS += -I$(TARGET_FS)/../include
endif
endif
endif
ifdef TARGET_OVERRIDE # cuda toolkit targets override
NVCCFLAGS += -target-dir $(TARGET_OVERRIDE)
endif
# Install directory of different arch
CUDA_INSTALL_TARGET_DIR :=
ifeq ($(TARGET_ARCH)-$(TARGET_OS),armv7l-linux)
CUDA_INSTALL_TARGET_DIR = targets/armv7-linux-gnueabihf/
else ifeq ($(TARGET_ARCH)-$(TARGET_OS),aarch64-linux)
CUDA_INSTALL_TARGET_DIR = targets/aarch64-linux/
else ifeq ($(TARGET_ARCH)-$(TARGET_OS),sbsa-linux)
CUDA_INSTALL_TARGET_DIR = targets/sbsa-linux/
else ifeq ($(TARGET_ARCH)-$(TARGET_OS),armv7l-android)
CUDA_INSTALL_TARGET_DIR = targets/armv7-linux-androideabi/
else ifeq ($(TARGET_ARCH)-$(TARGET_OS),aarch64-android)
CUDA_INSTALL_TARGET_DIR = targets/aarch64-linux-androideabi/
else ifeq ($(TARGET_ARCH)-$(TARGET_OS),armv7l-qnx)
CUDA_INSTALL_TARGET_DIR = targets/ARMv7-linux-QNX/
else ifeq ($(TARGET_ARCH)-$(TARGET_OS),aarch64-qnx)
CUDA_INSTALL_TARGET_DIR = targets/aarch64-qnx/
else ifeq ($(TARGET_ARCH),ppc64le)
CUDA_INSTALL_TARGET_DIR = targets/ppc64le-linux/
endif
# Debug build flags
ifeq ($(dbg),1)
NVCCFLAGS += -g -G
BUILD_TYPE := debug
else
BUILD_TYPE := release
endif
ALL_CCFLAGS :=
ALL_CCFLAGS += $(NVCCFLAGS)
ALL_CCFLAGS += $(EXTRA_NVCCFLAGS)
ALL_CCFLAGS += $(addprefix -Xcompiler ,$(CCFLAGS))
ALL_CCFLAGS += $(addprefix -Xcompiler ,$(EXTRA_CCFLAGS))
UBUNTU = $(shell lsb_release -i -s 2>/dev/null | grep -i ubuntu)
SAMPLE_ENABLED := 1
# This sample is not supported on Linux x86_64
ifeq ($(TARGET_OS),linux)
ifeq ($(TARGET_ARCH),x86_64)
$(info >>> WARNING - EGLSync_CUDAEvent_Interop is not supported on Linux x86_64 - waiving sample <<<)
SAMPLE_ENABLED := 0
endif
endif
# This sample is not supported on Mac OSX
ifeq ($(TARGET_OS),darwin)
$(info >>> WARNING - EGLSync_CUDAEvent_Interop is not supported on Mac OSX - waiving sample <<<)
SAMPLE_ENABLED := 0
endif
# This sample is not supported on sbsa
ifeq ($(TARGET_ARCH),sbsa)
$(info >>> WARNING - EGLSync_CUDAEvent_Interop is not supported on sbsa - waiving sample <<<)
SAMPLE_ENABLED := 0
endif
# This sample is not supported on android
ifeq ($(TARGET_OS),android)
$(info >>> WARNING - EGLSync_CUDAEvent_Interop is not supported on android - waiving sample <<<)
SAMPLE_ENABLED := 0
endif
# This sample is not supported on QNX
ifeq ($(TARGET_OS),qnx)
$(info >>> WARNING - EGLSync_CUDAEvent_Interop is not supported on QNX - waiving sample <<<)
SAMPLE_ENABLED := 0
endif
ALL_LDFLAGS :=
ALL_LDFLAGS += $(ALL_CCFLAGS)
ALL_LDFLAGS += $(addprefix -Xlinker ,$(LDFLAGS))
ALL_LDFLAGS += $(addprefix -Xlinker ,$(EXTRA_LDFLAGS))
# Common includes and paths for CUDA
INCLUDES := -I../../../Common
LIBRARIES :=
################################################################################
# Makefile include to help find EGL Libraries
include ./findegl.mk
# EGL specific libraries
ifneq ($(TARGET_OS),darwin)
LIBRARIES += -lEGL
endif
# Gencode arguments
ifeq ($(TARGET_ARCH),$(filter $(TARGET_ARCH),armv7l aarch64 sbsa))
SMS ?= 53 61 70 72 75 80 86 87
else
SMS ?= 35 37 50 52 60 61 70 75 80 86
endif
ifeq ($(SMS),)
$(info >>> WARNING - no SM architectures have been specified - waiving sample <<<)
SAMPLE_ENABLED := 0
endif
ifeq ($(GENCODE_FLAGS),)
# Generate SASS code for each SM architecture listed in $(SMS)
$(foreach sm,$(SMS),$(eval GENCODE_FLAGS += -gencode arch=compute_$(sm),code=sm_$(sm)))
# Generate PTX code from the highest SM architecture in $(SMS) to guarantee forward-compatibility
HIGHEST_SM := $(lastword $(sort $(SMS)))
ifneq ($(HIGHEST_SM),)
GENCODE_FLAGS += -gencode arch=compute_$(HIGHEST_SM),code=compute_$(HIGHEST_SM)
endif
endif
ifeq ($(TARGET_OS),darwin)
ALL_LDFLAGS += -Xcompiler -F/Library/Frameworks -Xlinker -framework -Xlinker CUDA
else
ifeq ($(TARGET_ARCH),x86_64)
CUDA_SEARCH_PATH ?= $(CUDA_PATH)/lib64/stubs
CUDA_SEARCH_PATH += $(CUDA_PATH)/lib/stubs
CUDA_SEARCH_PATH += $(CUDA_PATH)/targets/x86_64-linux/lib/stubs
endif
ifeq ($(TARGET_ARCH)-$(TARGET_OS),armv7l-linux)
CUDA_SEARCH_PATH ?= $(CUDA_PATH)/targets/armv7-linux-gnueabihf/lib/stubs
endif
ifeq ($(TARGET_ARCH)-$(TARGET_OS),aarch64-linux)
CUDA_SEARCH_PATH ?= $(CUDA_PATH)/targets/aarch64-linux/lib/stubs
endif
ifeq ($(TARGET_ARCH)-$(TARGET_OS),sbsa-linux)
CUDA_SEARCH_PATH ?= $(CUDA_PATH)/targets/sbsa-linux/lib/stubs
endif
ifeq ($(TARGET_ARCH)-$(TARGET_OS),armv7l-android)
CUDA_SEARCH_PATH ?= $(CUDA_PATH)/targets/armv7-linux-androideabi/lib/stubs
endif
ifeq ($(TARGET_ARCH)-$(TARGET_OS),aarch64-android)
CUDA_SEARCH_PATH ?= $(CUDA_PATH)/targets/aarch64-linux-androideabi/lib/stubs
endif
ifeq ($(TARGET_ARCH)-$(TARGET_OS),armv7l-qnx)
CUDA_SEARCH_PATH ?= $(CUDA_PATH)/targets/ARMv7-linux-QNX/lib/stubs
endif
ifeq ($(TARGET_ARCH)-$(TARGET_OS),aarch64-qnx)
CUDA_SEARCH_PATH ?= $(CUDA_PATH)/targets/aarch64-qnx/lib/stubs
ifdef TARGET_OVERRIDE
CUDA_SEARCH_PATH := $(CUDA_PATH)/targets/$(TARGET_OVERRIDE)/lib/stubs
endif
endif
ifeq ($(TARGET_ARCH),ppc64le)
CUDA_SEARCH_PATH ?= $(CUDA_PATH)/targets/ppc64le-linux/lib/stubs
endif
ifeq ($(HOST_ARCH),ppc64le)
CUDA_SEARCH_PATH += $(CUDA_PATH)/lib64/stubs
endif
CUDALIB ?= $(shell find -L $(CUDA_SEARCH_PATH) -maxdepth 1 -name libcuda.so 2> /dev/null)
ifeq ("$(CUDALIB)","")
$(info >>> WARNING - libcuda.so not found, CUDA Driver is not installed. Please re-install the driver. <<<)
SAMPLE_ENABLED := 0
else
CUDALIB := $(shell echo $(CUDALIB) | sed "s/ .*//" | sed "s/\/libcuda.so//" )
LIBRARIES += -L$(CUDALIB) -lcuda
endif
endif
ALL_CCFLAGS += --threads 0 --std=c++11
LIBRARIES += -lX11 -lGLESv2
ifeq ($(SAMPLE_ENABLED),0)
EXEC ?= @echo "[@]"
endif
################################################################################
# Target rules
all: build
build: EGLSync_CUDAEvent_Interop
check.deps:
ifeq ($(SAMPLE_ENABLED),0)
@echo "Sample will be waived due to the above missing dependencies"
else
@echo "Sample is ready - all dependencies have been met"
endif
EGLSync_CUDAEvent_Interop.o:EGLSync_CUDAEvent_Interop.cu
$(EXEC) $(NVCC) $(INCLUDES) $(ALL_CCFLAGS) $(GENCODE_FLAGS) -o $@ -c $<
EGLSync_CUDAEvent_Interop: EGLSync_CUDAEvent_Interop.o
$(EXEC) $(NVCC) $(ALL_LDFLAGS) $(GENCODE_FLAGS) -o $@ $+ $(LIBRARIES)
$(EXEC) mkdir -p ../../../bin/$(TARGET_ARCH)/$(TARGET_OS)/$(BUILD_TYPE)
$(EXEC) cp $@ ../../../bin/$(TARGET_ARCH)/$(TARGET_OS)/$(BUILD_TYPE)
run: build
$(EXEC) ./EGLSync_CUDAEvent_Interop
testrun: build
clean:
rm -f EGLSync_CUDAEvent_Interop EGLSync_CUDAEvent_Interop.o
rm -rf ../../../bin/$(TARGET_ARCH)/$(TARGET_OS)/$(BUILD_TYPE)/EGLSync_CUDAEvent_Interop
clobber: clean

View File

@@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE entry SYSTEM "SamplesInfo.dtd">
<entry>
<name>EGLSync_CUDAEvent_Interop</name>
<cuda_api_list>
<driver>cuGraphicsEGLRegisterImage</driver>
<driver>cuStreamCreate</driver>
<driver>cuEventCreate</driver>
<driver>cuCtxCreate</driver>
<driver>cuGraphicsSubResourceGetMappedArray</driver>
<driver>cuGraphicsUnregisterResource</driver>
<driver>cuCtxSynchronize</driver>
<driver>cuEventCreateFromEGLSync</driver>
<driver>cuEventDestroy</driver>
<driver>cuStreamWaitEvent</driver>
<driver>cuCtxPushCurrent</driver>
<driver>cuSurfObjectCreate</driver>
<driver>cuInit</driver>
<driver>cuEventRecord</driver>
<driver>cuDeviceGetAttribute</driver>
<toolkit>cudaFree</toolkit>
<toolkit>cudaDeviceSynchronize</toolkit>
<toolkit>cudaGetValueMismatch</toolkit>
<toolkit>cudaMalloc</toolkit>
<toolkit>cudaMemcpy</toolkit>
<toolkit>cudaGetErrorString</toolkit>
</cuda_api_list>
<description><![CDATA[Demonstrates interoperability between CUDA Event and EGL Sync/EGL Image using which one can achieve synchronization on GPU itself for GL-EGL-CUDA operations instead of blocking CPU for synchronization.]]></description>
<devicecompilation>whole</devicecompilation>
<includepaths>
<path>./</path>
<path>../</path>
<path>../../../Common</path>
</includepaths>
<keyconcepts>
<concept level="basic">EGLSync-CUDAEvent Interop</concept>
<concept level="basic">EGLImage-CUDA Interop</concept>
</keyconcepts>
<keywords>
<keyword>EGL Sync</keyword>
</keywords>
<libraries>
<library os="linux">cuda</library>
<library framework="true" os="macosx">CUDA</library>
<library>X11</library>
<library>GLESv2</library>
</libraries>
<librarypaths>
</librarypaths>
<nsight_eclipse>true</nsight_eclipse>
<primary_file>EGLSync_CUDAEvent_Interop.cu</primary_file>
<required_dependencies>
<dependency>EGL</dependency>
<dependency>EGLSync</dependency>
<dependency>X11</dependency>
<dependency>GLES</dependency>
</required_dependencies>
<scopes>
<scope>1:CUDA Basic Topics</scope>
<scope>2:Graphics Interop</scope>
</scopes>
<sm-arch>sm35</sm-arch>
<sm-arch>sm37</sm-arch>
<sm-arch>sm50</sm-arch>
<sm-arch>sm52</sm-arch>
<sm-arch>sm53</sm-arch>
<sm-arch>sm60</sm-arch>
<sm-arch>sm61</sm-arch>
<sm-arch>sm70</sm-arch>
<sm-arch>sm72</sm-arch>
<sm-arch>sm75</sm-arch>
<sm-arch>sm80</sm-arch>
<sm-arch>sm86</sm-arch>
<sm-arch>sm87</sm-arch>
<supported_envs>
<env>
<arch>arm</arch>
</env>
</supported_envs>
<supported_sm_architectures>
<include>all</include>
</supported_sm_architectures>
<title>EGLSync CUDA Event Interop</title>
<type>exe</type>
</entry>

View File

@@ -0,0 +1,67 @@
# EGLSync_CUDAEvent_Interop - EGLSync CUDA Event Interop
## Description
Demonstrates interoperability between CUDA Event and EGL Sync/EGL Image using which one can achieve synchronization on GPU itself for GL-EGL-CUDA operations instead of blocking CPU for synchronization.
## Key Concepts
EGLSync-CUDAEvent Interop, EGLImage-CUDA Interop
## Supported SM Architectures
[SM 3.5 ](https://developer.nvidia.com/cuda-gpus) [SM 3.7 ](https://developer.nvidia.com/cuda-gpus) [SM 5.0 ](https://developer.nvidia.com/cuda-gpus) [SM 5.2 ](https://developer.nvidia.com/cuda-gpus) [SM 5.3 ](https://developer.nvidia.com/cuda-gpus) [SM 6.0 ](https://developer.nvidia.com/cuda-gpus) [SM 6.1 ](https://developer.nvidia.com/cuda-gpus) [SM 7.0 ](https://developer.nvidia.com/cuda-gpus) [SM 7.2 ](https://developer.nvidia.com/cuda-gpus) [SM 7.5 ](https://developer.nvidia.com/cuda-gpus) [SM 8.0 ](https://developer.nvidia.com/cuda-gpus) [SM 8.6 ](https://developer.nvidia.com/cuda-gpus) [SM 8.7 ](https://developer.nvidia.com/cuda-gpus)
## Supported OSes
Linux
## Supported CPU Architecture
armv7l
## CUDA APIs involved
### [CUDA Driver API](http://docs.nvidia.com/cuda/cuda-driver-api/index.html)
cuGraphicsEGLRegisterImage, cuStreamCreate, cuEventCreate, cuCtxCreate, cuGraphicsSubResourceGetMappedArray, cuGraphicsUnregisterResource, cuCtxSynchronize, cuEventCreateFromEGLSync, cuEventDestroy, cuStreamWaitEvent, cuCtxPushCurrent, cuSurfObjectCreate, cuInit, cuEventRecord, cuDeviceGetAttribute
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
cudaFree, cudaDeviceSynchronize, cudaGetValueMismatch, cudaMalloc, cudaMemcpy, cudaGetErrorString
## Dependencies needed to build/run
[EGL](../../README.md#egl), [EGLSync](../../README.md#eglsync), [X11](../../README.md#x11), [GLES](../../README.md#gles)
## Prerequisites
Download and install the [CUDA Toolkit 11.6](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
Make sure the dependencies mentioned in [Dependencies]() section above are installed.
## Build and Run
### Linux
The Linux samples are built using makefiles. To use the makefiles, change the current directory to the sample directory you wish to build, and run make:
```
$ cd <sample_dir>
$ make
```
The samples makefiles can take advantage of certain options:
* **TARGET_ARCH=<arch>** - cross-compile targeting a specific architecture. Allowed architectures are armv7l.
By default, TARGET_ARCH is set to HOST_ARCH. On a x86_64 machine, not setting TARGET_ARCH is the equivalent of setting TARGET_ARCH=x86_64.<br/>
`$ make TARGET_ARCH=armv7l` <br/>
See [here](http://docs.nvidia.com/cuda/cuda-samples/index.html#cross-samples) for more details.
* **dbg=1** - build with debug symbols
```
$ make dbg=1
```
* **SMS="A B ..."** - override the SM architectures for which the sample will be built, where `"A B ..."` is a space-delimited list of SM architectures. For example, to generate SASS for SM 50 and SM 60, use `SMS="50 60"`.
```
$ make SMS="50 60"
```
* **HOST_COMPILER=<host_compiler>** - override the default g++ host compiler. See the [Linux Installation Guide](http://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html#system-requirements) for a list of supported host compilers.
```
$ make HOST_COMPILER=g++
```
## References (for more details)

View File

@@ -0,0 +1,71 @@
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//
// DESCRIPTION: Common EGL functions header file
//
#ifndef _EGL_COMMON_H_
#define _EGL_COMMON_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <signal.h>
#include "cuda.h"
#include "cudaEGL.h"
EGLImageKHR eglImage;
#define EXTENSION_LIST(T) \
T(PFNEGLCREATEIMAGEKHRPROC, eglCreateImageKHR) \
T(PFNEGLDESTROYIMAGEKHRPROC, eglDestroyImageKHR) \
T(PFNEGLCREATESYNCKHRPROC, eglCreateSyncKHR) \
T(PFNEGLDESTROYSYNCKHRPROC, eglDestroySyncKHR) \
T(PFNEGLCLIENTWAITSYNCKHRPROC, eglClientWaitSyncKHR) \
T(PFNEGLGETSYNCATTRIBKHRPROC, eglGetSyncAttribKHR) \
T(PFNEGLCREATESYNC64KHRPROC, eglCreateSync64KHR) \
T(PFNEGLWAITSYNCKHRPROC, eglWaitSyncKHR)
#define eglCreateImageKHR my_eglCreateImageKHR
#define eglDestroyImageKHR my_eglDestroyImageKHR
#define eglCreateSyncKHR my_eglCreateSyncKHR
#define eglDestroySyncKHR my_eglDestroySyncKHR
#define eglClientWaitSyncKHR my_eglClientWaitSyncKHR
#define eglGetSyncAttribKHR my_eglGetSyncAttribKHR
#define eglCreateSync64KHR my_eglCreateSync64KHR
#define eglWaitSyncKHR my_eglWaitSyncKHR
#define EXTLST_DECL(tx, x) tx my_##x = NULL;
#define EXTLST_EXTERN(tx, x) extern tx my_##x;
#define EXTLST_ENTRY(tx, x) {(extlst_fnptr_t *)&my_##x, #x},
int eglSetupExtensions(void);
#endif

View File

@@ -0,0 +1,160 @@
################################################################################
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
################################################################################
#
# findegl.mk is used to find the necessary EGL Libraries for specific distributions
# this is supported on Linux
#
################################################################################
# Determine OS platform and unix distribution
ifeq ("$(TARGET_OS)","linux")
# first search lsb_release
DISTRO = $(shell lsb_release -i -s 2>/dev/null | tr "[:upper:]" "[:lower:]")
ifeq ("$(DISTRO)","")
# second search and parse /etc/issue
DISTRO = $(shell more /etc/issue | awk '{print $$1}' | sed '1!d' | sed -e "/^$$/d" 2>/dev/null | tr "[:upper:]" "[:lower:]")
# ensure data from /etc/issue is valid
ifeq (,$(filter $(DISTRO),ubuntu fedora red rhel centos suse))
DISTRO =
endif
ifeq ("$(DISTRO)","")
# third, we can search in /etc/os-release or /etc/{distro}-release
DISTRO = $(shell awk '/ID/' /etc/*-release | sed 's/ID=//' | grep -v "VERSION" | grep -v "ID" | grep -v "DISTRIB")
endif
endif
endif
ifeq ("$(TARGET_OS)","linux")
# $(info) >> findegl.mk -> LINUX path <<<)
# Each set of Linux Distros have different paths for where to find their OpenGL libraries reside
UBUNTU = $(shell echo $(DISTRO) | grep -i ubuntu >/dev/null 2>&1; echo $$?)
FEDORA = $(shell echo $(DISTRO) | grep -i fedora >/dev/null 2>&1; echo $$?)
RHEL = $(shell echo $(DISTRO) | grep -i 'red\|rhel' >/dev/null 2>&1; echo $$?)
CENTOS = $(shell echo $(DISTRO) | grep -i centos >/dev/null 2>&1; echo $$?)
SUSE = $(shell echo $(DISTRO) | grep -i 'suse\|sles' >/dev/null 2>&1; echo $$?)
ifeq ("$(UBUNTU)","0")
ifeq ($(HOST_ARCH)-$(TARGET_ARCH),x86_64-armv7l)
GLPATH := /usr/arm-linux-gnueabihf/lib
GLLINK := -L/usr/arm-linux-gnueabihf/lib
ifneq ($(TARGET_FS),)
GLPATH += $(TARGET_FS)/usr/lib/arm-linux-gnueabihf
GLLINK += -L$(TARGET_FS)/usr/lib/arm-linux-gnueabihf
endif
else ifeq ($(HOST_ARCH)-$(TARGET_ARCH),x86_64-aarch64)
GLPATH := /usr/aarch64-linux-gnu/lib
GLLINK := -L/usr/aarch64-linux-gnu/lib
ifneq ($(TARGET_FS),)
GLPATH += $(TARGET_FS)/usr/lib
GLPATH += $(TARGET_FS)/usr/lib/aarch64-linux-gnu
GLLINK += -L$(TARGET_FS)/usr/lib/aarch64-linux-gnu
endif
else
UBUNTU_PKG_NAME = $(shell which dpkg >/dev/null 2>&1 && dpkg -l 'nvidia-*' | grep '^ii' | awk '{print $$2}' | head -1)
ifneq ("$(UBUNTU_PKG_NAME)","")
GLPATH ?= /usr/lib/$(UBUNTU_PKG_NAME)
GLLINK ?= -L/usr/lib/$(UBUNTU_PKG_NAME)
endif
DFLT_PATH ?= /usr/lib
endif
endif
ifeq ("$(SUSE)","0")
GLPATH ?= /usr/X11R6/lib64
GLLINK ?= -L/usr/X11R6/lib64
DFLT_PATH ?= /usr/lib64
endif
ifeq ("$(FEDORA)","0")
GLPATH ?= /usr/lib64/nvidia
GLLINK ?= -L/usr/lib64/nvidia
DFLT_PATH ?= /usr/lib64
endif
ifeq ("$(RHEL)","0")
GLPATH ?= /usr/lib64/nvidia
GLLINK ?= -L/usr/lib64/nvidia
DFLT_PATH ?= /usr/lib64
endif
ifeq ("$(CENTOS)","0")
GLPATH ?= /usr/lib64/nvidia
GLLINK ?= -L/usr/lib64/nvidia
DFLT_PATH ?= /usr/lib64
endif
EGLLIB := $(shell find -L $(GLPATH) $(DFLT_PATH) -name libEGL.so -print 2>/dev/null)
ifeq ("$(EGLLIB)","")
$(info >>> WARNING - libEGL.so not found, please install libEGL.so <<<)
SAMPLE_ENABLED := 0
endif
HEADER_SEARCH_PATH ?= $(TARGET_FS)/usr/include
ifeq ($(HOST_ARCH)-$(TARGET_ARCH)-$(TARGET_OS),x86_64-armv7l-linux)
HEADER_SEARCH_PATH += /usr/arm-linux-gnueabihf/include
else ifeq ($(HOST_ARCH)-$(TARGET_ARCH)-$(TARGET_OS),x86_64-aarch64-linux)
HEADER_SEARCH_PATH += /usr/aarch64-linux-gnu/include
endif
EGLHEADER := $(shell find -L $(HEADER_SEARCH_PATH) -name egl.h -print 2>/dev/null)
EGLEXTHEADER := $(shell find -L $(HEADER_SEARCH_PATH) -name eglext.h -print 2>/dev/null)
ifeq ("$(EGLHEADER)","")
$(info >>> WARNING - egl.h not found, please install egl.h <<<)
SAMPLE_ENABLED := 0
endif
ifeq ("$(EGLEXTHEADER)","")
$(info >>> WARNING - eglext.h not found, please install eglext.h <<<)
SAMPLE_ENABLED := 0
endif
else
endif
ifeq ("$(TARGET_OS)","qnx")
HOST_CCFLAGS := -V8.3.0,gcc_ntoaarch64le
endif
# Attempt to compile a minimal EGL application and run to check if EGL_SUPPORT_REUSE_NV is supported in the EGL headers available.
ifneq ($(SAMPLE_ENABLED), 0)
$(shell printf "#include <EGL/egl.h>\n#include <EGL/eglext.h>\nint main() {\n#ifdef EGL_SUPPORT_REUSE_NV \n #error \"Compatible EGL header found\" \n return 0;\n#endif \n return 1;\n}" > test.c; )
EGL_DEFINES := $(shell $(HOST_COMPILER) $(HOST_CCFLAGS) $(CCFLAGS) $(EXTRA_CCFLAGS) -lEGL test.c -c 2>&1 | grep -ic "Compatible EGL header found";)
SHOULD_WAIVE := 0
ifeq ($(EGL_DEFINES),0)
SHOULD_WAIVE := 1
endif
ifeq ($(SHOULD_WAIVE),1)
$(info -----------------------------------------------------------------------------------------------)
$(info WARNING - NVIDIA EGL EXTENSIONS are not available in the present EGL headers)
$(info -----------------------------------------------------------------------------------------------)
$(info This CUDA Sample cannot be built if the EGL NVIDIA EXTENSIONS like EGL_SUPPORT_REUSE_NV are not supported in EGL headers.)
$(info This will be a dry-run of the Makefile.)
$(info Please install the latest khronos EGL headers and libs to build this sample)
$(info -----------------------------------------------------------------------------------------------)
SAMPLE_ENABLED := 0
endif
$(shell rm test.o test.c 2>/dev/null)
endif

View File

@@ -0,0 +1,204 @@
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
Display *display;
int screen;
Window win = 0;
void error_exit(const char *format, ...) {
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
exit(1);
}
#include <EGL/egl.h>
#include <EGL/eglext.h>
#define GET_GLERROR(ret) \
{ \
GLenum err = glGetError(); \
if (err != GL_NO_ERROR) { \
fprintf(stderr, "[%s line %d] OpenGL Error: 0x%x\n", __FILE__, __LINE__, \
err); \
fflush(stderr); \
\
switch (err) { \
case GL_INVALID_ENUM: \
printf("GL_INVALID_ENUM\n"); \
break; \
case GL_INVALID_VALUE: \
printf("GL_INVALID_VALUE\n"); \
break; \
case GL_INVALID_OPERATION: \
printf("GL_INVALID_OPERATION\n"); \
break; \
case GL_OUT_OF_MEMORY: \
printf("GL_OUT_OF_MEMORY\n"); \
break; \
case GL_INVALID_FRAMEBUFFER_OPERATION: \
printf("GL_INVALID_FRAMEBUFFER_OPERATION\n"); \
break; \
default: \
printf("UKNOWN OPENGL ERROR CODE 0x%x\n", err); \
}; \
} \
}
EGLDisplay eglDisplay = EGL_NO_DISPLAY;
EGLSurface eglSurface = EGL_NO_SURFACE;
EGLContext eglContext = EGL_NO_CONTEXT;
int graphics_setup_window(int xpos, int ypos, int width, int height,
const char *windowname) {
EGLint configAttrs[] = {
EGL_RED_SIZE, 1, EGL_GREEN_SIZE, 1, EGL_BLUE_SIZE, 1, EGL_DEPTH_SIZE, 16,
EGL_SAMPLE_BUFFERS, 0, EGL_SAMPLES, 0,
// EGL_CONFORMANT, EGL_OPENGL_BIT,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, // 3_BIT_KHR,
EGL_NONE};
EGLint contextAttrs[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE};
EGLConfig *configList = NULL;
EGLint configCount;
display = XOpenDisplay(NULL);
if (!display) error_exit("Error opening X display.\n");
screen = DefaultScreen(display);
eglDisplay = eglGetDisplay(0);
if (eglDisplay == EGL_NO_DISPLAY)
error_exit("EGL failed to obtain display\n");
if (!eglInitialize(eglDisplay, 0, 0))
error_exit("EGL failed to initialize\n");
if (!eglChooseConfig(eglDisplay, configAttrs, NULL, 0, &configCount) ||
!configCount)
error_exit("EGL failed to return any matching configurations\n");
configList = (EGLConfig *)malloc(configCount * sizeof(EGLConfig));
if (!eglChooseConfig(eglDisplay, configAttrs, configList, configCount,
&configCount) ||
!configCount)
error_exit("EGL failed to populate configuration list\n");
Window xRootWindow = DefaultRootWindow(display);
XSetWindowAttributes xCreateWindowAttributes;
xCreateWindowAttributes.event_mask = ExposureMask;
win = XCreateWindow(display, xRootWindow, 0, 0, width, height, 0,
CopyFromParent, InputOutput, CopyFromParent, CWEventMask,
&xCreateWindowAttributes);
XMapWindow(display, win);
Atom netWmStateAtom = XInternAtom(display, "_NET_WM_STATE", false);
XEvent xEvent;
memset(&xEvent, 0, sizeof(xEvent));
xEvent.type = ClientMessage;
xEvent.xclient.window = win;
xEvent.xclient.message_type = netWmStateAtom;
xEvent.xclient.format = 32;
xEvent.xclient.data.l[0] = 1;
xEvent.xclient.data.l[1] = false;
XSendEvent(display, xRootWindow, false, SubstructureNotifyMask, &xEvent);
XStoreName(display, win, windowname);
XSelectInput(display, win,
ExposureMask | KeyPressMask | ButtonPressMask |
ButtonReleaseMask | KeyReleaseMask | VisibilityChangeMask |
PointerMotionMask);
EGLint windowAttrs[] = {EGL_NONE};
eglSurface = eglCreateWindowSurface(eglDisplay, configList[0],
(EGLNativeWindowType)win, windowAttrs);
if (!eglSurface) error_exit("EGL couldn't create window\n");
eglBindAPI(EGL_OPENGL_ES_API);
eglContext = eglCreateContext(eglDisplay, configList[0], NULL, contextAttrs);
if (!eglContext) error_exit("EGL couldn't create context\n");
if (!eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext))
error_exit("EGL couldn't make context/surface current\n");
EGLint Context_RendererType;
eglQueryContext(eglDisplay, eglContext, EGL_CONTEXT_CLIENT_TYPE,
&Context_RendererType);
switch (Context_RendererType) {
case EGL_OPENGL_API:
printf("Using OpenGL API is not supported\n");
exit(EXIT_FAILURE);
break;
case EGL_OPENGL_ES_API:
printf("Using OpenGL ES API\n");
break;
case EGL_OPENVG_API:
error_exit("Context Query Returned OpenVG. This is Unsupported\n");
default:
error_exit("Unknown Context Type. %04X\n", Context_RendererType);
}
return 1;
}
void graphics_set_windowtitle(const char *windowname) {
XStoreName(display, win, windowname);
}
void graphics_swap_buffers() { eglSwapBuffers(eglDisplay, eglSurface); }
void graphics_close_window() {
if (eglDisplay != EGL_NO_DISPLAY) {
eglMakeCurrent(eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (eglContext != EGL_NO_CONTEXT) eglDestroyContext(eglDisplay, eglContext);
if (eglSurface != EGL_NO_SURFACE) eglDestroySurface(eglDisplay, eglSurface);
eglTerminate(eglDisplay);
}
if (display) {
if (win) XDestroyWindow(display, win);
XCloseDisplay(display);
}
}