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