Don't show supervised user as "already on this device" while they're being imported.
[chromium-blink-merge.git] / gpu / command_buffer / service / program_manager.cc
blob896669fca3b294e8ac32d95eecb8d25cd64234c8
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "gpu/command_buffer/service/program_manager.h"
7 #include <algorithm>
8 #include <set>
9 #include <utility>
10 #include <vector>
12 #include "base/basictypes.h"
13 #include "base/command_line.h"
14 #include "base/logging.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/metrics/histogram.h"
17 #include "base/numerics/safe_math.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_util.h"
20 #include "base/time/time.h"
21 #include "gpu/command_buffer/common/gles2_cmd_format.h"
22 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
23 #include "gpu/command_buffer/service/gles2_cmd_decoder.h"
24 #include "gpu/command_buffer/service/gpu_switches.h"
25 #include "gpu/command_buffer/service/program_cache.h"
26 #include "gpu/command_buffer/service/shader_manager.h"
27 #include "third_party/re2/re2/re2.h"
29 using base::TimeDelta;
30 using base::TimeTicks;
32 namespace gpu {
33 namespace gles2 {
35 namespace {
37 int ShaderTypeToIndex(GLenum shader_type) {
38 switch (shader_type) {
39 case GL_VERTEX_SHADER:
40 return 0;
41 case GL_FRAGMENT_SHADER:
42 return 1;
43 default:
44 NOTREACHED();
45 return 0;
49 // Given a name like "foo.bar[123].moo[456]" sets new_name to "foo.bar[123].moo"
50 // and sets element_index to 456. returns false if element expression was not a
51 // whole decimal number. For example: "foo[1b2]"
52 bool GetUniformNameSansElement(
53 const std::string& name, int* element_index, std::string* new_name) {
54 DCHECK(element_index);
55 DCHECK(new_name);
56 if (name.size() < 3 || name[name.size() - 1] != ']') {
57 *element_index = 0;
58 *new_name = name;
59 return true;
62 // Look for an array specification.
63 size_t open_pos = name.find_last_of('[');
64 if (open_pos == std::string::npos ||
65 open_pos >= name.size() - 2) {
66 return false;
69 base::CheckedNumeric<GLint> index = 0;
70 size_t last = name.size() - 1;
71 for (size_t pos = open_pos + 1; pos < last; ++pos) {
72 int8 digit = name[pos] - '0';
73 if (digit < 0 || digit > 9) {
74 return false;
76 index = index * 10 + digit;
78 if (!index.IsValid()) {
79 return false;
82 *element_index = index.ValueOrDie();
83 *new_name = name.substr(0, open_pos);
84 return true;
87 bool IsBuiltInFragmentVarying(const std::string& name) {
88 // Built-in variables for fragment shaders.
89 const char* kBuiltInVaryings[] = {
90 "gl_FragCoord",
91 "gl_FrontFacing",
92 "gl_PointCoord"
94 for (size_t ii = 0; ii < arraysize(kBuiltInVaryings); ++ii) {
95 if (name == kBuiltInVaryings[ii])
96 return true;
98 return false;
101 bool IsBuiltInInvariant(
102 const VaryingMap& varyings, const std::string& name) {
103 VaryingMap::const_iterator hit = varyings.find(name);
104 if (hit == varyings.end())
105 return false;
106 return hit->second.isInvariant;
109 uint32 ComputeOffset(const void* start, const void* position) {
110 return static_cast<const uint8*>(position) -
111 static_cast<const uint8*>(start);
114 } // anonymous namespace.
116 Program::UniformInfo::UniformInfo()
117 : size(0),
118 type(GL_NONE),
119 fake_location_base(0),
120 is_array(false) {
123 Program::UniformInfo::UniformInfo(GLsizei _size,
124 GLenum _type,
125 int _fake_location_base,
126 const std::string& _name)
127 : size(_size),
128 type(_type),
129 accepts_api_type(0),
130 fake_location_base(_fake_location_base),
131 is_array(false),
132 name(_name) {
133 switch (type) {
134 case GL_INT:
135 accepts_api_type = kUniform1i;
136 break;
137 case GL_INT_VEC2:
138 accepts_api_type = kUniform2i;
139 break;
140 case GL_INT_VEC3:
141 accepts_api_type = kUniform3i;
142 break;
143 case GL_INT_VEC4:
144 accepts_api_type = kUniform4i;
145 break;
147 case GL_BOOL:
148 accepts_api_type = kUniform1i | kUniform1f;
149 break;
150 case GL_BOOL_VEC2:
151 accepts_api_type = kUniform2i | kUniform2f;
152 break;
153 case GL_BOOL_VEC3:
154 accepts_api_type = kUniform3i | kUniform3f;
155 break;
156 case GL_BOOL_VEC4:
157 accepts_api_type = kUniform4i | kUniform4f;
158 break;
160 case GL_FLOAT:
161 accepts_api_type = kUniform1f;
162 break;
163 case GL_FLOAT_VEC2:
164 accepts_api_type = kUniform2f;
165 break;
166 case GL_FLOAT_VEC3:
167 accepts_api_type = kUniform3f;
168 break;
169 case GL_FLOAT_VEC4:
170 accepts_api_type = kUniform4f;
171 break;
173 case GL_FLOAT_MAT2:
174 accepts_api_type = kUniformMatrix2f;
175 break;
176 case GL_FLOAT_MAT3:
177 accepts_api_type = kUniformMatrix3f;
178 break;
179 case GL_FLOAT_MAT4:
180 accepts_api_type = kUniformMatrix4f;
181 break;
183 case GL_SAMPLER_2D:
184 case GL_SAMPLER_2D_RECT_ARB:
185 case GL_SAMPLER_CUBE:
186 case GL_SAMPLER_3D_OES:
187 case GL_SAMPLER_EXTERNAL_OES:
188 accepts_api_type = kUniform1i;
189 break;
190 default:
191 NOTREACHED() << "Unhandled UniformInfo type " << type;
192 break;
196 Program::UniformInfo::~UniformInfo() {}
198 bool ProgramManager::IsInvalidPrefix(const char* name, size_t length) {
199 static const char kInvalidPrefix[] = { 'g', 'l', '_' };
200 return (length >= sizeof(kInvalidPrefix) &&
201 memcmp(name, kInvalidPrefix, sizeof(kInvalidPrefix)) == 0);
204 Program::Program(ProgramManager* manager, GLuint service_id)
205 : manager_(manager),
206 use_count_(0),
207 max_attrib_name_length_(0),
208 max_uniform_name_length_(0),
209 service_id_(service_id),
210 deleted_(false),
211 valid_(false),
212 link_status_(false),
213 uniforms_cleared_(false),
214 num_uniforms_(0),
215 transform_feedback_buffer_mode_(GL_NONE) {
216 manager_->StartTracking(this);
219 void Program::Reset() {
220 valid_ = false;
221 link_status_ = false;
222 num_uniforms_ = 0;
223 max_uniform_name_length_ = 0;
224 max_attrib_name_length_ = 0;
225 attrib_infos_.clear();
226 uniform_infos_.clear();
227 sampler_indices_.clear();
228 attrib_location_to_index_map_.clear();
231 std::string Program::ProcessLogInfo(
232 const std::string& log) {
233 std::string output;
234 re2::StringPiece input(log);
235 std::string prior_log;
236 std::string hashed_name;
237 while (RE2::Consume(&input,
238 "(.*?)(webgl_[0123456789abcdefABCDEF]+)",
239 &prior_log,
240 &hashed_name)) {
241 output += prior_log;
243 const std::string* original_name =
244 GetOriginalNameFromHashedName(hashed_name);
245 if (original_name)
246 output += *original_name;
247 else
248 output += hashed_name;
251 return output + input.as_string();
254 void Program::UpdateLogInfo() {
255 GLint max_len = 0;
256 glGetProgramiv(service_id_, GL_INFO_LOG_LENGTH, &max_len);
257 if (max_len == 0) {
258 set_log_info(NULL);
259 return;
261 scoped_ptr<char[]> temp(new char[max_len]);
262 GLint len = 0;
263 glGetProgramInfoLog(service_id_, max_len, &len, temp.get());
264 DCHECK(max_len == 0 || len < max_len);
265 DCHECK(len == 0 || temp[len] == '\0');
266 std::string log(temp.get(), len);
267 set_log_info(ProcessLogInfo(log).c_str());
270 void Program::ClearUniforms(
271 std::vector<uint8>* zero_buffer) {
272 DCHECK(zero_buffer);
273 if (uniforms_cleared_) {
274 return;
276 uniforms_cleared_ = true;
277 for (size_t ii = 0; ii < uniform_infos_.size(); ++ii) {
278 const UniformInfo& uniform_info = uniform_infos_[ii];
279 if (!uniform_info.IsValid()) {
280 continue;
282 GLint location = uniform_info.element_locations[0];
283 GLsizei size = uniform_info.size;
284 uint32 unit_size =
285 GLES2Util::GetElementCountForUniformType(uniform_info.type) *
286 GLES2Util::GetElementSizeForUniformType(uniform_info.type);
287 DCHECK_LT(0u, unit_size);
288 uint32 size_needed = size * unit_size;
289 if (size_needed > zero_buffer->size()) {
290 zero_buffer->resize(size_needed, 0u);
292 const void* zero = &(*zero_buffer)[0];
293 switch (uniform_info.type) {
294 case GL_FLOAT:
295 glUniform1fv(location, size, reinterpret_cast<const GLfloat*>(zero));
296 break;
297 case GL_FLOAT_VEC2:
298 glUniform2fv(location, size, reinterpret_cast<const GLfloat*>(zero));
299 break;
300 case GL_FLOAT_VEC3:
301 glUniform3fv(location, size, reinterpret_cast<const GLfloat*>(zero));
302 break;
303 case GL_FLOAT_VEC4:
304 glUniform4fv(location, size, reinterpret_cast<const GLfloat*>(zero));
305 break;
306 case GL_INT:
307 case GL_BOOL:
308 case GL_SAMPLER_2D:
309 case GL_SAMPLER_CUBE:
310 case GL_SAMPLER_EXTERNAL_OES: // extension.
311 case GL_SAMPLER_2D_RECT_ARB: // extension.
312 glUniform1iv(location, size, reinterpret_cast<const GLint*>(zero));
313 break;
314 case GL_INT_VEC2:
315 case GL_BOOL_VEC2:
316 glUniform2iv(location, size, reinterpret_cast<const GLint*>(zero));
317 break;
318 case GL_INT_VEC3:
319 case GL_BOOL_VEC3:
320 glUniform3iv(location, size, reinterpret_cast<const GLint*>(zero));
321 break;
322 case GL_INT_VEC4:
323 case GL_BOOL_VEC4:
324 glUniform4iv(location, size, reinterpret_cast<const GLint*>(zero));
325 break;
326 case GL_FLOAT_MAT2:
327 glUniformMatrix2fv(
328 location, size, false, reinterpret_cast<const GLfloat*>(zero));
329 break;
330 case GL_FLOAT_MAT3:
331 glUniformMatrix3fv(
332 location, size, false, reinterpret_cast<const GLfloat*>(zero));
333 break;
334 case GL_FLOAT_MAT4:
335 glUniformMatrix4fv(
336 location, size, false, reinterpret_cast<const GLfloat*>(zero));
337 break;
339 // ES3 types.
340 case GL_UNSIGNED_INT:
341 glUniform1uiv(location, size, reinterpret_cast<const GLuint*>(zero));
342 break;
343 case GL_SAMPLER_3D:
344 case GL_SAMPLER_2D_SHADOW:
345 case GL_SAMPLER_2D_ARRAY:
346 case GL_SAMPLER_2D_ARRAY_SHADOW:
347 case GL_SAMPLER_CUBE_SHADOW:
348 case GL_INT_SAMPLER_2D:
349 case GL_INT_SAMPLER_3D:
350 case GL_INT_SAMPLER_CUBE:
351 case GL_INT_SAMPLER_2D_ARRAY:
352 case GL_UNSIGNED_INT_SAMPLER_2D:
353 case GL_UNSIGNED_INT_SAMPLER_3D:
354 case GL_UNSIGNED_INT_SAMPLER_CUBE:
355 case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:
356 glUniform1iv(location, size, reinterpret_cast<const GLint*>(zero));
357 break;
358 case GL_UNSIGNED_INT_VEC2:
359 glUniform2uiv(location, size, reinterpret_cast<const GLuint*>(zero));
360 break;
361 case GL_UNSIGNED_INT_VEC3:
362 glUniform3uiv(location, size, reinterpret_cast<const GLuint*>(zero));
363 break;
364 case GL_UNSIGNED_INT_VEC4:
365 glUniform4uiv(location, size, reinterpret_cast<const GLuint*>(zero));
366 break;
367 case GL_FLOAT_MAT2x3:
368 glUniformMatrix2x3fv(
369 location, size, false, reinterpret_cast<const GLfloat*>(zero));
370 break;
371 case GL_FLOAT_MAT3x2:
372 glUniformMatrix3x2fv(
373 location, size, false, reinterpret_cast<const GLfloat*>(zero));
374 break;
375 case GL_FLOAT_MAT2x4:
376 glUniformMatrix2x4fv(
377 location, size, false, reinterpret_cast<const GLfloat*>(zero));
378 break;
379 case GL_FLOAT_MAT4x2:
380 glUniformMatrix4x2fv(
381 location, size, false, reinterpret_cast<const GLfloat*>(zero));
382 break;
383 case GL_FLOAT_MAT3x4:
384 glUniformMatrix3x4fv(
385 location, size, false, reinterpret_cast<const GLfloat*>(zero));
386 break;
387 case GL_FLOAT_MAT4x3:
388 glUniformMatrix4x3fv(
389 location, size, false, reinterpret_cast<const GLfloat*>(zero));
390 break;
392 default:
393 NOTREACHED();
394 break;
399 namespace {
401 struct UniformData {
402 UniformData() : size(-1), type(GL_NONE), location(0), added(false) {
404 std::string queried_name;
405 std::string corrected_name;
406 std::string original_name;
407 GLsizei size;
408 GLenum type;
409 GLint location;
410 bool added;
413 struct UniformDataComparer {
414 bool operator()(const UniformData& lhs, const UniformData& rhs) const {
415 return lhs.queried_name < rhs.queried_name;
419 } // anonymous namespace
421 void Program::Update() {
422 Reset();
423 UpdateLogInfo();
424 link_status_ = true;
425 uniforms_cleared_ = false;
426 GLint num_attribs = 0;
427 GLint max_len = 0;
428 GLint max_location = -1;
429 glGetProgramiv(service_id_, GL_ACTIVE_ATTRIBUTES, &num_attribs);
430 glGetProgramiv(service_id_, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &max_len);
431 // TODO(gman): Should we check for error?
432 scoped_ptr<char[]> name_buffer(new char[max_len]);
433 for (GLint ii = 0; ii < num_attribs; ++ii) {
434 GLsizei length = 0;
435 GLsizei size = 0;
436 GLenum type = 0;
437 glGetActiveAttrib(
438 service_id_, ii, max_len, &length, &size, &type, name_buffer.get());
439 DCHECK(max_len == 0 || length < max_len);
440 DCHECK(length == 0 || name_buffer[length] == '\0');
441 std::string original_name;
442 GetVertexAttribData(name_buffer.get(), &original_name, &type);
443 // TODO(gman): Should we check for error?
444 GLint location = glGetAttribLocation(service_id_, name_buffer.get());
445 if (location > max_location) {
446 max_location = location;
448 attrib_infos_.push_back(VertexAttrib(1, type, original_name, location));
449 max_attrib_name_length_ = std::max(
450 max_attrib_name_length_, static_cast<GLsizei>(original_name.size()));
453 // Create attrib location to index map.
454 attrib_location_to_index_map_.resize(max_location + 1);
455 for (GLint ii = 0; ii <= max_location; ++ii) {
456 attrib_location_to_index_map_[ii] = -1;
458 for (size_t ii = 0; ii < attrib_infos_.size(); ++ii) {
459 const VertexAttrib& info = attrib_infos_[ii];
460 attrib_location_to_index_map_[info.location] = ii;
463 #if !defined(NDEBUG)
464 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
465 switches::kEnableGPUServiceLoggingGPU)) {
466 DVLOG(1) << "----: attribs for service_id: " << service_id();
467 for (size_t ii = 0; ii < attrib_infos_.size(); ++ii) {
468 const VertexAttrib& info = attrib_infos_[ii];
469 DVLOG(1) << ii << ": loc = " << info.location
470 << ", size = " << info.size
471 << ", type = " << GLES2Util::GetStringEnum(info.type)
472 << ", name = " << info.name;
475 #endif
477 max_len = 0;
478 GLint num_uniforms = 0;
479 glGetProgramiv(service_id_, GL_ACTIVE_UNIFORMS, &num_uniforms);
480 glGetProgramiv(service_id_, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max_len);
481 name_buffer.reset(new char[max_len]);
483 // Reads all the names.
484 std::vector<UniformData> uniform_data;
485 for (GLint ii = 0; ii < num_uniforms; ++ii) {
486 GLsizei length = 0;
487 UniformData data;
488 glGetActiveUniform(
489 service_id_, ii, max_len, &length,
490 &data.size, &data.type, name_buffer.get());
491 DCHECK(max_len == 0 || length < max_len);
492 DCHECK(length == 0 || name_buffer[length] == '\0');
493 data.queried_name = std::string(name_buffer.get());
494 GetCorrectedUniformData(data.queried_name, &data.corrected_name,
495 &data.original_name, &data.size, &data.type);
496 uniform_data.push_back(data);
499 // NOTE: We don't care if 2 uniforms are bound to the same location.
500 // One of them will take preference. The spec allows this, same as
501 // BindAttribLocation.
503 // The reason we don't check is if we were to fail we'd have to
504 // restore the previous program but since we've already linked successfully
505 // at this point the previous program is gone.
507 // Assigns the uniforms with bindings.
508 size_t next_available_index = 0;
509 for (size_t ii = 0; ii < uniform_data.size(); ++ii) {
510 UniformData& data = uniform_data[ii];
511 // Force builtin uniforms (gl_DepthRange) to have invalid location.
512 if (ProgramManager::IsInvalidPrefix(data.queried_name.c_str(),
513 data.queried_name.size())) {
514 data.location = -1;
515 } else {
516 data.location =
517 glGetUniformLocation(service_id_, data.queried_name.c_str());
519 // remove "[0]"
520 std::string short_name;
521 int element_index = 0;
522 bool good = GetUniformNameSansElement(data.queried_name, &element_index,
523 &short_name);
524 DCHECK(good);
525 LocationMap::const_iterator it = bind_uniform_location_map_.find(
526 short_name);
527 if (it != bind_uniform_location_map_.end()) {
528 data.added = AddUniformInfo(
529 data.size, data.type, data.location, it->second, data.corrected_name,
530 data.original_name, &next_available_index);
534 // Assigns the uniforms that were not bound.
535 for (size_t ii = 0; ii < uniform_data.size(); ++ii) {
536 const UniformData& data = uniform_data[ii];
537 if (!data.added) {
538 AddUniformInfo(
539 data.size, data.type, data.location, -1, data.corrected_name,
540 data.original_name, &next_available_index);
544 #if !defined(NDEBUG)
545 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
546 switches::kEnableGPUServiceLoggingGPU)) {
547 DVLOG(1) << "----: uniforms for service_id: " << service_id();
548 for (size_t ii = 0; ii < uniform_infos_.size(); ++ii) {
549 const UniformInfo& info = uniform_infos_[ii];
550 if (info.IsValid()) {
551 DVLOG(1) << ii << ": loc = " << info.element_locations[0]
552 << ", size = " << info.size
553 << ", type = " << GLES2Util::GetStringEnum(info.type)
554 << ", name = " << info.name;
558 #endif
560 valid_ = true;
563 void Program::ExecuteBindAttribLocationCalls() {
564 for (LocationMap::const_iterator it = bind_attrib_location_map_.begin();
565 it != bind_attrib_location_map_.end(); ++it) {
566 const std::string* mapped_name = GetAttribMappedName(it->first);
567 if (mapped_name)
568 glBindAttribLocation(service_id_, it->second, mapped_name->c_str());
572 bool Program::Link(ShaderManager* manager,
573 Program::VaryingsPackingOption varyings_packing_option,
574 const ShaderCacheCallback& shader_callback) {
575 ClearLinkStatus();
577 if (!AttachedShadersExist()) {
578 set_log_info("missing shaders");
579 return false;
582 TimeTicks before_time = TimeTicks::Now();
583 bool link = true;
584 ProgramCache* cache = manager_->program_cache_;
585 if (cache) {
586 DCHECK(!attached_shaders_[0]->last_compiled_source().empty() &&
587 !attached_shaders_[1]->last_compiled_source().empty());
588 ProgramCache::LinkedProgramStatus status = cache->GetLinkedProgramStatus(
589 attached_shaders_[0]->last_compiled_signature(),
590 attached_shaders_[1]->last_compiled_signature(),
591 &bind_attrib_location_map_,
592 transform_feedback_varyings_,
593 transform_feedback_buffer_mode_);
595 if (status == ProgramCache::LINK_SUCCEEDED) {
596 ProgramCache::ProgramLoadResult success =
597 cache->LoadLinkedProgram(service_id(),
598 attached_shaders_[0].get(),
599 attached_shaders_[1].get(),
600 &bind_attrib_location_map_,
601 transform_feedback_varyings_,
602 transform_feedback_buffer_mode_,
603 shader_callback);
604 link = success != ProgramCache::PROGRAM_LOAD_SUCCESS;
605 UMA_HISTOGRAM_BOOLEAN("GPU.ProgramCache.LoadBinarySuccess", !link);
609 if (link) {
610 CompileAttachedShaders();
612 if (!CanLink()) {
613 set_log_info("invalid shaders");
614 return false;
616 if (DetectShaderVersionMismatch()) {
617 set_log_info("Versions of linked shaders have to match.");
618 return false;
620 if (DetectAttribLocationBindingConflicts()) {
621 set_log_info("glBindAttribLocation() conflicts");
622 return false;
624 std::string conflicting_name;
625 if (DetectUniformsMismatch(&conflicting_name)) {
626 std::string info_log = "Uniforms with the same name but different "
627 "type/precision: " + conflicting_name;
628 set_log_info(ProcessLogInfo(info_log).c_str());
629 return false;
631 if (DetectVaryingsMismatch(&conflicting_name)) {
632 std::string info_log = "Varyings with the same name but different type, "
633 "or statically used varyings in fragment shader "
634 "are not declared in vertex shader: " +
635 conflicting_name;
636 set_log_info(ProcessLogInfo(info_log).c_str());
637 return false;
639 if (DetectBuiltInInvariantConflicts()) {
640 set_log_info("Invariant settings for certain built-in varyings "
641 "have to match");
642 return false;
644 if (DetectGlobalNameConflicts(&conflicting_name)) {
645 std::string info_log = "Name conflicts between an uniform and an "
646 "attribute: " + conflicting_name;
647 set_log_info(ProcessLogInfo(info_log).c_str());
648 return false;
650 if (!CheckVaryingsPacking(varyings_packing_option)) {
651 set_log_info("Varyings over maximum register limit");
652 return false;
655 ExecuteBindAttribLocationCalls();
656 before_time = TimeTicks::Now();
657 if (cache && gfx::g_driver_gl.ext.b_GL_ARB_get_program_binary) {
658 glProgramParameteri(service_id(),
659 PROGRAM_BINARY_RETRIEVABLE_HINT,
660 GL_TRUE);
662 glLinkProgram(service_id());
665 GLint success = 0;
666 glGetProgramiv(service_id(), GL_LINK_STATUS, &success);
667 if (success == GL_TRUE) {
668 Update();
669 if (link) {
670 if (cache) {
671 cache->SaveLinkedProgram(service_id(),
672 attached_shaders_[0].get(),
673 attached_shaders_[1].get(),
674 &bind_attrib_location_map_,
675 transform_feedback_varyings_,
676 transform_feedback_buffer_mode_,
677 shader_callback);
679 UMA_HISTOGRAM_CUSTOM_COUNTS(
680 "GPU.ProgramCache.BinaryCacheMissTime",
681 static_cast<base::HistogramBase::Sample>(
682 (TimeTicks::Now() - before_time).InMicroseconds()),
684 static_cast<base::HistogramBase::Sample>(
685 TimeDelta::FromSeconds(10).InMicroseconds()),
686 50);
687 } else {
688 UMA_HISTOGRAM_CUSTOM_COUNTS(
689 "GPU.ProgramCache.BinaryCacheHitTime",
690 static_cast<base::HistogramBase::Sample>(
691 (TimeTicks::Now() - before_time).InMicroseconds()),
693 static_cast<base::HistogramBase::Sample>(
694 TimeDelta::FromSeconds(1).InMicroseconds()),
695 50);
697 } else {
698 UpdateLogInfo();
700 return success == GL_TRUE;
703 void Program::Validate() {
704 if (!IsValid()) {
705 set_log_info("program not linked");
706 return;
708 glValidateProgram(service_id());
709 UpdateLogInfo();
712 GLint Program::GetUniformFakeLocation(
713 const std::string& name) const {
714 bool getting_array_location = false;
715 size_t open_pos = std::string::npos;
716 int index = 0;
717 if (!GLES2Util::ParseUniformName(
718 name, &open_pos, &index, &getting_array_location)) {
719 return -1;
721 for (GLuint ii = 0; ii < uniform_infos_.size(); ++ii) {
722 const UniformInfo& info = uniform_infos_[ii];
723 if (!info.IsValid()) {
724 continue;
726 if (info.name == name ||
727 (info.is_array &&
728 info.name.compare(0, info.name.size() - 3, name) == 0)) {
729 return info.fake_location_base;
730 } else if (getting_array_location && info.is_array) {
731 // Look for an array specification.
732 size_t open_pos_2 = info.name.find_last_of('[');
733 if (open_pos_2 == open_pos &&
734 name.compare(0, open_pos, info.name, 0, open_pos) == 0) {
735 if (index >= 0 && index < info.size) {
736 DCHECK_GT(static_cast<int>(info.element_locations.size()), index);
737 if (info.element_locations[index] == -1)
738 return -1;
739 return ProgramManager::MakeFakeLocation(
740 info.fake_location_base, index);
745 return -1;
748 GLint Program::GetAttribLocation(
749 const std::string& original_name) const {
750 for (GLuint ii = 0; ii < attrib_infos_.size(); ++ii) {
751 const VertexAttrib& info = attrib_infos_[ii];
752 if (info.name == original_name) {
753 return info.location;
756 return -1;
759 const Program::UniformInfo*
760 Program::GetUniformInfoByFakeLocation(
761 GLint fake_location, GLint* real_location, GLint* array_index) const {
762 DCHECK(real_location);
763 DCHECK(array_index);
764 if (fake_location < 0) {
765 return NULL;
768 GLint uniform_index = GetUniformInfoIndexFromFakeLocation(fake_location);
769 if (uniform_index >= 0 &&
770 static_cast<size_t>(uniform_index) < uniform_infos_.size()) {
771 const UniformInfo& uniform_info = uniform_infos_[uniform_index];
772 if (!uniform_info.IsValid()) {
773 return NULL;
775 GLint element_index = GetArrayElementIndexFromFakeLocation(fake_location);
776 if (element_index < uniform_info.size) {
777 *real_location = uniform_info.element_locations[element_index];
778 *array_index = element_index;
779 return &uniform_info;
782 return NULL;
785 const std::string* Program::GetAttribMappedName(
786 const std::string& original_name) const {
787 for (int ii = 0; ii < kMaxAttachedShaders; ++ii) {
788 Shader* shader = attached_shaders_[ii].get();
789 if (shader) {
790 const std::string* mapped_name =
791 shader->GetAttribMappedName(original_name);
792 if (mapped_name)
793 return mapped_name;
796 return NULL;
799 const std::string* Program::GetOriginalNameFromHashedName(
800 const std::string& hashed_name) const {
801 for (int ii = 0; ii < kMaxAttachedShaders; ++ii) {
802 Shader* shader = attached_shaders_[ii].get();
803 if (shader) {
804 const std::string* original_name =
805 shader->GetOriginalNameFromHashedName(hashed_name);
806 if (original_name)
807 return original_name;
810 return NULL;
813 bool Program::SetUniformLocationBinding(
814 const std::string& name, GLint location) {
815 std::string short_name;
816 int element_index = 0;
817 if (!GetUniformNameSansElement(name, &element_index, &short_name) ||
818 element_index != 0) {
819 return false;
822 bind_uniform_location_map_[short_name] = location;
823 return true;
826 // Note: This is only valid to call right after a program has been linked
827 // successfully.
828 void Program::GetCorrectedUniformData(
829 const std::string& name,
830 std::string* corrected_name, std::string* original_name,
831 GLsizei* size, GLenum* type) const {
832 DCHECK(corrected_name && original_name && size && type);
833 for (int ii = 0; ii < kMaxAttachedShaders; ++ii) {
834 Shader* shader = attached_shaders_[ii].get();
835 if (!shader)
836 continue;
837 const sh::ShaderVariable* info = NULL;
838 const sh::Uniform* uniform = shader->GetUniformInfo(name);
839 bool found = false;
840 if (uniform)
841 found = uniform->findInfoByMappedName(name, &info, original_name);
842 if (found) {
843 const std::string kArraySpec("[0]");
844 if (info->arraySize > 0 && !EndsWith(name, kArraySpec, true)) {
845 *corrected_name = name + kArraySpec;
846 *original_name += kArraySpec;
847 } else {
848 *corrected_name = name;
850 *type = info->type;
851 *size = std::max(1u, info->arraySize);
852 return;
855 // TODO(zmo): this path should never be reached unless there is a serious
856 // bug in the driver or in ANGLE translator.
857 *corrected_name = name;
858 *original_name = name;
861 void Program::GetVertexAttribData(
862 const std::string& name, std::string* original_name, GLenum* type) const {
863 DCHECK(original_name);
864 DCHECK(type);
865 Shader* shader = attached_shaders_[ShaderTypeToIndex(GL_VERTEX_SHADER)].get();
866 if (shader) {
867 // Vertex attributes can not be arrays or structs (GLSL ES 3.00.4, section
868 // 4.3.4, "Input Variables"), so the top level sh::Attribute returns the
869 // information we need.
870 const sh::Attribute* info = shader->GetAttribInfo(name);
871 if (info) {
872 *original_name = info->name;
873 *type = info->type;
874 return;
877 // TODO(zmo): this path should never be reached unless there is a serious
878 // bug in the driver or in ANGLE translator.
879 *original_name = name;
882 bool Program::AddUniformInfo(
883 GLsizei size, GLenum type, GLint location, GLint fake_base_location,
884 const std::string& name, const std::string& original_name,
885 size_t* next_available_index) {
886 DCHECK(next_available_index);
887 const char* kArraySpec = "[0]";
888 size_t uniform_index =
889 fake_base_location >= 0 ? fake_base_location : *next_available_index;
890 if (uniform_infos_.size() < uniform_index + 1) {
891 uniform_infos_.resize(uniform_index + 1);
894 // return if this location is already in use.
895 if (uniform_infos_[uniform_index].IsValid()) {
896 DCHECK_GE(fake_base_location, 0);
897 return false;
900 uniform_infos_[uniform_index] = UniformInfo(
901 size, type, uniform_index, original_name);
902 ++num_uniforms_;
904 UniformInfo& info = uniform_infos_[uniform_index];
905 info.element_locations.resize(size);
906 info.element_locations[0] = location;
907 DCHECK_GE(size, 0);
908 size_t num_texture_units = info.IsSampler() ? static_cast<size_t>(size) : 0u;
909 info.texture_units.clear();
910 info.texture_units.resize(num_texture_units, 0);
912 if (size > 1) {
913 // Go through the array element locations looking for a match.
914 // We can skip the first element because it's the same as the
915 // the location without the array operators.
916 size_t array_pos = name.rfind(kArraySpec);
917 std::string base_name = name;
918 if (name.size() > 3) {
919 if (array_pos != name.size() - 3) {
920 info.name = name + kArraySpec;
921 } else {
922 base_name = name.substr(0, name.size() - 3);
925 for (GLsizei ii = 1; ii < info.size; ++ii) {
926 std::string element_name(base_name + "[" + base::IntToString(ii) + "]");
927 info.element_locations[ii] =
928 glGetUniformLocation(service_id_, element_name.c_str());
932 info.is_array =
933 (size > 1 ||
934 (info.name.size() > 3 &&
935 info.name.rfind(kArraySpec) == info.name.size() - 3));
937 if (info.IsSampler()) {
938 sampler_indices_.push_back(info.fake_location_base);
940 max_uniform_name_length_ =
941 std::max(max_uniform_name_length_,
942 static_cast<GLsizei>(info.name.size()));
944 while (*next_available_index < uniform_infos_.size() &&
945 uniform_infos_[*next_available_index].IsValid()) {
946 *next_available_index = *next_available_index + 1;
949 return true;
952 const Program::UniformInfo*
953 Program::GetUniformInfo(
954 GLint index) const {
955 if (static_cast<size_t>(index) >= uniform_infos_.size()) {
956 return NULL;
959 const UniformInfo& info = uniform_infos_[index];
960 return info.IsValid() ? &info : NULL;
963 bool Program::SetSamplers(
964 GLint num_texture_units, GLint fake_location,
965 GLsizei count, const GLint* value) {
966 if (fake_location < 0) {
967 return true;
969 GLint uniform_index = GetUniformInfoIndexFromFakeLocation(fake_location);
970 if (uniform_index >= 0 &&
971 static_cast<size_t>(uniform_index) < uniform_infos_.size()) {
972 UniformInfo& info = uniform_infos_[uniform_index];
973 if (!info.IsValid()) {
974 return false;
976 GLint element_index = GetArrayElementIndexFromFakeLocation(fake_location);
977 if (element_index < info.size) {
978 count = std::min(info.size - element_index, count);
979 if (info.IsSampler() && count > 0) {
980 for (GLsizei ii = 0; ii < count; ++ii) {
981 if (value[ii] < 0 || value[ii] >= num_texture_units) {
982 return false;
985 std::copy(value, value + count,
986 info.texture_units.begin() + element_index);
987 return true;
991 return true;
994 void Program::GetProgramiv(GLenum pname, GLint* params) {
995 switch (pname) {
996 case GL_ACTIVE_ATTRIBUTES:
997 *params = attrib_infos_.size();
998 break;
999 case GL_ACTIVE_ATTRIBUTE_MAX_LENGTH:
1000 // Notice +1 to accomodate NULL terminator.
1001 *params = max_attrib_name_length_ + 1;
1002 break;
1003 case GL_ACTIVE_UNIFORMS:
1004 *params = num_uniforms_;
1005 break;
1006 case GL_ACTIVE_UNIFORM_MAX_LENGTH:
1007 // Notice +1 to accomodate NULL terminator.
1008 *params = max_uniform_name_length_ + 1;
1009 break;
1010 case GL_LINK_STATUS:
1011 *params = link_status_;
1012 break;
1013 case GL_INFO_LOG_LENGTH:
1014 // Notice +1 to accomodate NULL terminator.
1015 *params = log_info_.get() ? (log_info_->size() + 1) : 0;
1016 break;
1017 case GL_DELETE_STATUS:
1018 *params = deleted_;
1019 break;
1020 case GL_VALIDATE_STATUS:
1021 if (!IsValid()) {
1022 *params = GL_FALSE;
1023 } else {
1024 glGetProgramiv(service_id_, pname, params);
1026 break;
1027 default:
1028 glGetProgramiv(service_id_, pname, params);
1029 break;
1033 bool Program::AttachShader(
1034 ShaderManager* shader_manager,
1035 Shader* shader) {
1036 DCHECK(shader_manager);
1037 DCHECK(shader);
1038 int index = ShaderTypeToIndex(shader->shader_type());
1039 if (attached_shaders_[index].get() != NULL) {
1040 return false;
1042 attached_shaders_[index] = scoped_refptr<Shader>(shader);
1043 shader_manager->UseShader(shader);
1044 return true;
1047 bool Program::DetachShader(
1048 ShaderManager* shader_manager,
1049 Shader* shader) {
1050 DCHECK(shader_manager);
1051 DCHECK(shader);
1052 if (attached_shaders_[ShaderTypeToIndex(shader->shader_type())].get() !=
1053 shader) {
1054 return false;
1056 attached_shaders_[ShaderTypeToIndex(shader->shader_type())] = NULL;
1057 shader_manager->UnuseShader(shader);
1058 return true;
1061 void Program::DetachShaders(ShaderManager* shader_manager) {
1062 DCHECK(shader_manager);
1063 for (int ii = 0; ii < kMaxAttachedShaders; ++ii) {
1064 if (attached_shaders_[ii].get()) {
1065 DetachShader(shader_manager, attached_shaders_[ii].get());
1070 void Program::CompileAttachedShaders() {
1071 for (int ii = 0; ii < kMaxAttachedShaders; ++ii) {
1072 Shader* shader = attached_shaders_[ii].get();
1073 if (shader) {
1074 shader->DoCompile();
1079 bool Program::AttachedShadersExist() const {
1080 for (int ii = 0; ii < kMaxAttachedShaders; ++ii) {
1081 if (!attached_shaders_[ii].get())
1082 return false;
1084 return true;
1087 bool Program::CanLink() const {
1088 for (int ii = 0; ii < kMaxAttachedShaders; ++ii) {
1089 if (!attached_shaders_[ii].get() || !attached_shaders_[ii]->valid()) {
1090 return false;
1093 return true;
1096 bool Program::DetectShaderVersionMismatch() const {
1097 int version = Shader::kUndefinedShaderVersion;
1098 for (int ii = 0; ii < kMaxAttachedShaders; ++ii) {
1099 Shader* shader = attached_shaders_[ii].get();
1100 if (shader) {
1101 if (version != Shader::kUndefinedShaderVersion &&
1102 shader->shader_version() != version) {
1103 return true;
1105 version = shader->shader_version();
1106 DCHECK(version != Shader::kUndefinedShaderVersion);
1109 return false;
1112 bool Program::DetectAttribLocationBindingConflicts() const {
1113 std::set<GLint> location_binding_used;
1114 for (LocationMap::const_iterator it = bind_attrib_location_map_.begin();
1115 it != bind_attrib_location_map_.end(); ++it) {
1116 // Find out if an attribute is statically used in this program's shaders.
1117 const sh::Attribute* attrib = NULL;
1118 const std::string* mapped_name = GetAttribMappedName(it->first);
1119 if (!mapped_name)
1120 continue;
1121 for (int ii = 0; ii < kMaxAttachedShaders; ++ii) {
1122 if (!attached_shaders_[ii].get() || !attached_shaders_[ii]->valid())
1123 continue;
1124 attrib = attached_shaders_[ii]->GetAttribInfo(*mapped_name);
1125 if (attrib) {
1126 if (attrib->staticUse)
1127 break;
1128 else
1129 attrib = NULL;
1132 if (attrib) {
1133 size_t num_of_locations = 1;
1134 switch (attrib->type) {
1135 case GL_FLOAT_MAT2:
1136 num_of_locations = 2;
1137 break;
1138 case GL_FLOAT_MAT3:
1139 num_of_locations = 3;
1140 break;
1141 case GL_FLOAT_MAT4:
1142 num_of_locations = 4;
1143 break;
1144 default:
1145 break;
1147 for (size_t ii = 0; ii < num_of_locations; ++ii) {
1148 GLint loc = it->second + ii;
1149 std::pair<std::set<GLint>::iterator, bool> result =
1150 location_binding_used.insert(loc);
1151 if (!result.second)
1152 return true;
1156 return false;
1159 bool Program::DetectUniformsMismatch(std::string* conflicting_name) const {
1160 typedef std::map<std::string, const sh::Uniform*> UniformPointerMap;
1161 UniformPointerMap uniform_pointer_map;
1162 for (int ii = 0; ii < kMaxAttachedShaders; ++ii) {
1163 const UniformMap& shader_uniforms = attached_shaders_[ii]->uniform_map();
1164 for (UniformMap::const_iterator iter = shader_uniforms.begin();
1165 iter != shader_uniforms.end(); ++iter) {
1166 const std::string& name = iter->first;
1167 UniformPointerMap::iterator hit = uniform_pointer_map.find(name);
1168 if (hit == uniform_pointer_map.end()) {
1169 uniform_pointer_map[name] = &(iter->second);
1170 } else {
1171 // If a uniform is in the map, i.e., it has already been declared by
1172 // another shader, then the type, precision, etc. must match.
1173 if (hit->second->isSameUniformAtLinkTime(iter->second))
1174 continue;
1175 *conflicting_name = name;
1176 return true;
1180 return false;
1183 bool Program::DetectVaryingsMismatch(std::string* conflicting_name) const {
1184 DCHECK(attached_shaders_[0].get() &&
1185 attached_shaders_[0]->shader_type() == GL_VERTEX_SHADER &&
1186 attached_shaders_[1].get() &&
1187 attached_shaders_[1]->shader_type() == GL_FRAGMENT_SHADER);
1188 const VaryingMap* vertex_varyings = &(attached_shaders_[0]->varying_map());
1189 const VaryingMap* fragment_varyings = &(attached_shaders_[1]->varying_map());
1191 int shader_version = attached_shaders_[0]->shader_version();
1193 for (VaryingMap::const_iterator iter = fragment_varyings->begin();
1194 iter != fragment_varyings->end(); ++iter) {
1195 const std::string& name = iter->first;
1196 if (IsBuiltInFragmentVarying(name))
1197 continue;
1199 VaryingMap::const_iterator hit = vertex_varyings->find(name);
1200 if (hit == vertex_varyings->end()) {
1201 if (iter->second.staticUse) {
1202 *conflicting_name = name;
1203 return true;
1205 continue;
1208 if (!hit->second.isSameVaryingAtLinkTime(iter->second, shader_version)) {
1209 *conflicting_name = name;
1210 return true;
1214 return false;
1217 bool Program::DetectBuiltInInvariantConflicts() const {
1218 DCHECK(attached_shaders_[0].get() &&
1219 attached_shaders_[0]->shader_type() == GL_VERTEX_SHADER &&
1220 attached_shaders_[1].get() &&
1221 attached_shaders_[1]->shader_type() == GL_FRAGMENT_SHADER);
1222 const VaryingMap& vertex_varyings = attached_shaders_[0]->varying_map();
1223 const VaryingMap& fragment_varyings = attached_shaders_[1]->varying_map();
1225 bool gl_position_invariant = IsBuiltInInvariant(
1226 vertex_varyings, "gl_Position");
1227 bool gl_point_size_invariant = IsBuiltInInvariant(
1228 vertex_varyings, "gl_PointSize");
1230 bool gl_frag_coord_invariant = IsBuiltInInvariant(
1231 fragment_varyings, "gl_FragCoord");
1232 bool gl_point_coord_invariant = IsBuiltInInvariant(
1233 fragment_varyings, "gl_PointCoord");
1235 return ((gl_frag_coord_invariant && !gl_position_invariant) ||
1236 (gl_point_coord_invariant && !gl_point_size_invariant));
1239 bool Program::DetectGlobalNameConflicts(std::string* conflicting_name) const {
1240 DCHECK(attached_shaders_[0].get() &&
1241 attached_shaders_[0]->shader_type() == GL_VERTEX_SHADER &&
1242 attached_shaders_[1].get() &&
1243 attached_shaders_[1]->shader_type() == GL_FRAGMENT_SHADER);
1244 const UniformMap* uniforms[2];
1245 uniforms[0] = &(attached_shaders_[0]->uniform_map());
1246 uniforms[1] = &(attached_shaders_[1]->uniform_map());
1247 const AttributeMap* attribs =
1248 &(attached_shaders_[0]->attrib_map());
1250 for (AttributeMap::const_iterator iter = attribs->begin();
1251 iter != attribs->end(); ++iter) {
1252 for (int ii = 0; ii < 2; ++ii) {
1253 if (uniforms[ii]->find(iter->first) != uniforms[ii]->end()) {
1254 *conflicting_name = iter->first;
1255 return true;
1259 return false;
1262 bool Program::CheckVaryingsPacking(
1263 Program::VaryingsPackingOption option) const {
1264 DCHECK(attached_shaders_[0].get() &&
1265 attached_shaders_[0]->shader_type() == GL_VERTEX_SHADER &&
1266 attached_shaders_[1].get() &&
1267 attached_shaders_[1]->shader_type() == GL_FRAGMENT_SHADER);
1268 const VaryingMap* vertex_varyings = &(attached_shaders_[0]->varying_map());
1269 const VaryingMap* fragment_varyings = &(attached_shaders_[1]->varying_map());
1271 std::map<std::string, ShVariableInfo> combined_map;
1273 for (VaryingMap::const_iterator iter = fragment_varyings->begin();
1274 iter != fragment_varyings->end(); ++iter) {
1275 if (!iter->second.staticUse && option == kCountOnlyStaticallyUsed)
1276 continue;
1277 if (!IsBuiltInFragmentVarying(iter->first)) {
1278 VaryingMap::const_iterator vertex_iter =
1279 vertex_varyings->find(iter->first);
1280 if (vertex_iter == vertex_varyings->end() ||
1281 (!vertex_iter->second.staticUse &&
1282 option == kCountOnlyStaticallyUsed))
1283 continue;
1286 ShVariableInfo var;
1287 var.type = static_cast<sh::GLenum>(iter->second.type);
1288 var.size = std::max(1u, iter->second.arraySize);
1289 combined_map[iter->first] = var;
1292 if (combined_map.size() == 0)
1293 return true;
1294 scoped_ptr<ShVariableInfo[]> variables(
1295 new ShVariableInfo[combined_map.size()]);
1296 size_t index = 0;
1297 for (std::map<std::string, ShVariableInfo>::const_iterator iter =
1298 combined_map.begin();
1299 iter != combined_map.end(); ++iter) {
1300 variables[index].type = iter->second.type;
1301 variables[index].size = iter->second.size;
1302 ++index;
1304 return ShCheckVariablesWithinPackingLimits(
1305 static_cast<int>(manager_->max_varying_vectors()),
1306 variables.get(),
1307 combined_map.size());
1310 void Program::GetProgramInfo(
1311 ProgramManager* manager, CommonDecoder::Bucket* bucket) const {
1312 // NOTE: It seems to me the math in here does not need check for overflow
1313 // because the data being calucated from has various small limits. The max
1314 // number of attribs + uniforms is somewhere well under 1024. The maximum size
1315 // of an identifier is 256 characters.
1316 uint32 num_locations = 0;
1317 uint32 total_string_size = 0;
1319 for (size_t ii = 0; ii < attrib_infos_.size(); ++ii) {
1320 const VertexAttrib& info = attrib_infos_[ii];
1321 num_locations += 1;
1322 total_string_size += info.name.size();
1325 for (size_t ii = 0; ii < uniform_infos_.size(); ++ii) {
1326 const UniformInfo& info = uniform_infos_[ii];
1327 if (info.IsValid()) {
1328 num_locations += info.element_locations.size();
1329 total_string_size += info.name.size();
1333 uint32 num_inputs = attrib_infos_.size() + num_uniforms_;
1334 uint32 input_size = num_inputs * sizeof(ProgramInput);
1335 uint32 location_size = num_locations * sizeof(int32);
1336 uint32 size = sizeof(ProgramInfoHeader) +
1337 input_size + location_size + total_string_size;
1339 bucket->SetSize(size);
1340 ProgramInfoHeader* header = bucket->GetDataAs<ProgramInfoHeader*>(0, size);
1341 ProgramInput* inputs = bucket->GetDataAs<ProgramInput*>(
1342 sizeof(ProgramInfoHeader), input_size);
1343 int32* locations = bucket->GetDataAs<int32*>(
1344 sizeof(ProgramInfoHeader) + input_size, location_size);
1345 char* strings = bucket->GetDataAs<char*>(
1346 sizeof(ProgramInfoHeader) + input_size + location_size,
1347 total_string_size);
1348 DCHECK(header);
1349 DCHECK(inputs);
1350 DCHECK(locations);
1351 DCHECK(strings);
1353 header->link_status = link_status_;
1354 header->num_attribs = attrib_infos_.size();
1355 header->num_uniforms = num_uniforms_;
1357 for (size_t ii = 0; ii < attrib_infos_.size(); ++ii) {
1358 const VertexAttrib& info = attrib_infos_[ii];
1359 inputs->size = info.size;
1360 inputs->type = info.type;
1361 inputs->location_offset = ComputeOffset(header, locations);
1362 inputs->name_offset = ComputeOffset(header, strings);
1363 inputs->name_length = info.name.size();
1364 *locations++ = info.location;
1365 memcpy(strings, info.name.c_str(), info.name.size());
1366 strings += info.name.size();
1367 ++inputs;
1370 for (size_t ii = 0; ii < uniform_infos_.size(); ++ii) {
1371 const UniformInfo& info = uniform_infos_[ii];
1372 if (info.IsValid()) {
1373 inputs->size = info.size;
1374 inputs->type = info.type;
1375 inputs->location_offset = ComputeOffset(header, locations);
1376 inputs->name_offset = ComputeOffset(header, strings);
1377 inputs->name_length = info.name.size();
1378 DCHECK(static_cast<size_t>(info.size) == info.element_locations.size());
1379 for (size_t jj = 0; jj < info.element_locations.size(); ++jj) {
1380 if (info.element_locations[jj] == -1)
1381 *locations++ = -1;
1382 else
1383 *locations++ = ProgramManager::MakeFakeLocation(ii, jj);
1385 memcpy(strings, info.name.c_str(), info.name.size());
1386 strings += info.name.size();
1387 ++inputs;
1391 DCHECK_EQ(ComputeOffset(header, strings), size);
1394 bool Program::GetUniformBlocks(CommonDecoder::Bucket* bucket) const {
1395 // The data is packed into the bucket in the following order
1396 // 1) header
1397 // 2) N entries of block data (except for name and indices)
1398 // 3) name1, indices1, name2, indices2, ..., nameN, indicesN
1400 // We query all the data directly through GL calls, assuming they are
1401 // cheap through MANGLE.
1403 DCHECK(bucket);
1404 GLuint program = service_id();
1406 uint32_t header_size = sizeof(UniformBlocksHeader);
1407 bucket->SetSize(header_size); // In case we fail.
1409 uint32_t num_uniform_blocks = 0;
1410 GLint param = GL_FALSE;
1411 // We assume program is a valid program service id.
1412 glGetProgramiv(program, GL_LINK_STATUS, &param);
1413 if (param == GL_TRUE) {
1414 param = 0;
1415 glGetProgramiv(program, GL_ACTIVE_UNIFORM_BLOCKS, &param);
1416 num_uniform_blocks = static_cast<uint32_t>(param);
1418 if (num_uniform_blocks == 0) {
1419 // Although spec allows an implementation to return uniform block info
1420 // even if a link fails, for consistency, we disallow that.
1421 return true;
1424 std::vector<UniformBlockInfo> blocks(num_uniform_blocks);
1425 base::CheckedNumeric<uint32_t> size = sizeof(UniformBlockInfo);
1426 size *= num_uniform_blocks;
1427 uint32_t entry_size = size.ValueOrDefault(0);
1428 size += header_size;
1429 std::vector<std::string> names(num_uniform_blocks);
1430 GLint max_name_length = 0;
1431 glGetProgramiv(
1432 program, GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH, &max_name_length);
1433 std::vector<GLchar> buffer(max_name_length);
1434 GLsizei length;
1435 for (uint32_t ii = 0; ii < num_uniform_blocks; ++ii) {
1436 param = 0;
1437 glGetActiveUniformBlockiv(program, ii, GL_UNIFORM_BLOCK_BINDING, &param);
1438 blocks[ii].binding = static_cast<uint32_t>(param);
1440 param = 0;
1441 glGetActiveUniformBlockiv(program, ii, GL_UNIFORM_BLOCK_DATA_SIZE, &param);
1442 blocks[ii].data_size = static_cast<uint32_t>(param);
1444 blocks[ii].name_offset = size.ValueOrDefault(0);
1445 param = 0;
1446 glGetActiveUniformBlockiv(
1447 program, ii, GL_UNIFORM_BLOCK_NAME_LENGTH, &param);
1448 DCHECK_GE(max_name_length, param);
1449 memset(&buffer[0], 0, param);
1450 length = 0;
1451 glGetActiveUniformBlockName(
1452 program, ii, static_cast<GLsizei>(param), &length, &buffer[0]);
1453 DCHECK_EQ(param, length + 1);
1454 names[ii] = std::string(&buffer[0], length);
1455 // TODO(zmo): optimize the name mapping lookup.
1456 const std::string* original_name = GetOriginalNameFromHashedName(names[ii]);
1457 if (original_name)
1458 names[ii] = *original_name;
1459 blocks[ii].name_length = names[ii].size() + 1;
1460 size += blocks[ii].name_length;
1462 param = 0;
1463 glGetActiveUniformBlockiv(
1464 program, ii, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &param);
1465 blocks[ii].active_uniforms = static_cast<uint32_t>(param);
1466 blocks[ii].active_uniform_offset = size.ValueOrDefault(0);
1467 base::CheckedNumeric<uint32_t> indices_size = blocks[ii].active_uniforms;
1468 indices_size *= sizeof(uint32_t);
1469 if (!indices_size.IsValid())
1470 return false;
1471 size += indices_size.ValueOrDefault(0);
1473 param = 0;
1474 glGetActiveUniformBlockiv(
1475 program, ii, GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER, &param);
1476 blocks[ii].referenced_by_vertex_shader = static_cast<uint32_t>(param);
1478 param = 0;
1479 glGetActiveUniformBlockiv(
1480 program, ii, GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER, &param);
1481 blocks[ii].referenced_by_fragment_shader = static_cast<uint32_t>(param);
1483 if (!size.IsValid())
1484 return false;
1485 uint32_t total_size = size.ValueOrDefault(0);
1486 DCHECK_LE(header_size + entry_size, total_size);
1487 uint32_t data_size = total_size - header_size - entry_size;
1489 bucket->SetSize(total_size);
1490 UniformBlocksHeader* header =
1491 bucket->GetDataAs<UniformBlocksHeader*>(0, header_size);
1492 UniformBlockInfo* entries = bucket->GetDataAs<UniformBlockInfo*>(
1493 header_size, entry_size);
1494 char* data = bucket->GetDataAs<char*>(header_size + entry_size, data_size);
1495 DCHECK(header);
1496 DCHECK(entries);
1497 DCHECK(data);
1499 // Copy over data for the header and entries.
1500 header->num_uniform_blocks = num_uniform_blocks;
1501 memcpy(entries, &blocks[0], entry_size);
1503 std::vector<GLint> params;
1504 for (uint32_t ii = 0; ii < num_uniform_blocks; ++ii) {
1505 // Get active uniform name.
1506 memcpy(data, names[ii].c_str(), names[ii].length() + 1);
1507 data += names[ii].length() + 1;
1509 // Get active uniform indices.
1510 if (params.size() < blocks[ii].active_uniforms)
1511 params.resize(blocks[ii].active_uniforms);
1512 uint32_t num_bytes = blocks[ii].active_uniforms * sizeof(GLint);
1513 memset(&params[0], 0, num_bytes);
1514 glGetActiveUniformBlockiv(
1515 program, ii, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, &params[0]);
1516 uint32_t* indices = reinterpret_cast<uint32_t*>(data);
1517 for (uint32_t uu = 0; uu < blocks[ii].active_uniforms; ++uu) {
1518 indices[uu] = static_cast<uint32_t>(params[uu]);
1520 data += num_bytes;
1522 DCHECK_EQ(ComputeOffset(header, data), total_size);
1523 return true;
1526 bool Program::GetTransformFeedbackVaryings(
1527 CommonDecoder::Bucket* bucket) const {
1528 // The data is packed into the bucket in the following order
1529 // 1) header
1530 // 2) N entries of varying data (except for name)
1531 // 3) name1, name2, ..., nameN
1533 // We query all the data directly through GL calls, assuming they are
1534 // cheap through MANGLE.
1536 DCHECK(bucket);
1537 GLuint program = service_id();
1539 uint32_t header_size = sizeof(TransformFeedbackVaryingsHeader);
1540 bucket->SetSize(header_size); // In case we fail.
1542 uint32_t num_transform_feedback_varyings = 0;
1543 GLint param = GL_FALSE;
1544 // We assume program is a valid program service id.
1545 glGetProgramiv(program, GL_LINK_STATUS, &param);
1546 if (param == GL_TRUE) {
1547 param = 0;
1548 glGetProgramiv(program, GL_TRANSFORM_FEEDBACK_VARYINGS, &param);
1549 num_transform_feedback_varyings = static_cast<uint32_t>(param);
1551 if (num_transform_feedback_varyings == 0) {
1552 return true;
1555 std::vector<TransformFeedbackVaryingInfo> varyings(
1556 num_transform_feedback_varyings);
1557 base::CheckedNumeric<uint32_t> size = sizeof(TransformFeedbackVaryingInfo);
1558 size *= num_transform_feedback_varyings;
1559 uint32_t entry_size = size.ValueOrDefault(0);
1560 size += header_size;
1561 std::vector<std::string> names(num_transform_feedback_varyings);
1562 GLint max_name_length = 0;
1563 glGetProgramiv(
1564 program, GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH, &max_name_length);
1565 if (max_name_length < 1)
1566 max_name_length = 1;
1567 std::vector<char> buffer(max_name_length);
1568 for (uint32_t ii = 0; ii < num_transform_feedback_varyings; ++ii) {
1569 GLsizei var_size = 0;
1570 GLsizei var_name_length = 0;
1571 GLenum var_type = 0;
1572 glGetTransformFeedbackVarying(
1573 program, ii, max_name_length,
1574 &var_name_length, &var_size, &var_type, &buffer[0]);
1575 varyings[ii].size = static_cast<uint32_t>(var_size);
1576 varyings[ii].type = static_cast<uint32_t>(var_type);
1577 varyings[ii].name_offset = static_cast<uint32_t>(size.ValueOrDefault(0));
1578 DCHECK_GT(max_name_length, var_name_length);
1579 names[ii] = std::string(&buffer[0], var_name_length);
1580 // TODO(zmo): optimize the name mapping lookup.
1581 const std::string* original_name = GetOriginalNameFromHashedName(names[ii]);
1582 if (original_name)
1583 names[ii] = *original_name;
1584 varyings[ii].name_length = names[ii].size() + 1;
1585 size += names[ii].size();
1586 size += 1;
1588 if (!size.IsValid())
1589 return false;
1590 uint32_t total_size = size.ValueOrDefault(0);
1591 DCHECK_LE(header_size + entry_size, total_size);
1592 uint32_t data_size = total_size - header_size - entry_size;
1594 bucket->SetSize(total_size);
1595 TransformFeedbackVaryingsHeader* header =
1596 bucket->GetDataAs<TransformFeedbackVaryingsHeader*>(0, header_size);
1597 TransformFeedbackVaryingInfo* entries =
1598 bucket->GetDataAs<TransformFeedbackVaryingInfo*>(header_size, entry_size);
1599 char* data = bucket->GetDataAs<char*>(header_size + entry_size, data_size);
1600 DCHECK(header);
1601 DCHECK(entries);
1602 DCHECK(data);
1604 // Copy over data for the header and entries.
1605 header->num_transform_feedback_varyings = num_transform_feedback_varyings;
1606 memcpy(entries, &varyings[0], entry_size);
1608 for (uint32_t ii = 0; ii < num_transform_feedback_varyings; ++ii) {
1609 memcpy(data, names[ii].c_str(), names[ii].length() + 1);
1610 data += names[ii].length() + 1;
1612 DCHECK_EQ(ComputeOffset(header, data), total_size);
1613 return true;
1616 bool Program::GetUniformsES3(CommonDecoder::Bucket* bucket) const {
1617 // The data is packed into the bucket in the following order
1618 // 1) header
1619 // 2) N entries of UniformES3Info
1621 // We query all the data directly through GL calls, assuming they are
1622 // cheap through MANGLE.
1624 DCHECK(bucket);
1625 GLuint program = service_id();
1627 uint32_t header_size = sizeof(UniformsES3Header);
1628 bucket->SetSize(header_size); // In case we fail.
1630 GLsizei count = 0;
1631 GLint param = GL_FALSE;
1632 // We assume program is a valid program service id.
1633 glGetProgramiv(program, GL_LINK_STATUS, &param);
1634 if (param == GL_TRUE) {
1635 param = 0;
1636 glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &count);
1638 if (count == 0) {
1639 return true;
1642 base::CheckedNumeric<uint32_t> size = sizeof(UniformES3Info);
1643 size *= count;
1644 uint32_t entry_size = size.ValueOrDefault(0);
1645 size += header_size;
1646 if (!size.IsValid())
1647 return false;
1648 uint32_t total_size = size.ValueOrDefault(0);
1649 bucket->SetSize(total_size);
1650 UniformsES3Header* header =
1651 bucket->GetDataAs<UniformsES3Header*>(0, header_size);
1652 DCHECK(header);
1653 header->num_uniforms = static_cast<uint32_t>(count);
1655 // Instead of GetDataAs<UniformES3Info*>, we do GetDataAs<int32_t>. This is
1656 // because struct UniformES3Info is defined as five int32_t.
1657 // By doing this, we can fill the structs through loops.
1658 int32_t* entries =
1659 bucket->GetDataAs<int32_t*>(header_size, entry_size);
1660 DCHECK(entries);
1661 const size_t kStride = sizeof(UniformES3Info) / sizeof(int32_t);
1663 const GLenum kPname[] = {
1664 GL_UNIFORM_BLOCK_INDEX,
1665 GL_UNIFORM_OFFSET,
1666 GL_UNIFORM_ARRAY_STRIDE,
1667 GL_UNIFORM_MATRIX_STRIDE,
1668 GL_UNIFORM_IS_ROW_MAJOR,
1670 const GLint kDefaultValue[] = { -1, -1, -1, -1, 0 };
1671 const size_t kNumPnames = arraysize(kPname);
1672 std::vector<GLuint> indices(count);
1673 for (GLsizei ii = 0; ii < count; ++ii) {
1674 indices[ii] = ii;
1676 std::vector<GLint> params(count);
1677 for (size_t pname_index = 0; pname_index < kNumPnames; ++pname_index) {
1678 for (GLsizei ii = 0; ii < count; ++ii) {
1679 params[ii] = kDefaultValue[pname_index];
1681 glGetActiveUniformsiv(
1682 program, count, &indices[0], kPname[pname_index], &params[0]);
1683 for (GLsizei ii = 0; ii < count; ++ii) {
1684 entries[kStride * ii + pname_index] = params[ii];
1687 return true;
1690 void Program::TransformFeedbackVaryings(GLsizei count,
1691 const char* const* varyings,
1692 GLenum buffer_mode) {
1693 transform_feedback_varyings_.clear();
1694 for (GLsizei i = 0; i < count; ++i) {
1695 transform_feedback_varyings_.push_back(std::string(varyings[i]));
1697 transform_feedback_buffer_mode_ = buffer_mode;
1700 Program::~Program() {
1701 if (manager_) {
1702 if (manager_->have_context_) {
1703 glDeleteProgram(service_id());
1705 manager_->StopTracking(this);
1706 manager_ = NULL;
1711 ProgramManager::ProgramManager(ProgramCache* program_cache,
1712 uint32 max_varying_vectors)
1713 : program_count_(0),
1714 have_context_(true),
1715 program_cache_(program_cache),
1716 max_varying_vectors_(max_varying_vectors) { }
1718 ProgramManager::~ProgramManager() {
1719 DCHECK(programs_.empty());
1722 void ProgramManager::Destroy(bool have_context) {
1723 have_context_ = have_context;
1724 programs_.clear();
1727 void ProgramManager::StartTracking(Program* /* program */) {
1728 ++program_count_;
1731 void ProgramManager::StopTracking(Program* /* program */) {
1732 --program_count_;
1735 Program* ProgramManager::CreateProgram(
1736 GLuint client_id, GLuint service_id) {
1737 std::pair<ProgramMap::iterator, bool> result =
1738 programs_.insert(
1739 std::make_pair(client_id,
1740 scoped_refptr<Program>(
1741 new Program(this, service_id))));
1742 DCHECK(result.second);
1743 return result.first->second.get();
1746 Program* ProgramManager::GetProgram(GLuint client_id) {
1747 ProgramMap::iterator it = programs_.find(client_id);
1748 return it != programs_.end() ? it->second.get() : NULL;
1751 bool ProgramManager::GetClientId(GLuint service_id, GLuint* client_id) const {
1752 // This doesn't need to be fast. It's only used during slow queries.
1753 for (ProgramMap::const_iterator it = programs_.begin();
1754 it != programs_.end(); ++it) {
1755 if (it->second->service_id() == service_id) {
1756 *client_id = it->first;
1757 return true;
1760 return false;
1763 ProgramCache* ProgramManager::program_cache() const {
1764 return program_cache_;
1767 bool ProgramManager::IsOwned(Program* program) {
1768 for (ProgramMap::iterator it = programs_.begin();
1769 it != programs_.end(); ++it) {
1770 if (it->second.get() == program) {
1771 return true;
1774 return false;
1777 void ProgramManager::RemoveProgramInfoIfUnused(
1778 ShaderManager* shader_manager, Program* program) {
1779 DCHECK(shader_manager);
1780 DCHECK(program);
1781 DCHECK(IsOwned(program));
1782 if (program->IsDeleted() && !program->InUse()) {
1783 program->DetachShaders(shader_manager);
1784 for (ProgramMap::iterator it = programs_.begin();
1785 it != programs_.end(); ++it) {
1786 if (it->second.get() == program) {
1787 programs_.erase(it);
1788 return;
1791 NOTREACHED();
1795 void ProgramManager::MarkAsDeleted(
1796 ShaderManager* shader_manager,
1797 Program* program) {
1798 DCHECK(shader_manager);
1799 DCHECK(program);
1800 DCHECK(IsOwned(program));
1801 program->MarkAsDeleted();
1802 RemoveProgramInfoIfUnused(shader_manager, program);
1805 void ProgramManager::UseProgram(Program* program) {
1806 DCHECK(program);
1807 DCHECK(IsOwned(program));
1808 program->IncUseCount();
1811 void ProgramManager::UnuseProgram(
1812 ShaderManager* shader_manager,
1813 Program* program) {
1814 DCHECK(shader_manager);
1815 DCHECK(program);
1816 DCHECK(IsOwned(program));
1817 program->DecUseCount();
1818 RemoveProgramInfoIfUnused(shader_manager, program);
1821 void ProgramManager::ClearUniforms(Program* program) {
1822 DCHECK(program);
1823 program->ClearUniforms(&zero_);
1826 int32 ProgramManager::MakeFakeLocation(int32 index, int32 element) {
1827 return index + element * 0x10000;
1830 } // namespace gles2
1831 } // namespace gpu