1 // Copyright 2018 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "tools/render/shader.h"
16
17 #include "absl/strings/str_cat.h"
18 #include "tools/render/program_state.h"
19
20 namespace quic_trace {
21 namespace render {
22
23 const char* kShaderPreamble = "#version 150 core";
24
25 const char* kShaderLibrary = R"(
26 // Transforms the window coordinates into the GL coordinates.
27 vec4 windowToGl(vec2 window_point) {
28 return vec4((window_point / program_state.window) * 2 - vec2(1, 1), 0, 1);
29 }
30 )";
31
PreprocessShader(const char * shader)32 static std::string PreprocessShader(const char* shader) {
33 return absl::StrCat(kShaderPreamble, "\n", kProgramStateData, "\n",
34 kShaderLibrary, "\n", shader);
35 }
36
Shader(const char * vertex_code,const char * fragment_code)37 Shader::Shader(const char* vertex_code, const char* fragment_code)
38 : Shader(vertex_code, nullptr, fragment_code) {}
39
Shader(const char * vertex_code,const char * geometry_code,const char * fragment_code)40 Shader::Shader(const char* vertex_code,
41 const char* geometry_code,
42 const char* fragment_code)
43 : vertex_shader_(GL_VERTEX_SHADER), fragment_shader_(GL_FRAGMENT_SHADER) {
44 vertex_shader_.CompileOrDie(PreprocessShader(vertex_code).c_str());
45 Attach(vertex_shader_);
46
47 fragment_shader_.CompileOrDie(PreprocessShader(fragment_code).c_str());
48 Attach(fragment_shader_);
49
50 if (geometry_code != nullptr) {
51 geometry_shader_.emplace(GL_GEOMETRY_SHADER);
52 geometry_shader_->CompileOrDie(PreprocessShader(geometry_code).c_str());
53 Attach(*geometry_shader_);
54 }
55
56 CHECK(Link());
57 }
58
59 } // namespace render
60 } // namespace quic_trace
61