1 //
2 // Copyright 2015 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6
7 // ProgramGL.cpp: Implements the class methods for ProgramGL.
8
9 #include "libANGLE/renderer/gl/ProgramGL.h"
10
11 #include "common/angleutils.h"
12 #include "common/bitset_utils.h"
13 #include "common/debug.h"
14 #include "common/string_utils.h"
15 #include "common/utilities.h"
16 #include "libANGLE/Context.h"
17 #include "libANGLE/ProgramLinkedResources.h"
18 #include "libANGLE/Uniform.h"
19 #include "libANGLE/WorkerThread.h"
20 #include "libANGLE/queryconversions.h"
21 #include "libANGLE/renderer/gl/ContextGL.h"
22 #include "libANGLE/renderer/gl/FunctionsGL.h"
23 #include "libANGLE/renderer/gl/RendererGL.h"
24 #include "libANGLE/renderer/gl/ShaderGL.h"
25 #include "libANGLE/renderer/gl/StateManagerGL.h"
26 #include "platform/FeaturesGL.h"
27 #include "platform/Platform.h"
28
29 namespace rx
30 {
31
ProgramGL(const gl::ProgramState & data,const FunctionsGL * functions,const angle::FeaturesGL & features,StateManagerGL * stateManager,const std::shared_ptr<RendererGL> & renderer)32 ProgramGL::ProgramGL(const gl::ProgramState &data,
33 const FunctionsGL *functions,
34 const angle::FeaturesGL &features,
35 StateManagerGL *stateManager,
36 const std::shared_ptr<RendererGL> &renderer)
37 : ProgramImpl(data),
38 mFunctions(functions),
39 mFeatures(features),
40 mStateManager(stateManager),
41 mMultiviewBaseViewLayerIndexUniformLocation(-1),
42 mProgramID(0),
43 mRenderer(renderer),
44 mLinkedInParallel(false)
45 {
46 ASSERT(mFunctions);
47 ASSERT(mStateManager);
48
49 mProgramID = mFunctions->createProgram();
50 }
51
~ProgramGL()52 ProgramGL::~ProgramGL()
53 {
54 mFunctions->deleteProgram(mProgramID);
55 mProgramID = 0;
56 }
57
load(const gl::Context * context,gl::BinaryInputStream * stream,gl::InfoLog & infoLog)58 std::unique_ptr<LinkEvent> ProgramGL::load(const gl::Context *context,
59 gl::BinaryInputStream *stream,
60 gl::InfoLog &infoLog)
61 {
62 preLink();
63
64 // Read the binary format, size and blob
65 GLenum binaryFormat = stream->readInt<GLenum>();
66 GLint binaryLength = stream->readInt<GLint>();
67 const uint8_t *binary = stream->data() + stream->offset();
68 stream->skip(binaryLength);
69
70 // Load the binary
71 mFunctions->programBinary(mProgramID, binaryFormat, binary, binaryLength);
72
73 // Verify that the program linked
74 if (!checkLinkStatus(infoLog))
75 {
76 return std::make_unique<LinkEventDone>(angle::Result::Incomplete);
77 }
78
79 postLink();
80 reapplyUBOBindingsIfNeeded(context);
81
82 return std::make_unique<LinkEventDone>(angle::Result::Continue);
83 }
84
save(const gl::Context * context,gl::BinaryOutputStream * stream)85 void ProgramGL::save(const gl::Context *context, gl::BinaryOutputStream *stream)
86 {
87 GLint binaryLength = 0;
88 mFunctions->getProgramiv(mProgramID, GL_PROGRAM_BINARY_LENGTH, &binaryLength);
89
90 std::vector<uint8_t> binary(std::max(binaryLength, 1));
91 GLenum binaryFormat = GL_NONE;
92 mFunctions->getProgramBinary(mProgramID, binaryLength, &binaryLength, &binaryFormat,
93 binary.data());
94
95 stream->writeInt(binaryFormat);
96 stream->writeInt(binaryLength);
97 stream->writeBytes(binary.data(), binaryLength);
98
99 reapplyUBOBindingsIfNeeded(context);
100 }
101
reapplyUBOBindingsIfNeeded(const gl::Context * context)102 void ProgramGL::reapplyUBOBindingsIfNeeded(const gl::Context *context)
103 {
104 // Re-apply UBO bindings to work around driver bugs.
105 const angle::FeaturesGL &features = GetImplAs<ContextGL>(context)->getFeaturesGL();
106 if (features.reapplyUBOBindingsAfterUsingBinaryProgram.enabled)
107 {
108 const auto &blocks = mState.getUniformBlocks();
109 for (size_t blockIndex : mState.getActiveUniformBlockBindingsMask())
110 {
111 setUniformBlockBinding(static_cast<GLuint>(blockIndex), blocks[blockIndex].binding);
112 }
113 }
114 }
115
setBinaryRetrievableHint(bool retrievable)116 void ProgramGL::setBinaryRetrievableHint(bool retrievable)
117 {
118 // glProgramParameteri isn't always available on ES backends.
119 if (mFunctions->programParameteri)
120 {
121 mFunctions->programParameteri(mProgramID, GL_PROGRAM_BINARY_RETRIEVABLE_HINT,
122 retrievable ? GL_TRUE : GL_FALSE);
123 }
124 }
125
setSeparable(bool separable)126 void ProgramGL::setSeparable(bool separable)
127 {
128 mFunctions->programParameteri(mProgramID, GL_PROGRAM_SEPARABLE, separable ? GL_TRUE : GL_FALSE);
129 }
130
131 using LinkImplFunctor = std::function<bool(std::string &)>;
132 class ProgramGL::LinkTask final : public angle::Closure
133 {
134 public:
LinkTask(LinkImplFunctor && functor)135 LinkTask(LinkImplFunctor &&functor) : mLinkImplFunctor(functor), mFallbackToMainContext(false)
136 {}
137
operator ()()138 void operator()() override { mFallbackToMainContext = mLinkImplFunctor(mInfoLog); }
fallbackToMainContext()139 bool fallbackToMainContext() { return mFallbackToMainContext; }
getInfoLog()140 const std::string &getInfoLog() { return mInfoLog; }
141
142 private:
143 LinkImplFunctor mLinkImplFunctor;
144 bool mFallbackToMainContext;
145 std::string mInfoLog;
146 };
147
148 using PostLinkImplFunctor = std::function<angle::Result(bool, const std::string &)>;
149
150 // The event for a parallelized linking using the native driver extension.
151 class ProgramGL::LinkEventNativeParallel final : public LinkEvent
152 {
153 public:
LinkEventNativeParallel(PostLinkImplFunctor && functor,const FunctionsGL * functions,GLuint programID)154 LinkEventNativeParallel(PostLinkImplFunctor &&functor,
155 const FunctionsGL *functions,
156 GLuint programID)
157 : mPostLinkImplFunctor(functor), mFunctions(functions), mProgramID(programID)
158 {}
159
wait(const gl::Context * context)160 angle::Result wait(const gl::Context *context) override
161 {
162 GLint linkStatus = GL_FALSE;
163 mFunctions->getProgramiv(mProgramID, GL_LINK_STATUS, &linkStatus);
164 if (linkStatus == GL_TRUE)
165 {
166 return mPostLinkImplFunctor(false, std::string());
167 }
168 return angle::Result::Incomplete;
169 }
170
isLinking()171 bool isLinking() override
172 {
173 GLint completionStatus = GL_FALSE;
174 mFunctions->getProgramiv(mProgramID, GL_COMPLETION_STATUS, &completionStatus);
175 return completionStatus == GL_FALSE;
176 }
177
178 private:
179 PostLinkImplFunctor mPostLinkImplFunctor;
180 const FunctionsGL *mFunctions;
181 GLuint mProgramID;
182 };
183
184 // The event for a parallelized linking using the worker thread pool.
185 class ProgramGL::LinkEventGL final : public LinkEvent
186 {
187 public:
LinkEventGL(std::shared_ptr<angle::WorkerThreadPool> workerPool,std::shared_ptr<ProgramGL::LinkTask> linkTask,PostLinkImplFunctor && functor)188 LinkEventGL(std::shared_ptr<angle::WorkerThreadPool> workerPool,
189 std::shared_ptr<ProgramGL::LinkTask> linkTask,
190 PostLinkImplFunctor &&functor)
191 : mLinkTask(linkTask),
192 mWaitableEvent(std::shared_ptr<angle::WaitableEvent>(
193 angle::WorkerThreadPool::PostWorkerTask(workerPool, mLinkTask))),
194 mPostLinkImplFunctor(functor)
195 {}
196
wait(const gl::Context * context)197 angle::Result wait(const gl::Context *context) override
198 {
199 mWaitableEvent->wait();
200 return mPostLinkImplFunctor(mLinkTask->fallbackToMainContext(), mLinkTask->getInfoLog());
201 }
202
isLinking()203 bool isLinking() override { return !mWaitableEvent->isReady(); }
204
205 private:
206 std::shared_ptr<ProgramGL::LinkTask> mLinkTask;
207 std::shared_ptr<angle::WaitableEvent> mWaitableEvent;
208 PostLinkImplFunctor mPostLinkImplFunctor;
209 };
210
link(const gl::Context * context,const gl::ProgramLinkedResources & resources,gl::InfoLog & infoLog)211 std::unique_ptr<LinkEvent> ProgramGL::link(const gl::Context *context,
212 const gl::ProgramLinkedResources &resources,
213 gl::InfoLog &infoLog)
214 {
215 preLink();
216
217 if (mState.getAttachedShader(gl::ShaderType::Compute))
218 {
219 const ShaderGL *computeShaderGL =
220 GetImplAs<ShaderGL>(mState.getAttachedShader(gl::ShaderType::Compute));
221
222 mFunctions->attachShader(mProgramID, computeShaderGL->getShaderID());
223 }
224 else
225 {
226 // Set the transform feedback state
227 std::vector<std::string> transformFeedbackVaryingMappedNames;
228 for (const auto &tfVarying : mState.getTransformFeedbackVaryingNames())
229 {
230 gl::ShaderType tfShaderType =
231 mState.getProgramExecutable().hasLinkedShaderStage(gl::ShaderType::Geometry)
232 ? gl::ShaderType::Geometry
233 : gl::ShaderType::Vertex;
234 std::string tfVaryingMappedName =
235 mState.getAttachedShader(tfShaderType)
236 ->getTransformFeedbackVaryingMappedName(tfVarying);
237 transformFeedbackVaryingMappedNames.push_back(tfVaryingMappedName);
238 }
239
240 if (transformFeedbackVaryingMappedNames.empty())
241 {
242 if (mFunctions->transformFeedbackVaryings)
243 {
244 mFunctions->transformFeedbackVaryings(mProgramID, 0, nullptr,
245 mState.getTransformFeedbackBufferMode());
246 }
247 }
248 else
249 {
250 ASSERT(mFunctions->transformFeedbackVaryings);
251 std::vector<const GLchar *> transformFeedbackVaryings;
252 for (const auto &varying : transformFeedbackVaryingMappedNames)
253 {
254 transformFeedbackVaryings.push_back(varying.c_str());
255 }
256 mFunctions->transformFeedbackVaryings(
257 mProgramID, static_cast<GLsizei>(transformFeedbackVaryingMappedNames.size()),
258 &transformFeedbackVaryings[0], mState.getTransformFeedbackBufferMode());
259 }
260
261 for (const gl::ShaderType shaderType : gl::kAllGraphicsShaderTypes)
262 {
263 const ShaderGL *shaderGL =
264 rx::SafeGetImplAs<ShaderGL, gl::Shader>(mState.getAttachedShader(shaderType));
265 if (shaderGL)
266 {
267 mFunctions->attachShader(mProgramID, shaderGL->getShaderID());
268 }
269 }
270
271 // Bind attribute locations to match the GL layer.
272 for (const sh::ShaderVariable &attribute : mState.getProgramInputs())
273 {
274 if (!attribute.active || attribute.isBuiltIn())
275 {
276 continue;
277 }
278
279 mFunctions->bindAttribLocation(mProgramID, attribute.location,
280 attribute.mappedName.c_str());
281 }
282
283 // Bind the secondary fragment color outputs defined in EXT_blend_func_extended. We only use
284 // the API to bind fragment output locations in case EXT_blend_func_extended is enabled.
285 // Otherwise shader-assigned locations will work.
286 if (context->getExtensions().blendFuncExtended)
287 {
288 gl::Shader *fragmentShader = mState.getAttachedShader(gl::ShaderType::Fragment);
289 if (fragmentShader && fragmentShader->getShaderVersion() == 100)
290 {
291 // TODO(http://anglebug.com/2833): The bind done below is only valid in case the
292 // compiler transforms the shader outputs to the angle/webgl prefixed ones. If we
293 // added support for running EXT_blend_func_extended on top of GLES, some changes
294 // would be required:
295 // - If we're backed by GLES 2.0, we shouldn't do the bind because it's not needed.
296 // - If we're backed by GLES 3.0+, it's a bit unclear what should happen. Currently
297 // the compiler doesn't support transforming GLSL ES 1.00 shaders to GLSL ES 3.00
298 // shaders in general, but support for that might be required. Or we might be
299 // able to skip the bind in case the compiler outputs GLSL ES 1.00.
300 const auto &shaderOutputs =
301 mState.getAttachedShader(gl::ShaderType::Fragment)->getActiveOutputVariables();
302 for (const auto &output : shaderOutputs)
303 {
304 // TODO(http://anglebug.com/1085) This could be cleaner if the transformed names
305 // would be set correctly in ShaderVariable::mappedName. This would require some
306 // refactoring in the translator. Adding a mapped name dictionary for builtins
307 // into the symbol table would be one fairly clean way to do it.
308 if (output.name == "gl_SecondaryFragColorEXT")
309 {
310 mFunctions->bindFragDataLocationIndexed(mProgramID, 0, 0,
311 "webgl_FragColor");
312 mFunctions->bindFragDataLocationIndexed(mProgramID, 0, 1,
313 "angle_SecondaryFragColor");
314 }
315 else if (output.name == "gl_SecondaryFragDataEXT")
316 {
317 // Basically we should have a loop here going over the output
318 // array binding "webgl_FragData[i]" and "angle_SecondaryFragData[i]" array
319 // indices to the correct color buffers and color indices.
320 // However I'm not sure if this construct is legal or not, neither ARB or
321 // EXT version of the spec mention this. They only mention that
322 // automatically assigned array locations for ESSL 3.00 output arrays need
323 // to have contiguous locations.
324 //
325 // In practice it seems that binding array members works on some drivers and
326 // fails on others. One option could be to modify the shader translator to
327 // expand the arrays into individual output variables instead of using an
328 // array.
329 //
330 // For now we're going to have a limitation of assuming that
331 // GL_MAX_DUAL_SOURCE_DRAW_BUFFERS is *always* 1 and then only bind the
332 // basename of the variable ignoring any indices. This appears to work
333 // uniformly.
334 ASSERT(output.isArray() && output.getOutermostArraySize() == 1);
335
336 mFunctions->bindFragDataLocationIndexed(mProgramID, 0, 0, "webgl_FragData");
337 mFunctions->bindFragDataLocationIndexed(mProgramID, 0, 1,
338 "angle_SecondaryFragData");
339 }
340 }
341 }
342 else
343 {
344 // ESSL 3.00 and up.
345 const auto &outputLocations = mState.getOutputLocations();
346 const auto &secondaryOutputLocations = mState.getSecondaryOutputLocations();
347 for (size_t outputLocationIndex = 0u; outputLocationIndex < outputLocations.size();
348 ++outputLocationIndex)
349 {
350 const gl::VariableLocation &outputLocation =
351 outputLocations[outputLocationIndex];
352 if (outputLocation.arrayIndex == 0 && outputLocation.used() &&
353 !outputLocation.ignored)
354 {
355 const sh::ShaderVariable &outputVar =
356 mState.getOutputVariables()[outputLocation.index];
357 if (outputVar.location == -1)
358 {
359 // We only need to assign the location and index via the API in case the
360 // variable doesn't have its location set in the shader. If a variable
361 // doesn't have its location set in the shader it doesn't have the index
362 // set either.
363 ASSERT(outputVar.index == -1);
364 mFunctions->bindFragDataLocationIndexed(
365 mProgramID, static_cast<int>(outputLocationIndex), 0,
366 outputVar.mappedName.c_str());
367 }
368 }
369 }
370 for (size_t outputLocationIndex = 0u;
371 outputLocationIndex < secondaryOutputLocations.size(); ++outputLocationIndex)
372 {
373 const gl::VariableLocation &outputLocation =
374 secondaryOutputLocations[outputLocationIndex];
375 if (outputLocation.arrayIndex == 0 && outputLocation.used() &&
376 !outputLocation.ignored)
377 {
378 const sh::ShaderVariable &outputVar =
379 mState.getOutputVariables()[outputLocation.index];
380 if (outputVar.location == -1 || outputVar.index == -1)
381 {
382 // We only need to assign the location and index via the API in case the
383 // variable doesn't have a shader-assigned location and index. If a
384 // variable doesn't have its location set in the shader it doesn't have
385 // the index set either.
386 ASSERT(outputVar.index == -1);
387 mFunctions->bindFragDataLocationIndexed(
388 mProgramID, static_cast<int>(outputLocationIndex), 1,
389 outputVar.mappedName.c_str());
390 }
391 }
392 }
393 }
394 }
395 }
396 auto workerPool = context->getWorkerThreadPool();
397 auto linkTask = std::make_shared<LinkTask>([this](std::string &infoLog) {
398 std::string workerInfoLog;
399 ScopedWorkerContextGL worker(mRenderer.get(), &workerInfoLog);
400 if (!worker())
401 {
402 #if !defined(NDEBUG)
403 infoLog += "bindWorkerContext failed.\n" + workerInfoLog;
404 #endif
405 // Fallback to the main context.
406 return true;
407 }
408
409 mFunctions->linkProgram(mProgramID);
410
411 // Make sure the driver actually does the link job.
412 GLint linkStatus = GL_FALSE;
413 mFunctions->getProgramiv(mProgramID, GL_LINK_STATUS, &linkStatus);
414
415 return false;
416 });
417
418 auto postLinkImplTask = [this, &infoLog, &resources](bool fallbackToMainContext,
419 const std::string &workerInfoLog) {
420 infoLog << workerInfoLog;
421 if (fallbackToMainContext)
422 {
423 mFunctions->linkProgram(mProgramID);
424 }
425
426 if (mState.getAttachedShader(gl::ShaderType::Compute))
427 {
428 const ShaderGL *computeShaderGL =
429 GetImplAs<ShaderGL>(mState.getAttachedShader(gl::ShaderType::Compute));
430
431 mFunctions->detachShader(mProgramID, computeShaderGL->getShaderID());
432 }
433 else
434 {
435 for (const gl::ShaderType shaderType : gl::kAllGraphicsShaderTypes)
436 {
437 const ShaderGL *shaderGL =
438 rx::SafeGetImplAs<ShaderGL>(mState.getAttachedShader(shaderType));
439 if (shaderGL)
440 {
441 mFunctions->detachShader(mProgramID, shaderGL->getShaderID());
442 }
443 }
444 }
445 // Verify the link
446 if (!checkLinkStatus(infoLog))
447 {
448 return angle::Result::Incomplete;
449 }
450
451 if (mFeatures.alwaysCallUseProgramAfterLink.enabled)
452 {
453 mStateManager->forceUseProgram(mProgramID);
454 }
455
456 linkResources(resources);
457 postLink();
458
459 return angle::Result::Continue;
460 };
461
462 if (mRenderer->hasNativeParallelCompile())
463 {
464 mFunctions->linkProgram(mProgramID);
465 return std::make_unique<LinkEventNativeParallel>(postLinkImplTask, mFunctions, mProgramID);
466 }
467 else if (workerPool->isAsync() &&
468 (!mFeatures.dontRelinkProgramsInParallel.enabled || !mLinkedInParallel))
469 {
470 mLinkedInParallel = true;
471 return std::make_unique<LinkEventGL>(workerPool, linkTask, postLinkImplTask);
472 }
473 else
474 {
475 return std::make_unique<LinkEventDone>(postLinkImplTask(true, std::string()));
476 }
477 }
478
validate(const gl::Caps &,gl::InfoLog *)479 GLboolean ProgramGL::validate(const gl::Caps & /*caps*/, gl::InfoLog * /*infoLog*/)
480 {
481 // TODO(jmadill): implement validate
482 return true;
483 }
484
setUniform1fv(GLint location,GLsizei count,const GLfloat * v)485 void ProgramGL::setUniform1fv(GLint location, GLsizei count, const GLfloat *v)
486 {
487 if (mFunctions->programUniform1fv != nullptr)
488 {
489 mFunctions->programUniform1fv(mProgramID, uniLoc(location), count, v);
490 }
491 else
492 {
493 mStateManager->useProgram(mProgramID);
494 mFunctions->uniform1fv(uniLoc(location), count, v);
495 }
496 }
497
setUniform2fv(GLint location,GLsizei count,const GLfloat * v)498 void ProgramGL::setUniform2fv(GLint location, GLsizei count, const GLfloat *v)
499 {
500 if (mFunctions->programUniform2fv != nullptr)
501 {
502 mFunctions->programUniform2fv(mProgramID, uniLoc(location), count, v);
503 }
504 else
505 {
506 mStateManager->useProgram(mProgramID);
507 mFunctions->uniform2fv(uniLoc(location), count, v);
508 }
509 }
510
setUniform3fv(GLint location,GLsizei count,const GLfloat * v)511 void ProgramGL::setUniform3fv(GLint location, GLsizei count, const GLfloat *v)
512 {
513 if (mFunctions->programUniform3fv != nullptr)
514 {
515 mFunctions->programUniform3fv(mProgramID, uniLoc(location), count, v);
516 }
517 else
518 {
519 mStateManager->useProgram(mProgramID);
520 mFunctions->uniform3fv(uniLoc(location), count, v);
521 }
522 }
523
setUniform4fv(GLint location,GLsizei count,const GLfloat * v)524 void ProgramGL::setUniform4fv(GLint location, GLsizei count, const GLfloat *v)
525 {
526 if (mFunctions->programUniform4fv != nullptr)
527 {
528 mFunctions->programUniform4fv(mProgramID, uniLoc(location), count, v);
529 }
530 else
531 {
532 mStateManager->useProgram(mProgramID);
533 mFunctions->uniform4fv(uniLoc(location), count, v);
534 }
535 }
536
setUniform1iv(GLint location,GLsizei count,const GLint * v)537 void ProgramGL::setUniform1iv(GLint location, GLsizei count, const GLint *v)
538 {
539 if (mFunctions->programUniform1iv != nullptr)
540 {
541 mFunctions->programUniform1iv(mProgramID, uniLoc(location), count, v);
542 }
543 else
544 {
545 mStateManager->useProgram(mProgramID);
546 mFunctions->uniform1iv(uniLoc(location), count, v);
547 }
548 }
549
setUniform2iv(GLint location,GLsizei count,const GLint * v)550 void ProgramGL::setUniform2iv(GLint location, GLsizei count, const GLint *v)
551 {
552 if (mFunctions->programUniform2iv != nullptr)
553 {
554 mFunctions->programUniform2iv(mProgramID, uniLoc(location), count, v);
555 }
556 else
557 {
558 mStateManager->useProgram(mProgramID);
559 mFunctions->uniform2iv(uniLoc(location), count, v);
560 }
561 }
562
setUniform3iv(GLint location,GLsizei count,const GLint * v)563 void ProgramGL::setUniform3iv(GLint location, GLsizei count, const GLint *v)
564 {
565 if (mFunctions->programUniform3iv != nullptr)
566 {
567 mFunctions->programUniform3iv(mProgramID, uniLoc(location), count, v);
568 }
569 else
570 {
571 mStateManager->useProgram(mProgramID);
572 mFunctions->uniform3iv(uniLoc(location), count, v);
573 }
574 }
575
setUniform4iv(GLint location,GLsizei count,const GLint * v)576 void ProgramGL::setUniform4iv(GLint location, GLsizei count, const GLint *v)
577 {
578 if (mFunctions->programUniform4iv != nullptr)
579 {
580 mFunctions->programUniform4iv(mProgramID, uniLoc(location), count, v);
581 }
582 else
583 {
584 mStateManager->useProgram(mProgramID);
585 mFunctions->uniform4iv(uniLoc(location), count, v);
586 }
587 }
588
setUniform1uiv(GLint location,GLsizei count,const GLuint * v)589 void ProgramGL::setUniform1uiv(GLint location, GLsizei count, const GLuint *v)
590 {
591 if (mFunctions->programUniform1uiv != nullptr)
592 {
593 mFunctions->programUniform1uiv(mProgramID, uniLoc(location), count, v);
594 }
595 else
596 {
597 mStateManager->useProgram(mProgramID);
598 mFunctions->uniform1uiv(uniLoc(location), count, v);
599 }
600 }
601
setUniform2uiv(GLint location,GLsizei count,const GLuint * v)602 void ProgramGL::setUniform2uiv(GLint location, GLsizei count, const GLuint *v)
603 {
604 if (mFunctions->programUniform2uiv != nullptr)
605 {
606 mFunctions->programUniform2uiv(mProgramID, uniLoc(location), count, v);
607 }
608 else
609 {
610 mStateManager->useProgram(mProgramID);
611 mFunctions->uniform2uiv(uniLoc(location), count, v);
612 }
613 }
614
setUniform3uiv(GLint location,GLsizei count,const GLuint * v)615 void ProgramGL::setUniform3uiv(GLint location, GLsizei count, const GLuint *v)
616 {
617 if (mFunctions->programUniform3uiv != nullptr)
618 {
619 mFunctions->programUniform3uiv(mProgramID, uniLoc(location), count, v);
620 }
621 else
622 {
623 mStateManager->useProgram(mProgramID);
624 mFunctions->uniform3uiv(uniLoc(location), count, v);
625 }
626 }
627
setUniform4uiv(GLint location,GLsizei count,const GLuint * v)628 void ProgramGL::setUniform4uiv(GLint location, GLsizei count, const GLuint *v)
629 {
630 if (mFunctions->programUniform4uiv != nullptr)
631 {
632 mFunctions->programUniform4uiv(mProgramID, uniLoc(location), count, v);
633 }
634 else
635 {
636 mStateManager->useProgram(mProgramID);
637 mFunctions->uniform4uiv(uniLoc(location), count, v);
638 }
639 }
640
setUniformMatrix2fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)641 void ProgramGL::setUniformMatrix2fv(GLint location,
642 GLsizei count,
643 GLboolean transpose,
644 const GLfloat *value)
645 {
646 if (mFunctions->programUniformMatrix2fv != nullptr)
647 {
648 mFunctions->programUniformMatrix2fv(mProgramID, uniLoc(location), count, transpose, value);
649 }
650 else
651 {
652 mStateManager->useProgram(mProgramID);
653 mFunctions->uniformMatrix2fv(uniLoc(location), count, transpose, value);
654 }
655 }
656
setUniformMatrix3fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)657 void ProgramGL::setUniformMatrix3fv(GLint location,
658 GLsizei count,
659 GLboolean transpose,
660 const GLfloat *value)
661 {
662 if (mFunctions->programUniformMatrix3fv != nullptr)
663 {
664 mFunctions->programUniformMatrix3fv(mProgramID, uniLoc(location), count, transpose, value);
665 }
666 else
667 {
668 mStateManager->useProgram(mProgramID);
669 mFunctions->uniformMatrix3fv(uniLoc(location), count, transpose, value);
670 }
671 }
672
setUniformMatrix4fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)673 void ProgramGL::setUniformMatrix4fv(GLint location,
674 GLsizei count,
675 GLboolean transpose,
676 const GLfloat *value)
677 {
678 if (mFunctions->programUniformMatrix4fv != nullptr)
679 {
680 mFunctions->programUniformMatrix4fv(mProgramID, uniLoc(location), count, transpose, value);
681 }
682 else
683 {
684 mStateManager->useProgram(mProgramID);
685 mFunctions->uniformMatrix4fv(uniLoc(location), count, transpose, value);
686 }
687 }
688
setUniformMatrix2x3fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)689 void ProgramGL::setUniformMatrix2x3fv(GLint location,
690 GLsizei count,
691 GLboolean transpose,
692 const GLfloat *value)
693 {
694 if (mFunctions->programUniformMatrix2x3fv != nullptr)
695 {
696 mFunctions->programUniformMatrix2x3fv(mProgramID, uniLoc(location), count, transpose,
697 value);
698 }
699 else
700 {
701 mStateManager->useProgram(mProgramID);
702 mFunctions->uniformMatrix2x3fv(uniLoc(location), count, transpose, value);
703 }
704 }
705
setUniformMatrix3x2fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)706 void ProgramGL::setUniformMatrix3x2fv(GLint location,
707 GLsizei count,
708 GLboolean transpose,
709 const GLfloat *value)
710 {
711 if (mFunctions->programUniformMatrix3x2fv != nullptr)
712 {
713 mFunctions->programUniformMatrix3x2fv(mProgramID, uniLoc(location), count, transpose,
714 value);
715 }
716 else
717 {
718 mStateManager->useProgram(mProgramID);
719 mFunctions->uniformMatrix3x2fv(uniLoc(location), count, transpose, value);
720 }
721 }
722
setUniformMatrix2x4fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)723 void ProgramGL::setUniformMatrix2x4fv(GLint location,
724 GLsizei count,
725 GLboolean transpose,
726 const GLfloat *value)
727 {
728 if (mFunctions->programUniformMatrix2x4fv != nullptr)
729 {
730 mFunctions->programUniformMatrix2x4fv(mProgramID, uniLoc(location), count, transpose,
731 value);
732 }
733 else
734 {
735 mStateManager->useProgram(mProgramID);
736 mFunctions->uniformMatrix2x4fv(uniLoc(location), count, transpose, value);
737 }
738 }
739
setUniformMatrix4x2fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)740 void ProgramGL::setUniformMatrix4x2fv(GLint location,
741 GLsizei count,
742 GLboolean transpose,
743 const GLfloat *value)
744 {
745 if (mFunctions->programUniformMatrix4x2fv != nullptr)
746 {
747 mFunctions->programUniformMatrix4x2fv(mProgramID, uniLoc(location), count, transpose,
748 value);
749 }
750 else
751 {
752 mStateManager->useProgram(mProgramID);
753 mFunctions->uniformMatrix4x2fv(uniLoc(location), count, transpose, value);
754 }
755 }
756
setUniformMatrix3x4fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)757 void ProgramGL::setUniformMatrix3x4fv(GLint location,
758 GLsizei count,
759 GLboolean transpose,
760 const GLfloat *value)
761 {
762 if (mFunctions->programUniformMatrix3x4fv != nullptr)
763 {
764 mFunctions->programUniformMatrix3x4fv(mProgramID, uniLoc(location), count, transpose,
765 value);
766 }
767 else
768 {
769 mStateManager->useProgram(mProgramID);
770 mFunctions->uniformMatrix3x4fv(uniLoc(location), count, transpose, value);
771 }
772 }
773
setUniformMatrix4x3fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)774 void ProgramGL::setUniformMatrix4x3fv(GLint location,
775 GLsizei count,
776 GLboolean transpose,
777 const GLfloat *value)
778 {
779 if (mFunctions->programUniformMatrix4x3fv != nullptr)
780 {
781 mFunctions->programUniformMatrix4x3fv(mProgramID, uniLoc(location), count, transpose,
782 value);
783 }
784 else
785 {
786 mStateManager->useProgram(mProgramID);
787 mFunctions->uniformMatrix4x3fv(uniLoc(location), count, transpose, value);
788 }
789 }
790
setUniformBlockBinding(GLuint uniformBlockIndex,GLuint uniformBlockBinding)791 void ProgramGL::setUniformBlockBinding(GLuint uniformBlockIndex, GLuint uniformBlockBinding)
792 {
793 // Lazy init
794 if (mUniformBlockRealLocationMap.empty())
795 {
796 mUniformBlockRealLocationMap.reserve(mState.getUniformBlocks().size());
797 for (const gl::InterfaceBlock &uniformBlock : mState.getUniformBlocks())
798 {
799 const std::string &mappedNameWithIndex = uniformBlock.mappedNameWithArrayIndex();
800 GLuint blockIndex =
801 mFunctions->getUniformBlockIndex(mProgramID, mappedNameWithIndex.c_str());
802 mUniformBlockRealLocationMap.push_back(blockIndex);
803 }
804 }
805
806 GLuint realBlockIndex = mUniformBlockRealLocationMap[uniformBlockIndex];
807 if (realBlockIndex != GL_INVALID_INDEX)
808 {
809 mFunctions->uniformBlockBinding(mProgramID, realBlockIndex, uniformBlockBinding);
810 }
811 }
812
getUniformBlockSize(const std::string &,const std::string & blockMappedName,size_t * sizeOut) const813 bool ProgramGL::getUniformBlockSize(const std::string & /* blockName */,
814 const std::string &blockMappedName,
815 size_t *sizeOut) const
816 {
817 ASSERT(mProgramID != 0u);
818
819 GLuint blockIndex = mFunctions->getUniformBlockIndex(mProgramID, blockMappedName.c_str());
820 if (blockIndex == GL_INVALID_INDEX)
821 {
822 *sizeOut = 0;
823 return false;
824 }
825
826 GLint dataSize = 0;
827 mFunctions->getActiveUniformBlockiv(mProgramID, blockIndex, GL_UNIFORM_BLOCK_DATA_SIZE,
828 &dataSize);
829 *sizeOut = static_cast<size_t>(dataSize);
830 return true;
831 }
832
getUniformBlockMemberInfo(const std::string &,const std::string & memberUniformMappedName,sh::BlockMemberInfo * memberInfoOut) const833 bool ProgramGL::getUniformBlockMemberInfo(const std::string & /* memberUniformName */,
834 const std::string &memberUniformMappedName,
835 sh::BlockMemberInfo *memberInfoOut) const
836 {
837 GLuint uniformIndex;
838 const GLchar *memberNameGLStr = memberUniformMappedName.c_str();
839 mFunctions->getUniformIndices(mProgramID, 1, &memberNameGLStr, &uniformIndex);
840
841 if (uniformIndex == GL_INVALID_INDEX)
842 {
843 *memberInfoOut = sh::kDefaultBlockMemberInfo;
844 return false;
845 }
846
847 mFunctions->getActiveUniformsiv(mProgramID, 1, &uniformIndex, GL_UNIFORM_OFFSET,
848 &memberInfoOut->offset);
849 mFunctions->getActiveUniformsiv(mProgramID, 1, &uniformIndex, GL_UNIFORM_ARRAY_STRIDE,
850 &memberInfoOut->arrayStride);
851 mFunctions->getActiveUniformsiv(mProgramID, 1, &uniformIndex, GL_UNIFORM_MATRIX_STRIDE,
852 &memberInfoOut->matrixStride);
853
854 // TODO(jmadill): possibly determine this at the gl::Program level.
855 GLint isRowMajorMatrix = 0;
856 mFunctions->getActiveUniformsiv(mProgramID, 1, &uniformIndex, GL_UNIFORM_IS_ROW_MAJOR,
857 &isRowMajorMatrix);
858 memberInfoOut->isRowMajorMatrix = gl::ConvertToBool(isRowMajorMatrix);
859 return true;
860 }
861
getShaderStorageBlockMemberInfo(const std::string &,const std::string & memberUniformMappedName,sh::BlockMemberInfo * memberInfoOut) const862 bool ProgramGL::getShaderStorageBlockMemberInfo(const std::string & /* memberName */,
863 const std::string &memberUniformMappedName,
864 sh::BlockMemberInfo *memberInfoOut) const
865 {
866 const GLchar *memberNameGLStr = memberUniformMappedName.c_str();
867 GLuint index =
868 mFunctions->getProgramResourceIndex(mProgramID, GL_BUFFER_VARIABLE, memberNameGLStr);
869
870 if (index == GL_INVALID_INDEX)
871 {
872 *memberInfoOut = sh::kDefaultBlockMemberInfo;
873 return false;
874 }
875
876 constexpr int kPropCount = 5;
877 std::array<GLenum, kPropCount> props = {
878 {GL_ARRAY_STRIDE, GL_IS_ROW_MAJOR, GL_MATRIX_STRIDE, GL_OFFSET, GL_TOP_LEVEL_ARRAY_STRIDE}};
879 std::array<GLint, kPropCount> params;
880 GLsizei length;
881 mFunctions->getProgramResourceiv(mProgramID, GL_BUFFER_VARIABLE, index, kPropCount,
882 props.data(), kPropCount, &length, params.data());
883 ASSERT(kPropCount == length);
884 memberInfoOut->arrayStride = params[0];
885 memberInfoOut->isRowMajorMatrix = params[1] != 0;
886 memberInfoOut->matrixStride = params[2];
887 memberInfoOut->offset = params[3];
888 memberInfoOut->topLevelArrayStride = params[4];
889
890 return true;
891 }
892
getShaderStorageBlockSize(const std::string & name,const std::string & mappedName,size_t * sizeOut) const893 bool ProgramGL::getShaderStorageBlockSize(const std::string &name,
894 const std::string &mappedName,
895 size_t *sizeOut) const
896 {
897 const GLchar *nameGLStr = mappedName.c_str();
898 GLuint index =
899 mFunctions->getProgramResourceIndex(mProgramID, GL_SHADER_STORAGE_BLOCK, nameGLStr);
900
901 if (index == GL_INVALID_INDEX)
902 {
903 *sizeOut = 0;
904 return false;
905 }
906
907 GLenum prop = GL_BUFFER_DATA_SIZE;
908 GLsizei length = 0;
909 GLint dataSize = 0;
910 mFunctions->getProgramResourceiv(mProgramID, GL_SHADER_STORAGE_BLOCK, index, 1, &prop, 1,
911 &length, &dataSize);
912 *sizeOut = static_cast<size_t>(dataSize);
913 return true;
914 }
915
getAtomicCounterBufferSizeMap(std::map<int,unsigned int> * sizeMapOut) const916 void ProgramGL::getAtomicCounterBufferSizeMap(std::map<int, unsigned int> *sizeMapOut) const
917 {
918 if (mFunctions->getProgramInterfaceiv == nullptr)
919 {
920 return;
921 }
922
923 int resourceCount = 0;
924 mFunctions->getProgramInterfaceiv(mProgramID, GL_ATOMIC_COUNTER_BUFFER, GL_ACTIVE_RESOURCES,
925 &resourceCount);
926
927 for (int index = 0; index < resourceCount; index++)
928 {
929 constexpr int kPropCount = 2;
930 std::array<GLenum, kPropCount> props = {{GL_BUFFER_BINDING, GL_BUFFER_DATA_SIZE}};
931 std::array<GLint, kPropCount> params;
932 GLsizei length;
933 mFunctions->getProgramResourceiv(mProgramID, GL_ATOMIC_COUNTER_BUFFER, index, kPropCount,
934 props.data(), kPropCount, &length, params.data());
935 ASSERT(kPropCount == length);
936 int bufferBinding = params[0];
937 unsigned int bufferDataSize = params[1];
938 sizeMapOut->insert(std::pair<int, unsigned int>(bufferBinding, bufferDataSize));
939 }
940 }
941
preLink()942 void ProgramGL::preLink()
943 {
944 // Reset the program state
945 mUniformRealLocationMap.clear();
946 mUniformBlockRealLocationMap.clear();
947
948 mMultiviewBaseViewLayerIndexUniformLocation = -1;
949 }
950
checkLinkStatus(gl::InfoLog & infoLog)951 bool ProgramGL::checkLinkStatus(gl::InfoLog &infoLog)
952 {
953 GLint linkStatus = GL_FALSE;
954 mFunctions->getProgramiv(mProgramID, GL_LINK_STATUS, &linkStatus);
955 if (linkStatus == GL_FALSE)
956 {
957 // Linking or program binary loading failed, put the error into the info log.
958 GLint infoLogLength = 0;
959 mFunctions->getProgramiv(mProgramID, GL_INFO_LOG_LENGTH, &infoLogLength);
960
961 // Info log length includes the null terminator, so 1 means that the info log is an empty
962 // string.
963 if (infoLogLength > 1)
964 {
965 std::vector<char> buf(infoLogLength);
966 mFunctions->getProgramInfoLog(mProgramID, infoLogLength, nullptr, &buf[0]);
967
968 infoLog << buf.data();
969
970 WARN() << "Program link or binary loading failed: " << buf.data();
971 }
972 else
973 {
974 WARN() << "Program link or binary loading failed with no info log.";
975 }
976
977 // This may happen under normal circumstances if we're loading program binaries and the
978 // driver or hardware has changed.
979 ASSERT(mProgramID != 0);
980 return false;
981 }
982
983 return true;
984 }
985
postLink()986 void ProgramGL::postLink()
987 {
988 // Query the uniform information
989 ASSERT(mUniformRealLocationMap.empty());
990 const auto &uniformLocations = mState.getUniformLocations();
991 const auto &uniforms = mState.getUniforms();
992 mUniformRealLocationMap.resize(uniformLocations.size(), GL_INVALID_INDEX);
993 for (size_t uniformLocation = 0; uniformLocation < uniformLocations.size(); uniformLocation++)
994 {
995 const auto &entry = uniformLocations[uniformLocation];
996 if (!entry.used())
997 {
998 continue;
999 }
1000
1001 // From the GLES 3.0.5 spec:
1002 // "Locations for sequential array indices are not required to be sequential."
1003 const gl::LinkedUniform &uniform = uniforms[entry.index];
1004 std::stringstream fullNameStr;
1005 if (uniform.isArray())
1006 {
1007 ASSERT(angle::EndsWith(uniform.mappedName, "[0]"));
1008 fullNameStr << uniform.mappedName.substr(0, uniform.mappedName.length() - 3);
1009 fullNameStr << "[" << entry.arrayIndex << "]";
1010 }
1011 else
1012 {
1013 fullNameStr << uniform.mappedName;
1014 }
1015 const std::string &fullName = fullNameStr.str();
1016
1017 GLint realLocation = mFunctions->getUniformLocation(mProgramID, fullName.c_str());
1018 mUniformRealLocationMap[uniformLocation] = realLocation;
1019 }
1020
1021 if (mState.usesMultiview())
1022 {
1023 mMultiviewBaseViewLayerIndexUniformLocation =
1024 mFunctions->getUniformLocation(mProgramID, "multiviewBaseViewLayerIndex");
1025 ASSERT(mMultiviewBaseViewLayerIndexUniformLocation != -1);
1026 }
1027 }
1028
enableSideBySideRenderingPath() const1029 void ProgramGL::enableSideBySideRenderingPath() const
1030 {
1031 ASSERT(mState.usesMultiview());
1032 ASSERT(mMultiviewBaseViewLayerIndexUniformLocation != -1);
1033
1034 ASSERT(mFunctions->programUniform1i != nullptr);
1035 mFunctions->programUniform1i(mProgramID, mMultiviewBaseViewLayerIndexUniformLocation, -1);
1036 }
1037
enableLayeredRenderingPath(int baseViewIndex) const1038 void ProgramGL::enableLayeredRenderingPath(int baseViewIndex) const
1039 {
1040 ASSERT(mState.usesMultiview());
1041 ASSERT(mMultiviewBaseViewLayerIndexUniformLocation != -1);
1042
1043 ASSERT(mFunctions->programUniform1i != nullptr);
1044 mFunctions->programUniform1i(mProgramID, mMultiviewBaseViewLayerIndexUniformLocation,
1045 baseViewIndex);
1046 }
1047
getUniformfv(const gl::Context * context,GLint location,GLfloat * params) const1048 void ProgramGL::getUniformfv(const gl::Context *context, GLint location, GLfloat *params) const
1049 {
1050 mFunctions->getUniformfv(mProgramID, uniLoc(location), params);
1051 }
1052
getUniformiv(const gl::Context * context,GLint location,GLint * params) const1053 void ProgramGL::getUniformiv(const gl::Context *context, GLint location, GLint *params) const
1054 {
1055 mFunctions->getUniformiv(mProgramID, uniLoc(location), params);
1056 }
1057
getUniformuiv(const gl::Context * context,GLint location,GLuint * params) const1058 void ProgramGL::getUniformuiv(const gl::Context *context, GLint location, GLuint *params) const
1059 {
1060 mFunctions->getUniformuiv(mProgramID, uniLoc(location), params);
1061 }
1062
markUnusedUniformLocations(std::vector<gl::VariableLocation> * uniformLocations,std::vector<gl::SamplerBinding> * samplerBindings,std::vector<gl::ImageBinding> * imageBindings)1063 void ProgramGL::markUnusedUniformLocations(std::vector<gl::VariableLocation> *uniformLocations,
1064 std::vector<gl::SamplerBinding> *samplerBindings,
1065 std::vector<gl::ImageBinding> *imageBindings)
1066 {
1067 GLint maxLocation = static_cast<GLint>(uniformLocations->size());
1068 for (GLint location = 0; location < maxLocation; ++location)
1069 {
1070 if (uniLoc(location) == -1)
1071 {
1072 auto &locationRef = (*uniformLocations)[location];
1073 if (mState.isSamplerUniformIndex(locationRef.index))
1074 {
1075 GLuint samplerIndex = mState.getSamplerIndexFromUniformIndex(locationRef.index);
1076 (*samplerBindings)[samplerIndex].unreferenced = true;
1077 }
1078 else if (mState.isImageUniformIndex(locationRef.index))
1079 {
1080 GLuint imageIndex = mState.getImageIndexFromUniformIndex(locationRef.index);
1081 (*imageBindings)[imageIndex].unreferenced = true;
1082 }
1083 // If the location has been previously bound by a glBindUniformLocation call, it should
1084 // be marked as ignored. Otherwise it's unused.
1085 if (mState.getUniformLocationBindings().getBindingByLocation(location) != -1)
1086 {
1087 locationRef.markIgnored();
1088 }
1089 else
1090 {
1091 locationRef.markUnused();
1092 }
1093 }
1094 }
1095 }
1096
linkResources(const gl::ProgramLinkedResources & resources)1097 void ProgramGL::linkResources(const gl::ProgramLinkedResources &resources)
1098 {
1099 // Gather interface block info.
1100 auto getUniformBlockSize = [this](const std::string &name, const std::string &mappedName,
1101 size_t *sizeOut) {
1102 return this->getUniformBlockSize(name, mappedName, sizeOut);
1103 };
1104
1105 auto getUniformBlockMemberInfo = [this](const std::string &name, const std::string &mappedName,
1106 sh::BlockMemberInfo *infoOut) {
1107 return this->getUniformBlockMemberInfo(name, mappedName, infoOut);
1108 };
1109
1110 resources.uniformBlockLinker.linkBlocks(getUniformBlockSize, getUniformBlockMemberInfo);
1111
1112 auto getShaderStorageBlockSize = [this](const std::string &name, const std::string &mappedName,
1113 size_t *sizeOut) {
1114 return this->getShaderStorageBlockSize(name, mappedName, sizeOut);
1115 };
1116
1117 auto getShaderStorageBlockMemberInfo = [this](const std::string &name,
1118 const std::string &mappedName,
1119 sh::BlockMemberInfo *infoOut) {
1120 return this->getShaderStorageBlockMemberInfo(name, mappedName, infoOut);
1121 };
1122 resources.shaderStorageBlockLinker.linkBlocks(getShaderStorageBlockSize,
1123 getShaderStorageBlockMemberInfo);
1124
1125 // Gather atomic counter buffer info.
1126 std::map<int, unsigned int> sizeMap;
1127 getAtomicCounterBufferSizeMap(&sizeMap);
1128 resources.atomicCounterBufferLinker.link(sizeMap);
1129 }
1130
syncState(const gl::Context * context,const gl::Program::DirtyBits & dirtyBits)1131 angle::Result ProgramGL::syncState(const gl::Context *context,
1132 const gl::Program::DirtyBits &dirtyBits)
1133 {
1134 for (size_t dirtyBit : dirtyBits)
1135 {
1136 ASSERT(dirtyBit <= gl::Program::DIRTY_BIT_UNIFORM_BLOCK_BINDING_MAX);
1137 GLuint binding = static_cast<GLuint>(dirtyBit);
1138 setUniformBlockBinding(binding, mState.getUniformBlockBinding(binding));
1139 }
1140 return angle::Result::Continue;
1141 }
1142 } // namespace rx
1143