1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
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 * http://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
16 #include "ec_log.h"
17 #include "program.h"
18
19 namespace OHOS {
20 namespace Rosen {
Compile(const std::string & vertexShader,const std::string & fragmentShader)21 void Program::Compile(const std::string& vertexShader, const std::string& fragmentShader)
22 {
23 vertexID_ = CreateShader(GL_VERTEX_SHADER, vertexShader);
24 fragmentID_ = CreateShader(GL_FRAGMENT_SHADER, fragmentShader);
25 if (!initFlag_) {
26 initFlag_ = true;
27 programID_ = glCreateProgram();
28 }
29 glAttachShader(programID_, vertexID_);
30 glAttachShader(programID_, fragmentID_);
31 glLinkProgram(programID_);
32 CheckProgramLinkErrors(programID_);
33 glDeleteShader(vertexID_);
34 glDeleteShader(fragmentID_);
35 }
36
UseProgram() const37 void Program::UseProgram() const
38 {
39 glUseProgram(programID_);
40 }
41
CreateShader(GLuint type,const std::string & shaderCode)42 GLuint Program::CreateShader(GLuint type, const std::string& shaderCode)
43 {
44 const GLchar* charShaderCode = (const GLchar*)shaderCode.c_str();
45 GLuint shader = glCreateShader(type);
46 glShaderSource(shader, 1, &charShaderCode, nullptr);
47 glCompileShader(shader);
48 if (type == GL_VERTEX_SHADER) {
49 CheckShaderCompileErrors(shader, "vertex");
50 } else if (type == GL_FRAGMENT_SHADER) {
51 CheckShaderCompileErrors(shader, "fragment");
52 }
53 return shader;
54 }
55
CheckShaderCompileErrors(GLuint shader,const std::string & type)56 void Program::CheckShaderCompileErrors(GLuint shader, const std::string& type)
57 {
58 GLint complete = 0;
59 GLchar infoLog[INFO_LOG_LENGTH];
60 glGetShaderiv(shader, GL_COMPILE_STATUS, &complete);
61 if (!complete) {
62 glGetShaderInfoLog(shader, INFO_LOG_LENGTH, nullptr, infoLog);
63 LOGE("Shader compile error of type: %{public}s, errorInfo: %{public}s", type.c_str(), infoLog);
64 }
65 }
66
CheckProgramLinkErrors(GLuint program)67 void Program::CheckProgramLinkErrors(GLuint program)
68 {
69 GLint complete = 0;
70 GLchar infoLog[INFO_LOG_LENGTH];
71 glGetProgramiv(program, GL_LINK_STATUS, &complete);
72 if (!complete) {
73 glGetProgramInfoLog(program, INFO_LOG_LENGTH, nullptr, infoLog);
74 LOGE("Program linking error: %{public}s", infoLog);
75 }
76 }
77 } // namespcae Rosen
78 } // namespace OHOS