void init_gl(void) { glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); /*glViewport(0, 0, win_x, win_y);*/ perspective = mat4f_perspective(45.0f, (float)win_x / win_y, 0.5f, 1000.0f); orthographic = mat4f_orthographic(0.0f, win_x, win_y, 0.0f, -1.0f, 1.0f); create_vertex_buffer(); init_font(); main_program = compile_shaders("main.vert", "main.frag"); text_program = compile_shaders("text.vert", "text.frag"); iqm_program = compile_shaders("iqm.vert", "iqm.frag"); glUseProgram(main_program); /*initialize main shader variables*/ //~ printf("Map vertex attribute bound to %i\n", attribute_map_position); //~ printf("Map texcoords attribute bound to %i\n", attribute_map_texcoords); //~ printf("Map lightmap coords attribute bound to %i\n", attribute_map_texcoordsLM); glLinkProgram(main_program); /*Must link program before uniforms and after attributes?*/ gWorldLocation = glGetUniformLocation(main_program, "gWorld"); glUniform1i(glGetUniformLocation(main_program, "textureSampler"), /*GLTEXTURE*/0); glUniform1i(glGetUniformLocation(main_program, "lightmapSampler"), /*GLTEXTURE*/1); /*initialize text shader variables*/ /*Not sure if needed... glUseProgram(text_program);*/ glBindAttribLocation(text_program, 0, "coord"); glBindAttribLocation(text_program, 1, "texpos"); ortho_mat = glGetUniformLocation(text_program, "proj_mat"); uniform_color = glGetUniformLocation(text_program, "color"); uniform_alpha_scale = glGetUniformLocation(text_program, "alpha_mod"); glGenBuffers(1, &text_vbo); /*initialize iqm model shader variables*/ glUseProgram(iqm_program); //glLinkProgram(iqm_program); //glUniform1i(glGetUniformLocation(iqm_program, "iqm_sampler"), 0); }
Scene_polyhedron_item::Scene_polyhedron_item(Polyhedron* const p) : Scene_item(), poly(p) { are_buffers_initialized = false; compile_shaders(); }
Scene_c3t3_item::Scene_c3t3_item() : Scene_item(NumberOfBuffers, NumberOfVaos) , d(new Scene_c3t3_item_priv()) , frame(new ManipulatedFrame()) , last_known_scene(NULL) , data_item_(NULL) , histogram_() , indices_() { positions_lines.resize(0); positions_poly.resize(0); normals.resize(0); s_vertex.resize(0); s_normals.resize(0); ws_vertex.resize(0); need_changed = false; startTimer(0); connect(frame, SIGNAL(modified()), this, SLOT(changed())); c3t3_changed(); setRenderingMode(FlatPlusEdges); compile_shaders(); spheres_are_shown = false; create_flat_and_wire_sphere(1.0f,s_vertex,s_normals, ws_vertex); }
void Viewer::init() { // Restore previous viewer state. restoreStateFromFile(); initializeOpenGLFunctions(); // Define 'Control+Q' as the new exit shortcut (default was 'Escape') setShortcut(EXIT_VIEWER, Qt::CTRL+Qt::Key_Q); // Add custom key description (see keyPressEvent). setKeyDescription(Qt::Key_W, "Toggles wire frame display"); setKeyDescription(Qt::Key_F, "Toggles flat shading display"); setKeyDescription(Qt::Key_E, "Toggles edges display"); setKeyDescription(Qt::Key_V, "Toggles vertices display"); // Light default parameters ::glLineWidth(1.4f); ::glPointSize(4.f); ::glEnable(GL_POLYGON_OFFSET_FILL); ::glPolygonOffset(1.0f,1.0f); ::glClearColor(1.0f,1.0f,1.0f,0.0f); ::glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); ::glEnable(GL_LIGHTING); ::glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE); ::glShadeModel(GL_FLAT); ::glDisable(GL_BLEND); ::glDisable(GL_LINE_SMOOTH); ::glDisable(GL_POLYGON_SMOOTH_HINT); ::glBlendFunc(GL_ONE, GL_ZERO); ::glHint(GL_LINE_SMOOTH_HINT, GL_FASTEST); compile_shaders(); }
Scene_polyhedron_item::Scene_polyhedron_item() : Scene_item(), poly(new Polyhedron) { are_buffers_initialized = false; compile_shaders(); }
void Viewer::init() { // Restore previous viewer state. restoreStateFromFile(); initializeOpenGLFunctions(); // Define 'Control+Q' as the new exit shortcut (default was 'Escape') setShortcut(CGAL::qglviewer::EXIT_VIEWER, Qt::CTRL+Qt::Key_Q); // Add custom key description (see keyPressEvent). setKeyDescription(Qt::Key_W, "Toggles wire frame display"); setKeyDescription(Qt::Key_F, "Toggles flat shading display"); setKeyDescription(Qt::Key_E, "Toggles edges display"); setKeyDescription(Qt::Key_V, "Toggles vertices display"); setKeyDescription(Qt::Key_N, "Inverse direction of normals"); setKeyDescription(Qt::Key_Plus, "Increase size of edges"); setKeyDescription(Qt::Key_Minus, "Decrease size of edges"); setKeyDescription(Qt::Key_Plus+Qt::ShiftModifier, "Increase size of vertices"); setKeyDescription(Qt::Key_Minus+Qt::ShiftModifier, "Decrease size of vertices"); setKeyDescription(Qt::Key_PageDown, "Increase light (all colors, use shift/alt/ctrl for one rgb component)"); setKeyDescription(Qt::Key_PageUp, "Decrease light (all colors, use shift/alt/ctrl for one rgb component)"); // Light default parameters glLineWidth(size_edges); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(1.0f,1.0f); glClearColor(1.0f,1.0f,1.0f,0.0f); glDisable(GL_BLEND); glDisable(GL_LINE_SMOOTH); glDisable(GL_POLYGON_SMOOTH_HINT); glBlendFunc(GL_ONE, GL_ZERO); glHint(GL_LINE_SMOOTH_HINT, GL_FASTEST); compile_shaders(); }
int main(int argc, char *argv[]) { // 初始化GLUT,可以直接从命令行传入参数如 // '-sync': 禁止X系统天然的异步特性 // '-gldebug': 自动检测GL的错误信息,并显示出来 glutInit(&argc, argv); // 配置GLUT选项 // GLUT_DOUBLE: 启动双缓冲(一个buffer用来绘制背景,另一个显示) glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); // 创建窗口 glutInitWindowSize(512, 384); glutInitWindowPosition(100, 100); glutCreateWindow(argv[0]); // GLUT的回调函数,这个函数会连续的被GLUT的内部循环调用 glutDisplayFunc(RenderSceneCB); // 加上这句之后显示了动态的效果?? glutIdleFunc(RenderSceneCB); // 颜色RGBA四个通道,取值范围0.0-1.0 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); compile_shaders(); create_vertex_buffer(); // 进入GLUT的内部循环 glutMainLoop(); return 0; }
int main(int argc, char **argv) { double time; float ratio; int width, height; GLFWwindow *window; GLuint rendering_program, vertex_array_object; glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); window = glfwCreateWindow(640, 480, "Rotating Triangle", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } // Set openGL context to the window object glfwMakeContextCurrent(window); rendering_program = compile_shaders(); glGenVertexArrays(1, &vertex_array_object); glBindVertexArray(vertex_array_object); glfwSetKeyCallback(window, key_callback); // can also be done using glfwGetFramebufferSize(window, &width, &height) glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // can additionally set glfwSetWindowCloseCallback(). // Can be manually set with glfwSetWindowShouldClose(). while(!glfwWindowShouldClose(window)) { time = glfwGetTime(); const GLfloat color[] = { 0.5f, 0.5f, 0.5f, 1.f }; glClearBufferfv(GL_COLOR, 0, color); glUseProgram(rendering_program); glDrawArrays(GL_TRIANGLES, 0, 3); glfwSwapBuffers(window); glfwPollEvents(); } glDeleteVertexArrays(1, &vertex_array_object); glDeleteProgram(rendering_program); glfwDestroyWindow(window); glfwTerminate(); return 0; }
void Shader::create(const std::string& name, Owner location){ init(); load_shaders(name,location); compile_shaders(); link_shaders(); get_attributes(); get_uniforms(); }
bool RenderChain::init(const LinkInfo &info, PixelFormat fmt) { pixel_size = fmt == RGB565 ? 2 : 4; if (!create_first_pass(info, fmt)) return false; log_info(info); if (!compile_shaders(fStock, vStock, "")) return false; return true; }
bool RenderChain::create_first_pass(const LinkInfo &info, PixelFormat fmt) { D3DXMATRIX ident; D3DXMatrixIdentity(&ident); dev->SetTransform(D3DTS_WORLD, &ident); dev->SetTransform(D3DTS_VIEW, &ident); Pass pass; pass.info = info; pass.last_width = 0; pass.last_height = 0; prev.ptr = 0; for (unsigned i = 0; i < Textures; i++) { prev.last_width[i] = 0; prev.last_height[i] = 0; if (FAILED(dev->CreateVertexBuffer( 4 * sizeof(Vertex), dev->GetSoftwareVertexProcessing() ? D3DUSAGE_SOFTWAREPROCESSING : 0, 0, D3DPOOL_DEFAULT, &prev.vertex_buf[i], NULL))) { return false; } if (FAILED(dev->CreateTexture(info.tex_w, info.tex_h, 1, 0, fmt == RGB565 ? D3DFMT_R5G6B5 : D3DFMT_X8R8G8B8, D3DPOOL_MANAGED, &prev.tex[i], NULL))) { return false; } dev->SetTexture(0, prev.tex[i]); dev->SetSamplerState(0, D3DSAMP_MINFILTER, translate_filter(info.pass->filter)); dev->SetSamplerState(0, D3DSAMP_MAGFILTER, translate_filter(info.pass->filter)); dev->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_BORDER); dev->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_BORDER); dev->SetTexture(0, NULL); } compile_shaders(pass.fPrg, pass.vPrg, info.pass->source.cg); if (!init_fvf(pass)) return false; passes.push_back(pass); return true; }
void Viewer::init() { initializeOpenGLFunctions(); setBackgroundColor(::Qt::white); this->camera()->setSceneBoundingBox( CGAL::qglviewer::Vec(-1.,-1.,-1.), CGAL::qglviewer::Vec( 1., 1., 1.)); glEnable(GL_LINE_SMOOTH); compile_shaders(); are_buffers_initialized = false; }
void Image::initializeDraw() { //Shader Program GLInfo._pid = compile_shaders(vshader_srctxt, fshader_srctxt); glUseProgram(GLInfo._pid); //VAO glGenVertexArrays(1, &GLInfo._vao); glBindVertexArray(GLInfo._vao); //VBO_VPOINT ///--- Vertex coordinates { const GLfloat vpoint[] = { /*V0*/ -1.0f, -1.0f, 0.0f, /*V1*/ +1.0f, -1.0f, 0.0f, /*V2*/ -1.0f, +1.0f, 0.0f, /*V3*/ +1.0f, +1.0f, 0.0f }; ///--- Buffer glGenBuffers(1, &GLInfo._vbo_vpoint); glBindBuffer(GL_ARRAY_BUFFER, GLInfo._vbo_vpoint); glBufferData(GL_ARRAY_BUFFER, sizeof(vpoint), vpoint, GL_STATIC_DRAW); ///--- Attribute GLuint vpoint_id = glGetAttribLocation(GLInfo._pid, "vpoint"); glEnableVertexAttribArray(vpoint_id); glVertexAttribPointer(vpoint_id, 3, GL_FLOAT, GL_FALSE, 0, (void *)0); } //VBO_VTEXCOORD /// NOTE: swaps Y upside down to match top-left image coordinates system /// this way Image(0,0) is the top-left pixel in screen { const GLfloat vtexcoord[] = { /*v0*/ 0.0f, 1.0f, /*v1*/ 1.0f, 1.0f, /*v2*/ 0.0f, 0.0f, /*v3*/ 1.0f, 0.0f }; ///--- Buffer glGenBuffers(1, &GLInfo._vbo_vtexcoord); glBindBuffer(GL_ARRAY_BUFFER, GLInfo._vbo_vtexcoord); glBufferData(GL_ARRAY_BUFFER, sizeof(vtexcoord), vtexcoord, GL_STATIC_DRAW); ///--- Attribute GLuint vtexcoord_id = glGetAttribLocation(GLInfo._pid, "vtexcoord"); glEnableVertexAttribArray(vtexcoord_id); glVertexAttribPointer(vtexcoord_id, 2, GL_FLOAT, GL_FALSE, 0, (void *)0); } }
ShaderProgram loadShaders(ShaderFileList const& file_list) { if (file_list.empty()) { throw std::invalid_argument{ "loadShaders passed empty shader list"}; } ShaderObjectList shader_objects {load_shaders_from_files(file_list)}; compile_shaders(shader_objects); ShaderProgram shader_program; attach_shaders(shader_program, shader_objects); shader_program.link(); return shader_program; }
void startup() { rendering_program = compile_shaders(); GLuint buffer[2]; GLuint vao; static const GLfloat positions[] = { 0.25f, -0.25f, 0.5f, 1.0f, -0.25f, -0.25f, 0.5f, 1.0f, 0.25f, 0.25f, 0.5f, 1.0f }; static const GLfloat colors[] = { 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0 }; // Create the vertex array object. glCreateVertexArrays(1, &vao); // Create two buffers. glCreateBuffers(2, &buffer[0]); // Initialize the first buffer. glNamedBufferStorage(buffer[0], sizeof(positions), positions, 0); // Bind it to the vertex array - offset zero, stride = sizeof(vec4) glVertexArrayVertexBuffer(vao, 0, buffer[0], 0, sizeof(vmath::vec4)); // Tell OpenGL what the format of the attribute is. glVertexArrayAttribFormat(vao, 0, 4, GL_FLOAT, GL_FALSE, 0); // Tell OpenGL which vertex buffer binding to use for this attribute. glVertexArrayAttribBinding(vao, 0, 0); // Enable the attribute. glEnableVertexArrayAttrib(vao, 0); // Perform similar initialization for the second buffer. glNamedBufferStorage(buffer[1], sizeof(colors), colors, 0); glVertexArrayVertexBuffer(vao, 1, buffer[1], 0, sizeof(vmath::vec4)); glVertexArrayAttribFormat(vao, 1, 4, GL_FLOAT, GL_FALSE, 0); glVertexArrayAttribBinding(vao, 1, 1); glEnableVertexArrayAttrib(vao, 1); glEnableVertexAttribArray(1); glBindVertexArray(vao); }
static bool test_streams_size(GLint size, bool expect_compile_ok, bool expect_link_ok) { GLint program; GLint ok; GLint gs; gs = compile_shaders(size, expect_compile_ok, &ok); if (!ok) return ok == expect_compile_ok; /* Check if test was compiled but a compilation error was expected */ if (ok != expect_compile_ok) return false; printf("Stream count of %d should %s: ", size, expect_link_ok ? "link successfully" : "produce a link error"); program = glCreateProgram(); glAttachShader(program, vs); glAttachShader(program, gs); glAttachShader(program, fs); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &ok); if (!piglit_link_check_status(program)) { /* Details of the error have already been printed. */ printf("Link error occurred.\n"); } if (ok) printf("Successful link.\n"); else printf("Link error.\n"); glDetachShader(program, fs); glDetachShader(program, gs); glDetachShader(program, vs); glDeleteProgram(program); glDeleteShader(gs); return ok == expect_link_ok; }
void Scene::initGL(Viewer *viewer) { //qDebug()<<"context from scene is valid :"<<context->isValid(); //gl = 0; //gl = viewer->context()->versionFunctions<QOpenGLFunctions_3_3_Core>(); gl = new QOpenGLFunctions_3_3_Core(); //if (!gl) { // qFatal("Could not obtain required OpenGL context version"); // exit(1); //} if(!gl->initializeOpenGLFunctions()) { qFatal("ERROR : OpenGL Functions not initialized. Check your OpenGL Verison (should be >=3.3)"); exit(1); } gl->glGenTextures(1, &textureId); compile_shaders(); }
Scene_implicit_function_item:: Scene_implicit_function_item(Implicit_function_interface* f) : function_(f) , frame_(new ManipulatedFrame()) , grid_size_(SCENE_IMPLICIT_GRID_SIZE) , max_value_(0.) , min_value_(0.) , blue_color_ramp_() , red_color_ramp_() { compile_shaders(); texture = new Texture(grid_size_,grid_size_); blue_color_ramp_.build_blue(); red_color_ramp_.build_red(); compute_min_max(); compute_function_grid(); connect(frame_, SIGNAL(modified()), this, SLOT(compute_function_grid())); are_buffers_initialized = false; texture_initialized = false; }
bool RenderChain::add_pass(const LinkInfo &info) { Pass pass; pass.info = info; pass.last_width = 0; pass.last_height = 0; compile_shaders(pass.fPrg, pass.vPrg, info.pass->source.cg); if (!init_fvf(pass)) return false; if (FAILED(dev->CreateVertexBuffer( 4 * sizeof(Vertex), dev->GetSoftwareVertexProcessing() ? D3DUSAGE_SOFTWAREPROCESSING : 0, 0, D3DPOOL_DEFAULT, &pass.vertex_buf, NULL))) return false; if (FAILED(dev->CreateTexture(info.tex_w, info.tex_h, 1, D3DUSAGE_RENDERTARGET, passes.back().info.pass->fbo.fp_fbo ? D3DFMT_A32B32G32R32F : D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &pass.tex, NULL))) return false; dev->SetTexture(0, pass.tex); dev->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_BORDER); dev->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_BORDER); dev->SetTexture(0, NULL); passes.push_back(pass); log_info(info); return true; }
void Viewer::initializeGL() { QGLViewer::initializeGL(); compile_shaders(); }
int main(int argc, char **argv) { s32 result; result = SDL_Init(SDL_INIT_VIDEO); if(result) { ross_log("Failed to init SDL", LOG_ERROR); return(-1); } WindowDimension window_dimension; window_dimension.width = 800; window_dimension.height = 600; SDL_Window *window = SDL_CreateWindow("rossie", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, window_dimension.width, window_dimension.height, SDL_WINDOW_OPENGL | SDL_WINDOW_MAXIMIZED); if(window) { SDL_GLContext context = SDL_GL_CreateContext(window); if(context) { if(glewInit() == GLEW_OK) { global_running = 1; GLuint shader_program = compile_shaders(); ProgramBuffers program_buffers = setup_buffers(); glEnableClientState(GL_VERTEX_ARRAY); glViewport(0, 0, window_dimension.width, window_dimension.height); Input last_input = {}; while(global_running) { SDL_PumpEvents(); Input new_input; new_input = get_frame_input(); manage_events(new_input, window); render(new_input, last_input, shader_program, program_buffers); SDL_GL_SwapWindow(window); last_input = new_input; } } else { ross_log("Failed to init glew", LOG_ERROR); } SDL_GL_DeleteContext(context); } else { ross_log("Failed to create SDL GL context", LOG_ERROR); } } else { ross_log("Failed to create window", LOG_ERROR); } SDL_DestroyWindow(window); SDL_Quit(); return(0); }
//+------------------------------------------------------------------+ //| Построение сцены //+------------------------------------------------------------------+ SCFRESULT CScene::initialize(const int width, const int height) { SCFRESULT res=RES_S_OK; Shape cube; Shape ball; Shape plane; m_width =width; m_height=height; m_render.initialize(width, height); initiailizeMatrix(); // инициализируем окружение m_cube.program=compile_shaders("shaders\\skybox.vs.glsl", "shaders\\skybox.fs.glsl"); if(RES_FAIL(res=m_render.createShape(cube, m_cube))) ReturnError(res); if(RES_FAIL(res=m_texture_loader.loadTextureCubic("textures\\mountaincube.ktx", &m_cube.cube_map))) ReturnError(res); if(RES_FAIL(res=m_render.getUniforms(m_cube))) ReturnError(res); m_cube.view_matrix =m_view_matrix; // инициализируем шар if(RES_FAIL(res=m_shape_generator.createSphere(1, 40, 40, ball))) ReturnError(res); if(RES_FAIL(res=m_render.createShape(ball, m_ball))) ReturnError(res); m_ball.program =compile_shaders("shaders\\ball.vs.glsl", "shaders\\ball.fs.glsl"); m_ball.model_matrix =math::rotate(180.0f, 1.0f, 0.0f, 0.0f) *math::translate(0.0f, 2.0f, 0.0f); m_ball.proj_matrix =m_proj_matrix; m_ball.view_matrix =m_view_matrix; m_ball.light_position=m_light_position; m_ball.cube_map =m_cube.cube_map; if(RES_FAIL(res=m_texture_loader.loadTexturePng("textures\\ball_albedo.png", &m_ball.texture))) ReturnError(res); if(RES_FAIL(res=m_render.getUniforms(m_ball))) ReturnError(res); math::mat4 df=math::translate(0.0f, 2.0f, 0.0f); math::vec4 ss=math::vec4(0.0f, 0.0f, 0.0f, 1.0f)*((m_proj_matrix*m_view_matrix*m_ball.model_matrix).transpose()); DebugOutput("x=%d, y=%d\n", ss[0], ss[1]); // инициализируем плоскость if(RES_FAIL(res=m_shape_generator.createSquarePlane(10, plane))) ReturnError(res); if(RES_FAIL(res=m_render.createShape(plane, m_plane))) ReturnError(res); m_plane.program =compile_shaders("shaders\\table.vs.glsl", "shaders\\table.fs.glsl"); m_plane.model_matrix =math::translate(0.0f, -3.0f, 0.0f); m_plane.proj_matrix =m_proj_matrix; m_plane.view_matrix =m_view_matrix; m_plane.light_position=m_light_position; m_plane.shadow_matrix =m_shadow_sbpv_matrix * m_plane.model_matrix; if(RES_FAIL(res=m_texture_loader.loadTexturePng("textures\\table.png", &m_plane.texture))) ReturnError(res); if(RES_FAIL(res=m_render.getUniforms(m_plane))) ReturnError(res); m_shadow_program=compile_shaders("shaders\\light.vs.glsl", "shaders\\light.fs.glsl"); if(RES_FAIL(res=m_texture_loader.generateShadowTexture(&m_shadow_frame_buffer, &m_shadow_texture))) ReturnError(res); m_plane.texture_shadow=m_shadow_texture; m_ball.texture_shadow =m_shadow_texture; // инициализируем объекты для карты теней m_ball_shadow =m_ball; m_plane_shadow=m_plane; m_ball_shadow.program =0; m_ball_shadow.cube_map=0; m_ball_shadow.texture =0; m_plane_shadow.program=0; m_ball_shadow.proj_matrix =m_light_proj_matrix; m_ball_shadow.view_matrix =m_light_view_matrix; m_plane_shadow.proj_matrix=m_light_proj_matrix; m_plane_shadow.view_matrix=m_light_view_matrix; m_render.getUniforms(m_ball_shadow, &m_shadow_program); m_render.getUniforms(m_plane_shadow, &m_shadow_program); return(RES_S_OK); }
void startup() { rendering_program = compile_shaders(); glGenVertexArrays(1, &vertex_array_object); glBindVertexArray(vertex_array_object); }
VdpStatus vdpDeviceCreateX11(Display *display_orig, int screen, VdpDevice *device, VdpGetProcAddress **get_proc_address) { if (!display_orig || !device) return VDP_STATUS_INVALID_POINTER; // Let's get own connection to the X server Display *display = handle_xdpy_ref(display_orig); if (NULL == display) return VDP_STATUS_ERROR; if (global.quirks.buggy_XCloseDisplay) { // XCloseDisplay could segfault on fglrx. To avoid calling XCloseDisplay, // make one more reference to xdpy copy. handle_xdpy_ref(display_orig); } VdpDeviceData *data = calloc(1, sizeof(VdpDeviceData)); if (NULL == data) return VDP_STATUS_RESOURCES; glx_ctx_lock(); // use glx lock to serialize X calls data->type = HANDLETYPE_DEVICE; data->display = display; data->display_orig = display_orig; // save supplied pointer too data->screen = screen; data->refcount = 0; pthread_mutex_init(&data->refcount_mutex, NULL); data->root = DefaultRootWindow(display); XWindowAttributes wnd_attrs; XGetWindowAttributes(display, data->root, &wnd_attrs); data->color_depth = wnd_attrs.depth; data->fn.glXBindTexImageEXT = (PFNGLXBINDTEXIMAGEEXTPROC)glXGetProcAddress((GLubyte *)"glXBindTexImageEXT"); data->fn.glXReleaseTexImageEXT = (PFNGLXRELEASETEXIMAGEEXTPROC)glXGetProcAddress((GLubyte *)"glXReleaseTexImageEXT"); glx_ctx_unlock(); if (!data->fn.glXBindTexImageEXT || !data->fn.glXReleaseTexImageEXT) { traceError("error (%s): can't get glXBindTexImageEXT address\n"); free(data); return VDP_STATUS_RESOURCES; } // create master GLX context to share data between further created ones glx_ctx_ref_glc_hash_table(display, screen); data->root_glc = glx_ctx_get_root_context(); glx_ctx_push_thread_local(data); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // initialize VAAPI if (global.quirks.avoid_va) { // pretend there is no VA-API available data->va_available = 0; } else { data->va_dpy = vaGetDisplay(display); data->va_available = 0; VAStatus status = vaInitialize(data->va_dpy, &data->va_version_major, &data->va_version_minor); if (VA_STATUS_SUCCESS == status) { data->va_available = 1; traceInfo("libva (version %d.%d) library initialized\n", data->va_version_major, data->va_version_minor); } else { data->va_available = 0; traceInfo("warning: failed to initialize libva. " "No video decode acceleration available.\n"); } } compile_shaders(data); glGenTextures(1, &data->watermark_tex_id); glBindTexture(GL_TEXTURE_2D, data->watermark_tex_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, watermark_width, watermark_height, 0, GL_BGRA, GL_UNSIGNED_BYTE, watermark_data); glFinish(); *device = handle_insert(data); if (get_proc_address) *get_proc_address = &vdpGetProcAddress; GLenum gl_error = glGetError(); glx_ctx_pop(); if (GL_NO_ERROR != gl_error) { traceError("error (%s): gl error %d\n", __func__, gl_error); return VDP_STATUS_ERROR; } return VDP_STATUS_OK; }
void InitializeGL() { //Compile the shaders programID = compile_shaders(vshader_square, fshader_square); //Generate Vertex Array and bind the vertex buffer data glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); ///--- Generate memory for vertexbuffer GLuint vertexbuffer; glGenBuffers(1, &vertexbuffer); /// The subsequent commands will affect the specified buffer glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); /// Pass the vertex positions to OpenGL glBufferData(GL_ARRAY_BUFFER, sizeof(vpoint), vpoint, GL_STATIC_DRAW); ///--- find the binding point in the shader: /// "vpoint" in the vertex shader glUseProgram(programID); GLuint vpoint_id = glGetAttribLocation(programID, "vpoint"); glEnableVertexAttribArray(vpoint_id); glVertexAttribPointer(vpoint_id, 3, //size per vertex (3 floats for cord) GL_FLOAT, false, //don't normalize 0, //stride = 0 0); //offset = 0 GLuint vtexcoordbuffer; glGenBuffers(1, &vtexcoordbuffer); glBindBuffer(GL_ARRAY_BUFFER, vtexcoordbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vtexcoord), vtexcoord, GL_STATIC_DRAW); glUseProgram(programID); //Don't need to do this here again, but it's safe GLuint vtexcoord_binding = glGetAttribLocation(programID, "vtexcoord"); glEnableVertexAttribArray(vtexcoord_binding); glVertexAttribPointer(vtexcoord_binding, 2, GL_FLOAT, false, 0, 0); //Load texture Texture teximage = LoadPNGTexture("texture.png"); //Upload this image onto GPU GLuint texobject; glGenTextures(1, &texobject); glBindTexture(GL_TEXTURE_2D, texobject); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); //the i at the end means to integer glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, teximage.width, teximage.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, teximage.dataptr); // -- Activate the texture image GLuint sampler_ID = glGetUniformLocation(programID, "tex"); glUniform1i(sampler_ID, 0); //Means? If tex is a uniform with type int, then that api call will set this int to 0, but it's a sampler2D, then we tell it to usee the first sampler glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texobject); //Find the binding point for the uniform variable //"rotation" in vertex shader RotBindingID = glGetUniformLocation(programID, "rotation"); }
int main() { srand(time(0)); for (int i = 0; i < 3; i++) gColor[i] = random_float(); signal(SIGINT, signal_handler); SDL_Init(SDL_INIT_VIDEO); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); /* Create our window centered at 512x512 resolution */ gWindow = SDL_CreateWindow("Hello Triangle", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN); SDL_GL_CreateContext(gWindow); SDL_GL_SetSwapInterval(1); /* create a black box context */ if (!bbgl_init(&bbgl)) { fprintf(stderr, "[bbgl] (client) failed to connect to black box\n"); return -1; } glViewport(0, 0, 800, 600); glClearColor(0.0f, 0.0f, 1.0f, 1.0f); //const char *vendor = (const char *)glGetString(GL_VENDOR); //const char *renderer = (const char *)glGetString(GL_RENDERER); //const char *version = (const char *)glGetString(GL_VERSION); //const char *shading = (const char *)glGetString(GL_SHADING_LANGUAGE_VERSION); //printf("vendor: %s\n", vendor); //printf("renderer: %s\n", renderer); //printf("version: %s\n", version); //printf("shading: %s\n", shading); create_vertex_array(); create_vertex_buffer(); compile_shaders(); int frames = 0; Uint32 start = SDL_GetTicks(); int dirs[3] = { +1, +1, +1 }; while (gRunning) { ++frames; Uint32 elapsed = SDL_GetTicks() - start; if (elapsed) { double seconds = elapsed / 1000.0; double fps = frames / seconds; printf("\r%g FPS\n", fps); } SDL_Event e; while (SDL_PollEvent(&e)) { switch (e.type) { case SDL_QUIT: gRunning = 0; break; } } render(); for (int i = 0; i < 3; i++) { int value = ((int)(gColor[i] * 255.0f)+dirs[i]); if (value > 255 || value <= 0) dirs[i] = -dirs[i]; gColor[i] = value/255.0f; } } bbgl_destroy(&bbgl); return 0; }
bool shader_cache_read_program_metadata(struct gl_context *ctx, struct gl_shader_program *prog) { /* Fixed function programs generated by Mesa are not cached. So don't * try to read metadata for them from the cache. */ if (prog->Name == 0) return false; struct disk_cache *cache = ctx->Cache; if (!cache) return false; /* Include bindings when creating sha1. These bindings change the resulting * binary so they are just as important as the shader source. */ char *buf = ralloc_strdup(NULL, "vb: "); prog->AttributeBindings->iterate(create_binding_str, &buf); ralloc_strcat(&buf, "fb: "); prog->FragDataBindings->iterate(create_binding_str, &buf); ralloc_strcat(&buf, "fbi: "); prog->FragDataIndexBindings->iterate(create_binding_str, &buf); /* SSO has an effect on the linked program so include this when generating * the sha also. */ ralloc_asprintf_append(&buf, "sso: %s\n", prog->SeparateShader ? "T" : "F"); /* A shader might end up producing different output depending on the glsl * version supported by the compiler. For example a different path might be * taken by the preprocessor, so add the version to the hash input. */ ralloc_asprintf_append(&buf, "api: %d glsl: %d fglsl: %d\n", ctx->API, ctx->Const.GLSLVersion, ctx->Const.ForceGLSLVersion); /* We run the preprocessor on shaders after hashing them, so we need to * add any extension override vars to the hash. If we don't do this the * preprocessor could result in different output and we could load the * wrong shader. */ char *ext_override = getenv("MESA_EXTENSION_OVERRIDE"); if (ext_override) { ralloc_asprintf_append(&buf, "ext:%s", ext_override); } /* DRI config options may also change the output from the compiler so * include them as an input to sha1 creation. */ char sha1buf[41]; _mesa_sha1_format(sha1buf, ctx->Const.dri_config_options_sha1); ralloc_strcat(&buf, sha1buf); for (unsigned i = 0; i < prog->NumShaders; i++) { struct gl_shader *sh = prog->Shaders[i]; _mesa_sha1_format(sha1buf, sh->sha1); ralloc_asprintf_append(&buf, "%s: %s\n", _mesa_shader_stage_to_abbrev(sh->Stage), sha1buf); } disk_cache_compute_key(cache, buf, strlen(buf), prog->data->sha1); ralloc_free(buf); size_t size; uint8_t *buffer = (uint8_t *) disk_cache_get(cache, prog->data->sha1, &size); if (buffer == NULL) { /* Cached program not found. We may have seen the individual shaders * before and skipped compiling but they may not have been used together * in this combination before. Fall back to linking shaders but first * re-compile the shaders. * * We could probably only compile the shaders which were skipped here * but we need to be careful because the source may also have been * changed since the last compile so for now we just recompile * everything. */ compile_shaders(ctx, prog); return false; } if (ctx->_Shader->Flags & GLSL_CACHE_INFO) { _mesa_sha1_format(sha1buf, prog->data->sha1); fprintf(stderr, "loading shader program meta data from cache: %s\n", sha1buf); } struct blob_reader metadata; blob_reader_init(&metadata, buffer, size); bool deserialized = deserialize_glsl_program(&metadata, ctx, prog); if (!deserialized || metadata.current != metadata.end || metadata.overrun) { /* Something has gone wrong discard the item from the cache and rebuild * from source. */ assert(!"Invalid GLSL shader disk cache item!"); if (ctx->_Shader->Flags & GLSL_CACHE_INFO) { fprintf(stderr, "Error reading program from cache (invalid GLSL " "cache item)\n"); } disk_cache_remove(cache, prog->data->sha1); compile_shaders(ctx, prog); free(buffer); return false; } /* This is used to flag a shader retrieved from cache */ prog->data->LinkStatus = linking_skipped; /* Since the program load was successful, CompileStatus of all shaders at * this point should normally be compile_skipped. However because of how * the eviction works, it may happen that some of the individual shader keys * have been evicted, resulting in unnecessary recompiles on this load, so * mark them again to skip such recompiles next time. */ char sha1_buf[41]; for (unsigned i = 0; i < prog->NumShaders; i++) { if (prog->Shaders[i]->CompileStatus == compiled_no_opts) { disk_cache_put_key(cache, prog->Shaders[i]->sha1); if (ctx->_Shader->Flags & GLSL_CACHE_INFO) { _mesa_sha1_format(sha1_buf, prog->Shaders[i]->sha1); fprintf(stderr, "re-marking shader: %s\n", sha1_buf); } } } free (buffer); return true; }