mesa: fix glGetActiveUniformsiv regression
[mesa.git] / src / mesa / main / uniform_query.cpp
1 /*
2 * Mesa 3-D graphics library
3 *
4 * Copyright (C) 2004-2008 Brian Paul All Rights Reserved.
5 * Copyright (C) 2009-2010 VMware, Inc. All Rights Reserved.
6 * Copyright © 2010, 2011 Intel Corporation
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included
16 * in all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
22 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
23 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24 * OTHER DEALINGS IN THE SOFTWARE.
25 */
26
27 #include <stdlib.h>
28
29 #include "main/core.h"
30 #include "main/context.h"
31 #include "ir.h"
32 #include "ir_uniform.h"
33 #include "program/hash_table.h"
34 #include "../glsl/program.h"
35 #include "../glsl/ir_uniform.h"
36 #include "../glsl/glsl_parser_extras.h"
37 #include "main/shaderapi.h"
38 #include "main/shaderobj.h"
39 #include "uniforms.h"
40
41
42 extern "C" void GLAPIENTRY
43 _mesa_GetActiveUniform(GLuint program, GLuint index,
44 GLsizei maxLength, GLsizei *length, GLint *size,
45 GLenum *type, GLcharARB *nameOut)
46 {
47 GET_CURRENT_CONTEXT(ctx);
48 struct gl_shader_program *shProg;
49 struct gl_program_resource *res;
50
51 if (maxLength < 0) {
52 _mesa_error(ctx, GL_INVALID_VALUE, "glGetActiveUniform(maxLength < 0)");
53 return;
54 }
55
56 shProg = _mesa_lookup_shader_program_err(ctx, program, "glGetActiveUniform");
57 if (!shProg)
58 return;
59
60 res = _mesa_program_resource_find_index((struct gl_shader_program *) shProg,
61 GL_UNIFORM, index);
62
63 if (!res) {
64 _mesa_error(ctx, GL_INVALID_VALUE, "glGetActiveUniform(index)");
65 return;
66 }
67
68 if (nameOut)
69 _mesa_get_program_resource_name(shProg, GL_UNIFORM, index, maxLength,
70 length, nameOut, "glGetActiveUniform");
71 if (type)
72 _mesa_program_resource_prop((struct gl_shader_program *) shProg,
73 res, index, GL_TYPE, (GLint*) type,
74 "glGetActiveUniform");
75 if (size)
76 _mesa_program_resource_prop((struct gl_shader_program *) shProg,
77 res, index, GL_ARRAY_SIZE, (GLint*) size,
78 "glGetActiveUniform");
79 }
80
81 static GLenum
82 resource_prop_from_uniform_prop(GLenum uni_prop)
83 {
84 switch (uni_prop) {
85 case GL_UNIFORM_TYPE:
86 return GL_TYPE;
87 case GL_UNIFORM_SIZE:
88 return GL_ARRAY_SIZE;
89 case GL_UNIFORM_NAME_LENGTH:
90 return GL_NAME_LENGTH;
91 case GL_UNIFORM_BLOCK_INDEX:
92 return GL_BLOCK_INDEX;
93 case GL_UNIFORM_OFFSET:
94 return GL_OFFSET;
95 case GL_UNIFORM_ARRAY_STRIDE:
96 return GL_ARRAY_STRIDE;
97 case GL_UNIFORM_MATRIX_STRIDE:
98 return GL_MATRIX_STRIDE;
99 case GL_UNIFORM_IS_ROW_MAJOR:
100 return GL_IS_ROW_MAJOR;
101 case GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX:
102 return GL_ATOMIC_COUNTER_BUFFER_INDEX;
103 default:
104 return 0;
105 }
106 }
107
108 extern "C" void GLAPIENTRY
109 _mesa_GetActiveUniformsiv(GLuint program,
110 GLsizei uniformCount,
111 const GLuint *uniformIndices,
112 GLenum pname,
113 GLint *params)
114 {
115 GET_CURRENT_CONTEXT(ctx);
116 struct gl_shader_program *shProg;
117 struct gl_program_resource *res;
118 GLenum res_prop;
119
120 if (uniformCount < 0) {
121 _mesa_error(ctx, GL_INVALID_VALUE,
122 "glGetActiveUniformsiv(uniformCount < 0)");
123 return;
124 }
125
126 shProg = _mesa_lookup_shader_program_err(ctx, program, "glGetActiveUniform");
127 if (!shProg)
128 return;
129
130 res_prop = resource_prop_from_uniform_prop(pname);
131
132 /* We need to first verify that each entry exists as active uniform. If
133 * not, generate error and do not cause any other side effects.
134 *
135 * In the case of and error condition, Page 16 (section 2.3.1 Errors)
136 * of the OpenGL 4.5 spec says:
137 *
138 * "If the generating command modifies values through a pointer argu-
139 * ment, no change is made to these values."
140 */
141 for (int i = 0; i < uniformCount; i++) {
142 if (!_mesa_program_resource_find_index(shProg, GL_UNIFORM,
143 uniformIndices[i])) {
144 _mesa_error(ctx, GL_INVALID_VALUE, "glGetActiveUniformsiv(index)");
145 return;
146 }
147 }
148
149 for (int i = 0; i < uniformCount; i++) {
150 res = _mesa_program_resource_find_index(shProg, GL_UNIFORM,
151 uniformIndices[i]);
152 if (!_mesa_program_resource_prop(shProg, res, uniformIndices[i],
153 res_prop, &params[i],
154 "glGetActiveUniformsiv"))
155 break;
156 }
157 }
158
159 static struct gl_uniform_storage *
160 validate_uniform_parameters(struct gl_context *ctx,
161 struct gl_shader_program *shProg,
162 GLint location, GLsizei count,
163 unsigned *array_index,
164 const char *caller)
165 {
166 if (shProg == NULL) {
167 _mesa_error(ctx, GL_INVALID_OPERATION, "%s(program not linked)", caller);
168 return NULL;
169 }
170
171 /* From page 12 (page 26 of the PDF) of the OpenGL 2.1 spec:
172 *
173 * "If a negative number is provided where an argument of type sizei or
174 * sizeiptr is specified, the error INVALID_VALUE is generated."
175 */
176 if (count < 0) {
177 _mesa_error(ctx, GL_INVALID_VALUE, "%s(count < 0)", caller);
178 return NULL;
179 }
180
181 /* Check that the given location is in bounds of uniform remap table.
182 * Unlinked programs will have NumUniformRemapTable == 0, so we can take
183 * the shProg->LinkStatus check out of the main path.
184 */
185 if (unlikely(location >= (GLint) shProg->NumUniformRemapTable)) {
186 if (!shProg->LinkStatus)
187 _mesa_error(ctx, GL_INVALID_OPERATION, "%s(program not linked)",
188 caller);
189 else
190 _mesa_error(ctx, GL_INVALID_OPERATION, "%s(location=%d)",
191 caller, location);
192
193 return NULL;
194 }
195
196 if (location == -1) {
197 if (!shProg->LinkStatus)
198 _mesa_error(ctx, GL_INVALID_OPERATION, "%s(program not linked)",
199 caller);
200
201 return NULL;
202 }
203
204 /* Page 82 (page 96 of the PDF) of the OpenGL 2.1 spec says:
205 *
206 * "If any of the following conditions occur, an INVALID_OPERATION
207 * error is generated by the Uniform* commands, and no uniform values
208 * are changed:
209 *
210 * ...
211 *
212 * - if no variable with a location of location exists in the
213 * program object currently in use and location is not -1,
214 * - if count is greater than one, and the uniform declared in the
215 * shader is not an array variable,
216 */
217 if (location < -1 || !shProg->UniformRemapTable[location]) {
218 _mesa_error(ctx, GL_INVALID_OPERATION, "%s(location=%d)",
219 caller, location);
220 return NULL;
221 }
222
223 /* If the driver storage pointer in remap table is -1, we ignore silently.
224 *
225 * GL_ARB_explicit_uniform_location spec says:
226 * "What happens if Uniform* is called with an explicitly defined
227 * uniform location, but that uniform is deemed inactive by the
228 * linker?
229 *
230 * RESOLVED: The call is ignored for inactive uniform variables and
231 * no error is generated."
232 *
233 */
234 if (shProg->UniformRemapTable[location] ==
235 INACTIVE_UNIFORM_EXPLICIT_LOCATION)
236 return NULL;
237
238 struct gl_uniform_storage *const uni = shProg->UniformRemapTable[location];
239
240 if (uni->array_elements == 0) {
241 if (count > 1) {
242 _mesa_error(ctx, GL_INVALID_OPERATION,
243 "%s(count = %u for non-array \"%s\"@%d)",
244 caller, count, uni->name, location);
245 return NULL;
246 }
247
248 assert((location - uni->remap_location) == 0);
249 *array_index = 0;
250 } else {
251 /* The array index specified by the uniform location is just the uniform
252 * location minus the base location of of the uniform.
253 */
254 *array_index = location - uni->remap_location;
255
256 /* If the uniform is an array, check that array_index is in bounds.
257 * array_index is unsigned so no need to check for less than zero.
258 */
259 if (*array_index >= uni->array_elements) {
260 _mesa_error(ctx, GL_INVALID_OPERATION, "%s(location=%d)",
261 caller, location);
262 return NULL;
263 }
264 }
265 return uni;
266 }
267
268 /**
269 * Called via glGetUniform[fiui]v() to get the current value of a uniform.
270 */
271 extern "C" void
272 _mesa_get_uniform(struct gl_context *ctx, GLuint program, GLint location,
273 GLsizei bufSize, enum glsl_base_type returnType,
274 GLvoid *paramsOut)
275 {
276 struct gl_shader_program *shProg =
277 _mesa_lookup_shader_program_err(ctx, program, "glGetUniformfv");
278 unsigned offset;
279
280 struct gl_uniform_storage *const uni =
281 validate_uniform_parameters(ctx, shProg, location, 1,
282 &offset, "glGetUniform");
283 if (uni == NULL) {
284 /* For glGetUniform, page 264 (page 278 of the PDF) of the OpenGL 2.1
285 * spec says:
286 *
287 * "The error INVALID_OPERATION is generated if program has not been
288 * linked successfully, or if location is not a valid location for
289 * program."
290 *
291 * For glUniform, page 82 (page 96 of the PDF) of the OpenGL 2.1 spec
292 * says:
293 *
294 * "If the value of location is -1, the Uniform* commands will
295 * silently ignore the data passed in, and the current uniform
296 * values will not be changed."
297 *
298 * Allowing -1 for the location parameter of glUniform allows
299 * applications to avoid error paths in the case that, for example, some
300 * uniform variable is removed by the compiler / linker after
301 * optimization. In this case, the new value of the uniform is dropped
302 * on the floor. For the case of glGetUniform, there is nothing
303 * sensible to do for a location of -1.
304 *
305 * If the location was -1, validate_unfirom_parameters will return NULL
306 * without raising an error. Raise the error here.
307 */
308 if (location == -1) {
309 _mesa_error(ctx, GL_INVALID_OPERATION, "glGetUniform(location=%d)",
310 location);
311 }
312
313 return;
314 }
315
316 {
317 unsigned elements = (uni->type->is_sampler())
318 ? 1 : uni->type->components();
319
320 /* Calculate the source base address *BEFORE* modifying elements to
321 * account for the size of the user's buffer.
322 */
323 const union gl_constant_value *const src =
324 &uni->storage[offset * elements];
325
326 assert(returnType == GLSL_TYPE_FLOAT || returnType == GLSL_TYPE_INT ||
327 returnType == GLSL_TYPE_UINT);
328 /* The three (currently) supported types all have the same size,
329 * which is of course the same as their union. That'll change
330 * with glGetUniformdv()...
331 */
332 unsigned bytes = sizeof(src[0]) * elements;
333 if (bufSize < 0 || bytes > (unsigned) bufSize) {
334 _mesa_error( ctx, GL_INVALID_OPERATION,
335 "glGetnUniform*vARB(out of bounds: bufSize is %d,"
336 " but %u bytes are required)", bufSize, bytes );
337 return;
338 }
339
340 /* If the return type and the uniform's native type are "compatible,"
341 * just memcpy the data. If the types are not compatible, perform a
342 * slower convert-and-copy process.
343 */
344 if (returnType == uni->type->base_type
345 || ((returnType == GLSL_TYPE_INT
346 || returnType == GLSL_TYPE_UINT)
347 &&
348 (uni->type->base_type == GLSL_TYPE_INT
349 || uni->type->base_type == GLSL_TYPE_UINT
350 || uni->type->base_type == GLSL_TYPE_SAMPLER))) {
351 memcpy(paramsOut, src, bytes);
352 } else {
353 union gl_constant_value *const dst =
354 (union gl_constant_value *) paramsOut;
355
356 /* This code could be optimized by putting the loop inside the switch
357 * statements. However, this is not expected to be
358 * performance-critical code.
359 */
360 for (unsigned i = 0; i < elements; i++) {
361 switch (returnType) {
362 case GLSL_TYPE_FLOAT:
363 switch (uni->type->base_type) {
364 case GLSL_TYPE_UINT:
365 dst[i].f = (float) src[i].u;
366 break;
367 case GLSL_TYPE_INT:
368 case GLSL_TYPE_SAMPLER:
369 dst[i].f = (float) src[i].i;
370 break;
371 case GLSL_TYPE_BOOL:
372 dst[i].f = src[i].i ? 1.0f : 0.0f;
373 break;
374 default:
375 assert(!"Should not get here.");
376 break;
377 }
378 break;
379
380 case GLSL_TYPE_INT:
381 case GLSL_TYPE_UINT:
382 switch (uni->type->base_type) {
383 case GLSL_TYPE_FLOAT:
384 /* While the GL 3.2 core spec doesn't explicitly
385 * state how conversion of float uniforms to integer
386 * values works, in section 6.2 "State Tables" on
387 * page 267 it says:
388 *
389 * "Unless otherwise specified, when floating
390 * point state is returned as integer values or
391 * integer state is returned as floating-point
392 * values it is converted in the fashion
393 * described in section 6.1.2"
394 *
395 * That section, on page 248, says:
396 *
397 * "If GetIntegerv or GetInteger64v are called,
398 * a floating-point value is rounded to the
399 * nearest integer..."
400 */
401 dst[i].i = IROUND(src[i].f);
402 break;
403 case GLSL_TYPE_BOOL:
404 dst[i].i = src[i].i ? 1 : 0;
405 break;
406 default:
407 assert(!"Should not get here.");
408 break;
409 }
410 break;
411
412 default:
413 assert(!"Should not get here.");
414 break;
415 }
416 }
417 }
418 }
419 }
420
421 static void
422 log_uniform(const void *values, enum glsl_base_type basicType,
423 unsigned rows, unsigned cols, unsigned count,
424 bool transpose,
425 const struct gl_shader_program *shProg,
426 GLint location,
427 const struct gl_uniform_storage *uni)
428 {
429
430 const union gl_constant_value *v = (const union gl_constant_value *) values;
431 const unsigned elems = rows * cols * count;
432 const char *const extra = (cols == 1) ? "uniform" : "uniform matrix";
433
434 printf("Mesa: set program %u %s \"%s\" (loc %d, type \"%s\", "
435 "transpose = %s) to: ",
436 shProg->Name, extra, uni->name, location, uni->type->name,
437 transpose ? "true" : "false");
438 for (unsigned i = 0; i < elems; i++) {
439 if (i != 0 && ((i % rows) == 0))
440 printf(", ");
441
442 switch (basicType) {
443 case GLSL_TYPE_UINT:
444 printf("%u ", v[i].u);
445 break;
446 case GLSL_TYPE_INT:
447 printf("%d ", v[i].i);
448 break;
449 case GLSL_TYPE_FLOAT:
450 printf("%g ", v[i].f);
451 break;
452 case GLSL_TYPE_DOUBLE:
453 printf("%g ", *(double* )&v[i * 2].f);
454 break;
455 default:
456 assert(!"Should not get here.");
457 break;
458 }
459 }
460 printf("\n");
461 fflush(stdout);
462 }
463
464 #if 0
465 static void
466 log_program_parameters(const struct gl_shader_program *shProg)
467 {
468 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
469 if (shProg->_LinkedShaders[i] == NULL)
470 continue;
471
472 const struct gl_program *const prog = shProg->_LinkedShaders[i]->Program;
473
474 printf("Program %d %s shader parameters:\n",
475 shProg->Name, _mesa_shader_stage_to_string(i));
476 for (unsigned j = 0; j < prog->Parameters->NumParameters; j++) {
477 printf("%s: %p %f %f %f %f\n",
478 prog->Parameters->Parameters[j].Name,
479 prog->Parameters->ParameterValues[j],
480 prog->Parameters->ParameterValues[j][0].f,
481 prog->Parameters->ParameterValues[j][1].f,
482 prog->Parameters->ParameterValues[j][2].f,
483 prog->Parameters->ParameterValues[j][3].f);
484 }
485 }
486 fflush(stdout);
487 }
488 #endif
489
490 /**
491 * Propagate some values from uniform backing storage to driver storage
492 *
493 * Values propagated from uniform backing storage to driver storage
494 * have all format / type conversions previously requested by the
495 * driver applied. This function is most often called by the
496 * implementations of \c glUniform1f, etc. and \c glUniformMatrix2f,
497 * etc.
498 *
499 * \param uni Uniform whose data is to be propagated to driver storage
500 * \param array_index If \c uni is an array, this is the element of
501 * the array to be propagated.
502 * \param count Number of array elements to propagate.
503 */
504 extern "C" void
505 _mesa_propagate_uniforms_to_driver_storage(struct gl_uniform_storage *uni,
506 unsigned array_index,
507 unsigned count)
508 {
509 unsigned i;
510
511 /* vector_elements and matrix_columns can be 0 for samplers.
512 */
513 const unsigned components = MAX2(1, uni->type->vector_elements);
514 const unsigned vectors = MAX2(1, uni->type->matrix_columns);
515 const int dmul = uni->type->base_type == GLSL_TYPE_DOUBLE ? 2 : 1;
516
517 /* Store the data in the driver's requested type in the driver's storage
518 * areas.
519 */
520 unsigned src_vector_byte_stride = components * 4 * dmul;
521
522 for (i = 0; i < uni->num_driver_storage; i++) {
523 struct gl_uniform_driver_storage *const store = &uni->driver_storage[i];
524 uint8_t *dst = (uint8_t *) store->data;
525 const unsigned extra_stride =
526 store->element_stride - (vectors * store->vector_stride);
527 const uint8_t *src =
528 (uint8_t *) (&uni->storage[array_index * (dmul * components * vectors)].i);
529
530 #if 0
531 printf("%s: %p[%d] components=%u vectors=%u count=%u vector_stride=%u "
532 "extra_stride=%u\n",
533 __func__, dst, array_index, components,
534 vectors, count, store->vector_stride, extra_stride);
535 #endif
536
537 dst += array_index * store->element_stride;
538
539 switch (store->format) {
540 case uniform_native: {
541 unsigned j;
542 unsigned v;
543
544 for (j = 0; j < count; j++) {
545 for (v = 0; v < vectors; v++) {
546 memcpy(dst, src, src_vector_byte_stride);
547 src += src_vector_byte_stride;
548 dst += store->vector_stride;
549 }
550
551 dst += extra_stride;
552 }
553 break;
554 }
555
556 case uniform_int_float: {
557 const int *isrc = (const int *) src;
558 unsigned j;
559 unsigned v;
560 unsigned c;
561
562 for (j = 0; j < count; j++) {
563 for (v = 0; v < vectors; v++) {
564 for (c = 0; c < components; c++) {
565 ((float *) dst)[c] = (float) *isrc;
566 isrc++;
567 }
568
569 dst += store->vector_stride;
570 }
571
572 dst += extra_stride;
573 }
574 break;
575 }
576
577 default:
578 assert(!"Should not get here.");
579 break;
580 }
581 }
582 }
583
584
585 /**
586 * Return printable string for a given GLSL_TYPE_x
587 */
588 static const char *
589 glsl_type_name(enum glsl_base_type type)
590 {
591 switch (type) {
592 case GLSL_TYPE_UINT:
593 return "uint";
594 case GLSL_TYPE_INT:
595 return "int";
596 case GLSL_TYPE_FLOAT:
597 return "float";
598 case GLSL_TYPE_DOUBLE:
599 return "double";
600 case GLSL_TYPE_BOOL:
601 return "bool";
602 case GLSL_TYPE_SAMPLER:
603 return "sampler";
604 case GLSL_TYPE_IMAGE:
605 return "image";
606 case GLSL_TYPE_ATOMIC_UINT:
607 return "atomic_uint";
608 case GLSL_TYPE_STRUCT:
609 return "struct";
610 case GLSL_TYPE_INTERFACE:
611 return "interface";
612 case GLSL_TYPE_ARRAY:
613 return "array";
614 case GLSL_TYPE_VOID:
615 return "void";
616 case GLSL_TYPE_ERROR:
617 return "error";
618 default:
619 return "other";
620 }
621 }
622
623
624 /**
625 * Called via glUniform*() functions.
626 */
627 extern "C" void
628 _mesa_uniform(struct gl_context *ctx, struct gl_shader_program *shProg,
629 GLint location, GLsizei count,
630 const GLvoid *values,
631 enum glsl_base_type basicType,
632 unsigned src_components)
633 {
634 unsigned offset;
635 int size_mul = basicType == GLSL_TYPE_DOUBLE ? 2 : 1;
636
637 struct gl_uniform_storage *const uni =
638 validate_uniform_parameters(ctx, shProg, location, count,
639 &offset, "glUniform");
640 if (uni == NULL)
641 return;
642
643 if (uni->type->is_matrix()) {
644 /* Can't set matrix uniforms (like mat4) with glUniform */
645 _mesa_error(ctx, GL_INVALID_OPERATION,
646 "glUniform%u(uniform \"%s\"@%d is matrix)",
647 src_components, uni->name, location);
648 return;
649 }
650
651 /* Verify that the types are compatible.
652 */
653 const unsigned components = uni->type->is_sampler()
654 ? 1 : uni->type->vector_elements;
655
656 if (components != src_components) {
657 /* glUniformN() must match float/vecN type */
658 _mesa_error(ctx, GL_INVALID_OPERATION,
659 "glUniform%u(\"%s\"@%u has %u components, not %u)",
660 src_components, uni->name, location,
661 components, src_components);
662 return;
663 }
664
665 bool match;
666 switch (uni->type->base_type) {
667 case GLSL_TYPE_BOOL:
668 match = (basicType != GLSL_TYPE_DOUBLE);
669 break;
670 case GLSL_TYPE_SAMPLER:
671 case GLSL_TYPE_IMAGE:
672 match = (basicType == GLSL_TYPE_INT);
673 break;
674 default:
675 match = (basicType == uni->type->base_type);
676 break;
677 }
678
679 if (!match) {
680 _mesa_error(ctx, GL_INVALID_OPERATION,
681 "glUniform%u(\"%s\"@%d is %s, not %s)",
682 src_components, uni->name, location,
683 glsl_type_name(uni->type->base_type),
684 glsl_type_name(basicType));
685 return;
686 }
687
688 if (unlikely(ctx->_Shader->Flags & GLSL_UNIFORMS)) {
689 log_uniform(values, basicType, components, 1, count,
690 false, shProg, location, uni);
691 }
692
693 /* Page 100 (page 116 of the PDF) of the OpenGL 3.0 spec says:
694 *
695 * "Setting a sampler's value to i selects texture image unit number
696 * i. The values of i range from zero to the implementation- dependent
697 * maximum supported number of texture image units."
698 *
699 * In addition, table 2.3, "Summary of GL errors," on page 17 (page 33 of
700 * the PDF) says:
701 *
702 * "Error Description Offending command
703 * ignored?
704 * ...
705 * INVALID_VALUE Numeric argument out of range Yes"
706 *
707 * Based on that, when an invalid sampler is specified, we generate a
708 * GL_INVALID_VALUE error and ignore the command.
709 */
710 if (uni->type->is_sampler()) {
711 for (int i = 0; i < count; i++) {
712 const unsigned texUnit = ((unsigned *) values)[i];
713
714 /* check that the sampler (tex unit index) is legal */
715 if (texUnit >= ctx->Const.MaxCombinedTextureImageUnits) {
716 _mesa_error(ctx, GL_INVALID_VALUE,
717 "glUniform1i(invalid sampler/tex unit index for "
718 "uniform %d)",
719 location);
720 return;
721 }
722 }
723 }
724
725 if (uni->type->is_image()) {
726 for (int i = 0; i < count; i++) {
727 const int unit = ((GLint *) values)[i];
728
729 /* check that the image unit is legal */
730 if (unit < 0 || unit >= (int)ctx->Const.MaxImageUnits) {
731 _mesa_error(ctx, GL_INVALID_VALUE,
732 "glUniform1i(invalid image unit index for uniform %d)",
733 location);
734 return;
735 }
736 }
737 }
738
739 /* Page 82 (page 96 of the PDF) of the OpenGL 2.1 spec says:
740 *
741 * "When loading N elements starting at an arbitrary position k in a
742 * uniform declared as an array, elements k through k + N - 1 in the
743 * array will be replaced with the new values. Values for any array
744 * element that exceeds the highest array element index used, as
745 * reported by GetActiveUniform, will be ignored by the GL."
746 *
747 * Clamp 'count' to a valid value. Note that for non-arrays a count > 1
748 * will have already generated an error.
749 */
750 if (uni->array_elements != 0) {
751 count = MIN2(count, (int) (uni->array_elements - offset));
752 }
753
754 FLUSH_VERTICES(ctx, _NEW_PROGRAM_CONSTANTS);
755
756 /* Store the data in the "actual type" backing storage for the uniform.
757 */
758 if (!uni->type->is_boolean()) {
759 memcpy(&uni->storage[size_mul * components * offset], values,
760 sizeof(uni->storage[0]) * components * count * size_mul);
761 } else {
762 const union gl_constant_value *src =
763 (const union gl_constant_value *) values;
764 union gl_constant_value *dst = &uni->storage[components * offset];
765 const unsigned elems = components * count;
766
767 for (unsigned i = 0; i < elems; i++) {
768 if (basicType == GLSL_TYPE_FLOAT) {
769 dst[i].i = src[i].f != 0.0f ? ctx->Const.UniformBooleanTrue : 0;
770 } else {
771 dst[i].i = src[i].i != 0 ? ctx->Const.UniformBooleanTrue : 0;
772 }
773 }
774 }
775
776 uni->initialized = true;
777
778 _mesa_propagate_uniforms_to_driver_storage(uni, offset, count);
779
780 /* If the uniform is a sampler, do the extra magic necessary to propagate
781 * the changes through.
782 */
783 if (uni->type->is_sampler()) {
784 bool flushed = false;
785 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
786 struct gl_shader *const sh = shProg->_LinkedShaders[i];
787
788 /* If the shader stage doesn't use the sampler uniform, skip this.
789 */
790 if (sh == NULL || !uni->sampler[i].active)
791 continue;
792
793 for (int j = 0; j < count; j++) {
794 sh->SamplerUnits[uni->sampler[i].index + offset + j] =
795 ((unsigned *) values)[j];
796 }
797
798 struct gl_program *const prog = sh->Program;
799
800 assert(sizeof(prog->SamplerUnits) == sizeof(sh->SamplerUnits));
801
802 /* Determine if any of the samplers used by this shader stage have
803 * been modified.
804 */
805 bool changed = false;
806 for (unsigned j = 0; j < ARRAY_SIZE(prog->SamplerUnits); j++) {
807 if ((sh->active_samplers & (1U << j)) != 0
808 && (prog->SamplerUnits[j] != sh->SamplerUnits[j])) {
809 changed = true;
810 break;
811 }
812 }
813
814 if (changed) {
815 if (!flushed) {
816 FLUSH_VERTICES(ctx, _NEW_TEXTURE | _NEW_PROGRAM);
817 flushed = true;
818 }
819
820 memcpy(prog->SamplerUnits,
821 sh->SamplerUnits,
822 sizeof(sh->SamplerUnits));
823
824 _mesa_update_shader_textures_used(shProg, prog);
825 if (ctx->Driver.SamplerUniformChange)
826 ctx->Driver.SamplerUniformChange(ctx, prog->Target, prog);
827 }
828 }
829 }
830
831 /* If the uniform is an image, update the mapping from image
832 * uniforms to image units present in the shader data structure.
833 */
834 if (uni->type->is_image()) {
835 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
836 if (uni->image[i].active) {
837 struct gl_shader *sh = shProg->_LinkedShaders[i];
838
839 for (int j = 0; j < count; j++)
840 sh->ImageUnits[uni->image[i].index + offset + j] =
841 ((GLint *) values)[j];
842 }
843 }
844
845 ctx->NewDriverState |= ctx->DriverFlags.NewImageUnits;
846 }
847 }
848
849 /**
850 * Called by glUniformMatrix*() functions.
851 * Note: cols=2, rows=4 ==> array[2] of vec4
852 */
853 extern "C" void
854 _mesa_uniform_matrix(struct gl_context *ctx, struct gl_shader_program *shProg,
855 GLuint cols, GLuint rows,
856 GLint location, GLsizei count,
857 GLboolean transpose,
858 const GLvoid *values, GLenum type)
859 {
860 unsigned offset;
861 unsigned vectors;
862 unsigned components;
863 unsigned elements;
864 int size_mul;
865 struct gl_uniform_storage *const uni =
866 validate_uniform_parameters(ctx, shProg, location, count,
867 &offset, "glUniformMatrix");
868 if (uni == NULL)
869 return;
870
871 if (!uni->type->is_matrix()) {
872 _mesa_error(ctx, GL_INVALID_OPERATION,
873 "glUniformMatrix(non-matrix uniform)");
874 return;
875 }
876
877 assert(type == GL_FLOAT || type == GL_DOUBLE);
878 size_mul = type == GL_DOUBLE ? 2 : 1;
879
880 assert(!uni->type->is_sampler());
881 vectors = uni->type->matrix_columns;
882 components = uni->type->vector_elements;
883
884 /* Verify that the types are compatible. This is greatly simplified for
885 * matrices because they can only have a float base type.
886 */
887 if (vectors != cols || components != rows) {
888 _mesa_error(ctx, GL_INVALID_OPERATION,
889 "glUniformMatrix(matrix size mismatch)");
890 return;
891 }
892
893 /* GL_INVALID_VALUE is generated if `transpose' is not GL_FALSE.
894 * http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml
895 */
896 if (transpose) {
897 if (ctx->API == API_OPENGLES2 && ctx->Version < 30) {
898 _mesa_error(ctx, GL_INVALID_VALUE,
899 "glUniformMatrix(matrix transpose is not GL_FALSE)");
900 return;
901 }
902 }
903
904 if (unlikely(ctx->_Shader->Flags & GLSL_UNIFORMS)) {
905 log_uniform(values, uni->type->base_type, components, vectors, count,
906 bool(transpose), shProg, location, uni);
907 }
908
909 /* Page 82 (page 96 of the PDF) of the OpenGL 2.1 spec says:
910 *
911 * "When loading N elements starting at an arbitrary position k in a
912 * uniform declared as an array, elements k through k + N - 1 in the
913 * array will be replaced with the new values. Values for any array
914 * element that exceeds the highest array element index used, as
915 * reported by GetActiveUniform, will be ignored by the GL."
916 *
917 * Clamp 'count' to a valid value. Note that for non-arrays a count > 1
918 * will have already generated an error.
919 */
920 if (uni->array_elements != 0) {
921 count = MIN2(count, (int) (uni->array_elements - offset));
922 }
923
924 FLUSH_VERTICES(ctx, _NEW_PROGRAM_CONSTANTS);
925
926 /* Store the data in the "actual type" backing storage for the uniform.
927 */
928 elements = components * vectors;
929
930 if (!transpose) {
931 memcpy(&uni->storage[elements * offset], values,
932 sizeof(uni->storage[0]) * elements * count * size_mul);
933 } else if (type == GL_FLOAT) {
934 /* Copy and transpose the matrix.
935 */
936 const float *src = (const float *)values;
937 float *dst = &uni->storage[elements * offset].f;
938
939 for (int i = 0; i < count; i++) {
940 for (unsigned r = 0; r < rows; r++) {
941 for (unsigned c = 0; c < cols; c++) {
942 dst[(c * components) + r] = src[c + (r * vectors)];
943 }
944 }
945
946 dst += elements;
947 src += elements;
948 }
949 } else {
950 assert(type == GL_DOUBLE);
951 const double *src = (const double *)values;
952 double *dst = (double *)&uni->storage[elements * offset].f;
953
954 for (int i = 0; i < count; i++) {
955 for (unsigned r = 0; r < rows; r++) {
956 for (unsigned c = 0; c < cols; c++) {
957 dst[(c * components) + r] = src[c + (r * vectors)];
958 }
959 }
960
961 dst += elements;
962 src += elements;
963 }
964 }
965
966 uni->initialized = true;
967
968 _mesa_propagate_uniforms_to_driver_storage(uni, offset, count);
969 }
970
971
972 /**
973 * Called via glGetUniformLocation().
974 *
975 * Returns the uniform index into UniformStorage (also the
976 * glGetActiveUniformsiv uniform index), and stores the referenced
977 * array offset in *offset, or GL_INVALID_INDEX (-1).
978 */
979 extern "C" unsigned
980 _mesa_get_uniform_location(struct gl_shader_program *shProg,
981 const GLchar *name,
982 unsigned *out_offset)
983 {
984 /* Page 80 (page 94 of the PDF) of the OpenGL 2.1 spec says:
985 *
986 * "The first element of a uniform array is identified using the
987 * name of the uniform array appended with "[0]". Except if the last
988 * part of the string name indicates a uniform array, then the
989 * location of the first element of that array can be retrieved by
990 * either using the name of the uniform array, or the name of the
991 * uniform array appended with "[0]"."
992 *
993 * Note: since uniform names are not allowed to use whitespace, and array
994 * indices within uniform names are not allowed to use "+", "-", or leading
995 * zeros, it follows that each uniform has a unique name up to the possible
996 * ambiguity with "[0]" noted above. Therefore we don't need to worry
997 * about mal-formed inputs--they will properly fail when we try to look up
998 * the uniform name in shProg->UniformHash.
999 */
1000
1001 const GLchar *base_name_end;
1002 long offset = parse_program_resource_name(name, &base_name_end);
1003 bool array_lookup = offset >= 0;
1004 char *name_copy;
1005
1006 if (array_lookup) {
1007 name_copy = (char *) malloc(base_name_end - name + 1);
1008 memcpy(name_copy, name, base_name_end - name);
1009 name_copy[base_name_end - name] = '\0';
1010 } else {
1011 name_copy = (char *) name;
1012 offset = 0;
1013 }
1014
1015 unsigned location = 0;
1016 const bool found = shProg->UniformHash->get(location, name_copy);
1017
1018 assert(!found
1019 || strcmp(name_copy, shProg->UniformStorage[location].name) == 0);
1020
1021 /* Free the temporary buffer *before* possibly returning an error.
1022 */
1023 if (name_copy != name)
1024 free(name_copy);
1025
1026 if (!found)
1027 return GL_INVALID_INDEX;
1028
1029 /* If the uniform is an array, fail if the index is out of bounds.
1030 * (A negative index is caught above.) This also fails if the uniform
1031 * is not an array, but the user is trying to index it, because
1032 * array_elements is zero and offset >= 0.
1033 */
1034 if (array_lookup
1035 && offset >= (long) shProg->UniformStorage[location].array_elements) {
1036 return GL_INVALID_INDEX;
1037 }
1038
1039 *out_offset = offset;
1040 return location;
1041 }
1042
1043 extern "C" bool
1044 _mesa_sampler_uniforms_are_valid(const struct gl_shader_program *shProg,
1045 char *errMsg, size_t errMsgLength)
1046 {
1047 /* Shader does not have samplers. */
1048 if (shProg->NumUserUniformStorage == 0)
1049 return true;
1050
1051 if (!shProg->SamplersValidated) {
1052 _mesa_snprintf(errMsg, errMsgLength,
1053 "active samplers with a different type "
1054 "refer to the same texture image unit");
1055 return false;
1056 }
1057 return true;
1058 }
1059
1060 extern "C" bool
1061 _mesa_sampler_uniforms_pipeline_are_valid(struct gl_pipeline_object *pipeline)
1062 {
1063 /* Section 2.11.11 (Shader Execution), subheading "Validation," of the
1064 * OpenGL 4.1 spec says:
1065 *
1066 * "[INVALID_OPERATION] is generated by any command that transfers
1067 * vertices to the GL if:
1068 *
1069 * ...
1070 *
1071 * - Any two active samplers in the current program object are of
1072 * different types, but refer to the same texture image unit.
1073 *
1074 * - The number of active samplers in the program exceeds the
1075 * maximum number of texture image units allowed."
1076 */
1077 unsigned active_samplers = 0;
1078 const struct gl_shader_program **shProg =
1079 (const struct gl_shader_program **) pipeline->CurrentProgram;
1080
1081 const glsl_type *unit_types[MAX_COMBINED_TEXTURE_IMAGE_UNITS];
1082 memset(unit_types, 0, sizeof(unit_types));
1083
1084 for (unsigned idx = 0; idx < ARRAY_SIZE(pipeline->CurrentProgram); idx++) {
1085 if (!shProg[idx])
1086 continue;
1087
1088 for (unsigned i = 0; i < shProg[idx]->NumUserUniformStorage; i++) {
1089 const struct gl_uniform_storage *const storage =
1090 &shProg[idx]->UniformStorage[i];
1091 const glsl_type *const t = (storage->type->is_array())
1092 ? storage->type->fields.array : storage->type;
1093
1094 if (!t->is_sampler())
1095 continue;
1096
1097 active_samplers++;
1098
1099 const unsigned count = MAX2(1, storage->type->array_size());
1100 for (unsigned j = 0; j < count; j++) {
1101 const unsigned unit = storage->storage[j].i;
1102
1103 /* The types of the samplers associated with a particular texture
1104 * unit must be an exact match. Page 74 (page 89 of the PDF) of
1105 * the OpenGL 3.3 core spec says:
1106 *
1107 * "It is not allowed to have variables of different sampler
1108 * types pointing to the same texture image unit within a
1109 * program object."
1110 */
1111 if (unit_types[unit] == NULL) {
1112 unit_types[unit] = t;
1113 } else if (unit_types[unit] != t) {
1114 pipeline->InfoLog =
1115 ralloc_asprintf(pipeline,
1116 "Texture unit %d is accessed both as %s "
1117 "and %s",
1118 unit, unit_types[unit]->name, t->name);
1119 return false;
1120 }
1121 }
1122 }
1123 }
1124
1125 if (active_samplers > MAX_COMBINED_TEXTURE_IMAGE_UNITS) {
1126 pipeline->InfoLog =
1127 ralloc_asprintf(pipeline,
1128 "the number of active samplers %d exceed the "
1129 "maximum %d",
1130 active_samplers, MAX_COMBINED_TEXTURE_IMAGE_UNITS);
1131 return false;
1132 }
1133
1134 return true;
1135 }