main: memcpy larger chunks in _mesa_propagate_uniforms_to_driver_storage
[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 "main/shaderapi.h"
32 #include "main/shaderobj.h"
33 #include "main/uniforms.h"
34 #include "compiler/glsl/ir.h"
35 #include "compiler/glsl/ir_uniform.h"
36 #include "compiler/glsl/glsl_parser_extras.h"
37 #include "compiler/glsl/program.h"
38 #include "program/hash_table.h"
39 #include "util/bitscan.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 /* Even though no location is assigned to a built-in uniform and this
241 * function should already have returned NULL, this test makes it explicit
242 * that we are not allowing to update the value of a built-in.
243 */
244 if (uni->builtin)
245 return NULL;
246
247 if (uni->array_elements == 0) {
248 if (count > 1) {
249 _mesa_error(ctx, GL_INVALID_OPERATION,
250 "%s(count = %u for non-array \"%s\"@%d)",
251 caller, count, uni->name, location);
252 return NULL;
253 }
254
255 assert((location - uni->remap_location) == 0);
256 *array_index = 0;
257 } else {
258 /* The array index specified by the uniform location is just the uniform
259 * location minus the base location of of the uniform.
260 */
261 *array_index = location - uni->remap_location;
262
263 /* If the uniform is an array, check that array_index is in bounds.
264 * array_index is unsigned so no need to check for less than zero.
265 */
266 if (*array_index >= uni->array_elements) {
267 _mesa_error(ctx, GL_INVALID_OPERATION, "%s(location=%d)",
268 caller, location);
269 return NULL;
270 }
271 }
272 return uni;
273 }
274
275 /**
276 * Called via glGetUniform[fiui]v() to get the current value of a uniform.
277 */
278 extern "C" void
279 _mesa_get_uniform(struct gl_context *ctx, GLuint program, GLint location,
280 GLsizei bufSize, enum glsl_base_type returnType,
281 GLvoid *paramsOut)
282 {
283 struct gl_shader_program *shProg =
284 _mesa_lookup_shader_program_err(ctx, program, "glGetUniformfv");
285 unsigned offset;
286
287 struct gl_uniform_storage *const uni =
288 validate_uniform_parameters(ctx, shProg, location, 1,
289 &offset, "glGetUniform");
290 if (uni == NULL) {
291 /* For glGetUniform, page 264 (page 278 of the PDF) of the OpenGL 2.1
292 * spec says:
293 *
294 * "The error INVALID_OPERATION is generated if program has not been
295 * linked successfully, or if location is not a valid location for
296 * program."
297 *
298 * For glUniform, page 82 (page 96 of the PDF) of the OpenGL 2.1 spec
299 * says:
300 *
301 * "If the value of location is -1, the Uniform* commands will
302 * silently ignore the data passed in, and the current uniform
303 * values will not be changed."
304 *
305 * Allowing -1 for the location parameter of glUniform allows
306 * applications to avoid error paths in the case that, for example, some
307 * uniform variable is removed by the compiler / linker after
308 * optimization. In this case, the new value of the uniform is dropped
309 * on the floor. For the case of glGetUniform, there is nothing
310 * sensible to do for a location of -1.
311 *
312 * If the location was -1, validate_unfirom_parameters will return NULL
313 * without raising an error. Raise the error here.
314 */
315 if (location == -1) {
316 _mesa_error(ctx, GL_INVALID_OPERATION, "glGetUniform(location=%d)",
317 location);
318 }
319
320 return;
321 }
322
323 {
324 unsigned elements = (uni->type->is_sampler())
325 ? 1 : uni->type->components();
326 const int dmul = uni->type->is_64bit() ? 2 : 1;
327 const int rmul = glsl_base_type_is_64bit(returnType) ? 2 : 1;
328
329 /* Calculate the source base address *BEFORE* modifying elements to
330 * account for the size of the user's buffer.
331 */
332 const union gl_constant_value *const src =
333 &uni->storage[offset * elements * dmul];
334
335 assert(returnType == GLSL_TYPE_FLOAT || returnType == GLSL_TYPE_INT ||
336 returnType == GLSL_TYPE_UINT || returnType == GLSL_TYPE_DOUBLE);
337
338 /* doubles have a different size than the other 3 types */
339 unsigned bytes = sizeof(src[0]) * elements * rmul;
340 if (bufSize < 0 || bytes > (unsigned) bufSize) {
341 _mesa_error( ctx, GL_INVALID_OPERATION,
342 "glGetnUniform*vARB(out of bounds: bufSize is %d,"
343 " but %u bytes are required)", bufSize, bytes );
344 return;
345 }
346
347 /* If the return type and the uniform's native type are "compatible,"
348 * just memcpy the data. If the types are not compatible, perform a
349 * slower convert-and-copy process.
350 */
351 if (returnType == uni->type->base_type
352 || ((returnType == GLSL_TYPE_INT
353 || returnType == GLSL_TYPE_UINT)
354 &&
355 (uni->type->base_type == GLSL_TYPE_INT
356 || uni->type->base_type == GLSL_TYPE_UINT
357 || uni->type->base_type == GLSL_TYPE_SAMPLER
358 || uni->type->base_type == GLSL_TYPE_IMAGE))) {
359 memcpy(paramsOut, src, bytes);
360 } else {
361 union gl_constant_value *const dst =
362 (union gl_constant_value *) paramsOut;
363 /* This code could be optimized by putting the loop inside the switch
364 * statements. However, this is not expected to be
365 * performance-critical code.
366 */
367 for (unsigned i = 0; i < elements; i++) {
368 int sidx = i * dmul;
369 int didx = i * rmul;
370
371 switch (returnType) {
372 case GLSL_TYPE_FLOAT:
373 switch (uni->type->base_type) {
374 case GLSL_TYPE_UINT:
375 dst[didx].f = (float) src[sidx].u;
376 break;
377 case GLSL_TYPE_INT:
378 case GLSL_TYPE_SAMPLER:
379 case GLSL_TYPE_IMAGE:
380 dst[didx].f = (float) src[sidx].i;
381 break;
382 case GLSL_TYPE_BOOL:
383 dst[didx].f = src[sidx].i ? 1.0f : 0.0f;
384 break;
385 case GLSL_TYPE_DOUBLE:
386 dst[didx].f = *(double *)&src[sidx].f;
387 break;
388 default:
389 assert(!"Should not get here.");
390 break;
391 }
392 break;
393 case GLSL_TYPE_DOUBLE:
394 switch (uni->type->base_type) {
395 case GLSL_TYPE_UINT:
396 *(double *)&dst[didx].f = (double) src[sidx].u;
397 break;
398 case GLSL_TYPE_INT:
399 case GLSL_TYPE_SAMPLER:
400 case GLSL_TYPE_IMAGE:
401 *(double *)&dst[didx].f = (double) src[sidx].i;
402 break;
403 case GLSL_TYPE_BOOL:
404 *(double *)&dst[didx].f = src[sidx].i ? 1.0f : 0.0f;
405 break;
406 case GLSL_TYPE_FLOAT:
407 *(double *)&dst[didx].f = (double) src[sidx].f;
408 break;
409 default:
410 assert(!"Should not get here.");
411 break;
412 }
413 break;
414 case GLSL_TYPE_INT:
415 case GLSL_TYPE_UINT:
416 switch (uni->type->base_type) {
417 case GLSL_TYPE_FLOAT:
418 /* While the GL 3.2 core spec doesn't explicitly
419 * state how conversion of float uniforms to integer
420 * values works, in section 6.2 "State Tables" on
421 * page 267 it says:
422 *
423 * "Unless otherwise specified, when floating
424 * point state is returned as integer values or
425 * integer state is returned as floating-point
426 * values it is converted in the fashion
427 * described in section 6.1.2"
428 *
429 * That section, on page 248, says:
430 *
431 * "If GetIntegerv or GetInteger64v are called,
432 * a floating-point value is rounded to the
433 * nearest integer..."
434 */
435 dst[didx].i = IROUND(src[sidx].f);
436 break;
437 case GLSL_TYPE_BOOL:
438 dst[didx].i = src[sidx].i ? 1 : 0;
439 break;
440 case GLSL_TYPE_DOUBLE:
441 dst[didx].i = IROUNDD(*(double *)&src[sidx].f);
442 break;
443 default:
444 assert(!"Should not get here.");
445 break;
446 }
447 break;
448
449 default:
450 assert(!"Should not get here.");
451 break;
452 }
453 }
454 }
455 }
456 }
457
458 static void
459 log_uniform(const void *values, enum glsl_base_type basicType,
460 unsigned rows, unsigned cols, unsigned count,
461 bool transpose,
462 const struct gl_shader_program *shProg,
463 GLint location,
464 const struct gl_uniform_storage *uni)
465 {
466
467 const union gl_constant_value *v = (const union gl_constant_value *) values;
468 const unsigned elems = rows * cols * count;
469 const char *const extra = (cols == 1) ? "uniform" : "uniform matrix";
470
471 printf("Mesa: set program %u %s \"%s\" (loc %d, type \"%s\", "
472 "transpose = %s) to: ",
473 shProg->Name, extra, uni->name, location, uni->type->name,
474 transpose ? "true" : "false");
475 for (unsigned i = 0; i < elems; i++) {
476 if (i != 0 && ((i % rows) == 0))
477 printf(", ");
478
479 switch (basicType) {
480 case GLSL_TYPE_UINT:
481 printf("%u ", v[i].u);
482 break;
483 case GLSL_TYPE_INT:
484 printf("%d ", v[i].i);
485 break;
486 case GLSL_TYPE_FLOAT:
487 printf("%g ", v[i].f);
488 break;
489 case GLSL_TYPE_DOUBLE:
490 printf("%g ", *(double* )&v[i * 2].f);
491 break;
492 default:
493 assert(!"Should not get here.");
494 break;
495 }
496 }
497 printf("\n");
498 fflush(stdout);
499 }
500
501 #if 0
502 static void
503 log_program_parameters(const struct gl_shader_program *shProg)
504 {
505 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
506 if (shProg->_LinkedShaders[i] == NULL)
507 continue;
508
509 const struct gl_program *const prog = shProg->_LinkedShaders[i]->Program;
510
511 printf("Program %d %s shader parameters:\n",
512 shProg->Name, _mesa_shader_stage_to_string(i));
513 for (unsigned j = 0; j < prog->Parameters->NumParameters; j++) {
514 printf("%s: %p %f %f %f %f\n",
515 prog->Parameters->Parameters[j].Name,
516 prog->Parameters->ParameterValues[j],
517 prog->Parameters->ParameterValues[j][0].f,
518 prog->Parameters->ParameterValues[j][1].f,
519 prog->Parameters->ParameterValues[j][2].f,
520 prog->Parameters->ParameterValues[j][3].f);
521 }
522 }
523 fflush(stdout);
524 }
525 #endif
526
527 /**
528 * Propagate some values from uniform backing storage to driver storage
529 *
530 * Values propagated from uniform backing storage to driver storage
531 * have all format / type conversions previously requested by the
532 * driver applied. This function is most often called by the
533 * implementations of \c glUniform1f, etc. and \c glUniformMatrix2f,
534 * etc.
535 *
536 * \param uni Uniform whose data is to be propagated to driver storage
537 * \param array_index If \c uni is an array, this is the element of
538 * the array to be propagated.
539 * \param count Number of array elements to propagate.
540 */
541 extern "C" void
542 _mesa_propagate_uniforms_to_driver_storage(struct gl_uniform_storage *uni,
543 unsigned array_index,
544 unsigned count)
545 {
546 unsigned i;
547
548 /* vector_elements and matrix_columns can be 0 for samplers.
549 */
550 const unsigned components = MAX2(1, uni->type->vector_elements);
551 const unsigned vectors = MAX2(1, uni->type->matrix_columns);
552 const int dmul = uni->type->is_64bit() ? 2 : 1;
553
554 /* Store the data in the driver's requested type in the driver's storage
555 * areas.
556 */
557 unsigned src_vector_byte_stride = components * 4 * dmul;
558
559 for (i = 0; i < uni->num_driver_storage; i++) {
560 struct gl_uniform_driver_storage *const store = &uni->driver_storage[i];
561 uint8_t *dst = (uint8_t *) store->data;
562 const unsigned extra_stride =
563 store->element_stride - (vectors * store->vector_stride);
564 const uint8_t *src =
565 (uint8_t *) (&uni->storage[array_index * (dmul * components * vectors)].i);
566
567 #if 0
568 printf("%s: %p[%d] components=%u vectors=%u count=%u vector_stride=%u "
569 "extra_stride=%u\n",
570 __func__, dst, array_index, components,
571 vectors, count, store->vector_stride, extra_stride);
572 #endif
573
574 dst += array_index * store->element_stride;
575
576 switch (store->format) {
577 case uniform_native: {
578 unsigned j;
579 unsigned v;
580
581 if (src_vector_byte_stride == store->vector_stride) {
582 if (extra_stride) {
583 for (j = 0; j < count; j++) {
584 memcpy(dst, src, src_vector_byte_stride * vectors);
585 src += src_vector_byte_stride * vectors;
586 dst += store->vector_stride * vectors;
587
588 dst += extra_stride;
589 }
590 } else {
591 /* Unigine Heaven benchmark gets here */
592 memcpy(dst, src, src_vector_byte_stride * vectors * count);
593 src += src_vector_byte_stride * vectors * count;
594 dst += store->vector_stride * vectors * count;
595 }
596 } else {
597 for (j = 0; j < count; j++) {
598 for (v = 0; v < vectors; v++) {
599 memcpy(dst, src, src_vector_byte_stride);
600 src += src_vector_byte_stride;
601 dst += store->vector_stride;
602 }
603
604 dst += extra_stride;
605 }
606 }
607 break;
608 }
609
610 case uniform_int_float: {
611 const int *isrc = (const int *) src;
612 unsigned j;
613 unsigned v;
614 unsigned c;
615
616 for (j = 0; j < count; j++) {
617 for (v = 0; v < vectors; v++) {
618 for (c = 0; c < components; c++) {
619 ((float *) dst)[c] = (float) *isrc;
620 isrc++;
621 }
622
623 dst += store->vector_stride;
624 }
625
626 dst += extra_stride;
627 }
628 break;
629 }
630
631 default:
632 assert(!"Should not get here.");
633 break;
634 }
635 }
636 }
637
638
639 /**
640 * Return printable string for a given GLSL_TYPE_x
641 */
642 static const char *
643 glsl_type_name(enum glsl_base_type type)
644 {
645 switch (type) {
646 case GLSL_TYPE_UINT:
647 return "uint";
648 case GLSL_TYPE_INT:
649 return "int";
650 case GLSL_TYPE_FLOAT:
651 return "float";
652 case GLSL_TYPE_DOUBLE:
653 return "double";
654 case GLSL_TYPE_BOOL:
655 return "bool";
656 case GLSL_TYPE_SAMPLER:
657 return "sampler";
658 case GLSL_TYPE_IMAGE:
659 return "image";
660 case GLSL_TYPE_ATOMIC_UINT:
661 return "atomic_uint";
662 case GLSL_TYPE_STRUCT:
663 return "struct";
664 case GLSL_TYPE_INTERFACE:
665 return "interface";
666 case GLSL_TYPE_ARRAY:
667 return "array";
668 case GLSL_TYPE_VOID:
669 return "void";
670 case GLSL_TYPE_ERROR:
671 return "error";
672 default:
673 return "other";
674 }
675 }
676
677
678 /**
679 * Called via glUniform*() functions.
680 */
681 extern "C" void
682 _mesa_uniform(struct gl_context *ctx, struct gl_shader_program *shProg,
683 GLint location, GLsizei count,
684 const GLvoid *values,
685 enum glsl_base_type basicType,
686 unsigned src_components)
687 {
688 unsigned offset;
689 int size_mul = glsl_base_type_is_64bit(basicType) ? 2 : 1;
690
691 struct gl_uniform_storage *const uni =
692 validate_uniform_parameters(ctx, shProg, location, count,
693 &offset, "glUniform");
694 if (uni == NULL)
695 return;
696
697 if (uni->type->is_matrix()) {
698 /* Can't set matrix uniforms (like mat4) with glUniform */
699 _mesa_error(ctx, GL_INVALID_OPERATION,
700 "glUniform%u(uniform \"%s\"@%d is matrix)",
701 src_components, uni->name, location);
702 return;
703 }
704
705 /* Verify that the types are compatible.
706 */
707 const unsigned components = uni->type->is_sampler()
708 ? 1 : uni->type->vector_elements;
709
710 if (components != src_components) {
711 /* glUniformN() must match float/vecN type */
712 _mesa_error(ctx, GL_INVALID_OPERATION,
713 "glUniform%u(\"%s\"@%u has %u components, not %u)",
714 src_components, uni->name, location,
715 components, src_components);
716 return;
717 }
718
719 bool match;
720 switch (uni->type->base_type) {
721 case GLSL_TYPE_BOOL:
722 match = (basicType != GLSL_TYPE_DOUBLE);
723 break;
724 case GLSL_TYPE_SAMPLER:
725 match = (basicType == GLSL_TYPE_INT);
726 break;
727 case GLSL_TYPE_IMAGE:
728 match = (basicType == GLSL_TYPE_INT && _mesa_is_desktop_gl(ctx));
729 break;
730 default:
731 match = (basicType == uni->type->base_type);
732 break;
733 }
734
735 if (!match) {
736 _mesa_error(ctx, GL_INVALID_OPERATION,
737 "glUniform%u(\"%s\"@%d is %s, not %s)",
738 src_components, uni->name, location,
739 glsl_type_name(uni->type->base_type),
740 glsl_type_name(basicType));
741 return;
742 }
743
744 if (unlikely(ctx->_Shader->Flags & GLSL_UNIFORMS)) {
745 log_uniform(values, basicType, components, 1, count,
746 false, shProg, location, uni);
747 }
748
749 /* Page 100 (page 116 of the PDF) of the OpenGL 3.0 spec says:
750 *
751 * "Setting a sampler's value to i selects texture image unit number
752 * i. The values of i range from zero to the implementation- dependent
753 * maximum supported number of texture image units."
754 *
755 * In addition, table 2.3, "Summary of GL errors," on page 17 (page 33 of
756 * the PDF) says:
757 *
758 * "Error Description Offending command
759 * ignored?
760 * ...
761 * INVALID_VALUE Numeric argument out of range Yes"
762 *
763 * Based on that, when an invalid sampler is specified, we generate a
764 * GL_INVALID_VALUE error and ignore the command.
765 */
766 if (uni->type->is_sampler()) {
767 for (int i = 0; i < count; i++) {
768 const unsigned texUnit = ((unsigned *) values)[i];
769
770 /* check that the sampler (tex unit index) is legal */
771 if (texUnit >= ctx->Const.MaxCombinedTextureImageUnits) {
772 _mesa_error(ctx, GL_INVALID_VALUE,
773 "glUniform1i(invalid sampler/tex unit index for "
774 "uniform %d)",
775 location);
776 return;
777 }
778 }
779 /* We need to reset the validate flag on changes to samplers in case
780 * two different sampler types are set to the same texture unit.
781 */
782 ctx->_Shader->Validated = GL_FALSE;
783 }
784
785 if (uni->type->is_image()) {
786 for (int i = 0; i < count; i++) {
787 const int unit = ((GLint *) values)[i];
788
789 /* check that the image unit is legal */
790 if (unit < 0 || unit >= (int)ctx->Const.MaxImageUnits) {
791 _mesa_error(ctx, GL_INVALID_VALUE,
792 "glUniform1i(invalid image unit index for uniform %d)",
793 location);
794 return;
795 }
796 }
797 }
798
799 /* Page 82 (page 96 of the PDF) of the OpenGL 2.1 spec says:
800 *
801 * "When loading N elements starting at an arbitrary position k in a
802 * uniform declared as an array, elements k through k + N - 1 in the
803 * array will be replaced with the new values. Values for any array
804 * element that exceeds the highest array element index used, as
805 * reported by GetActiveUniform, will be ignored by the GL."
806 *
807 * Clamp 'count' to a valid value. Note that for non-arrays a count > 1
808 * will have already generated an error.
809 */
810 if (uni->array_elements != 0) {
811 count = MIN2(count, (int) (uni->array_elements - offset));
812 }
813
814 FLUSH_VERTICES(ctx, _NEW_PROGRAM_CONSTANTS);
815
816 /* Store the data in the "actual type" backing storage for the uniform.
817 */
818 if (!uni->type->is_boolean()) {
819 memcpy(&uni->storage[size_mul * components * offset], values,
820 sizeof(uni->storage[0]) * components * count * size_mul);
821 } else {
822 const union gl_constant_value *src =
823 (const union gl_constant_value *) values;
824 union gl_constant_value *dst = &uni->storage[components * offset];
825 const unsigned elems = components * count;
826
827 for (unsigned i = 0; i < elems; i++) {
828 if (basicType == GLSL_TYPE_FLOAT) {
829 dst[i].i = src[i].f != 0.0f ? ctx->Const.UniformBooleanTrue : 0;
830 } else {
831 dst[i].i = src[i].i != 0 ? ctx->Const.UniformBooleanTrue : 0;
832 }
833 }
834 }
835
836 _mesa_propagate_uniforms_to_driver_storage(uni, offset, count);
837
838 /* If the uniform is a sampler, do the extra magic necessary to propagate
839 * the changes through.
840 */
841 if (uni->type->is_sampler()) {
842 bool flushed = false;
843 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
844 struct gl_linked_shader *const sh = shProg->_LinkedShaders[i];
845
846 /* If the shader stage doesn't use the sampler uniform, skip this.
847 */
848 if (sh == NULL || !uni->opaque[i].active)
849 continue;
850
851 for (int j = 0; j < count; j++) {
852 sh->SamplerUnits[uni->opaque[i].index + offset + j] =
853 ((unsigned *) values)[j];
854 }
855
856 struct gl_program *const prog = sh->Program;
857
858 assert(sizeof(prog->SamplerUnits) == sizeof(sh->SamplerUnits));
859
860 /* Determine if any of the samplers used by this shader stage have
861 * been modified.
862 */
863 bool changed = false;
864 GLbitfield mask = sh->active_samplers;
865 while (mask) {
866 const int j = u_bit_scan(&mask);
867 if (prog->SamplerUnits[j] != sh->SamplerUnits[j]) {
868 changed = true;
869 break;
870 }
871 }
872
873 if (changed) {
874 if (!flushed) {
875 FLUSH_VERTICES(ctx, _NEW_TEXTURE | _NEW_PROGRAM);
876 flushed = true;
877 }
878
879 _mesa_update_shader_textures_used(shProg, prog);
880 if (ctx->Driver.SamplerUniformChange)
881 ctx->Driver.SamplerUniformChange(ctx, prog->Target, prog);
882 }
883 }
884 }
885
886 /* If the uniform is an image, update the mapping from image
887 * uniforms to image units present in the shader data structure.
888 */
889 if (uni->type->is_image()) {
890 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
891 if (uni->opaque[i].active) {
892 struct gl_linked_shader *sh = shProg->_LinkedShaders[i];
893
894 for (int j = 0; j < count; j++)
895 sh->ImageUnits[uni->opaque[i].index + offset + j] =
896 ((GLint *) values)[j];
897 }
898 }
899
900 ctx->NewDriverState |= ctx->DriverFlags.NewImageUnits;
901 }
902 }
903
904 /**
905 * Called by glUniformMatrix*() functions.
906 * Note: cols=2, rows=4 ==> array[2] of vec4
907 */
908 extern "C" void
909 _mesa_uniform_matrix(struct gl_context *ctx, struct gl_shader_program *shProg,
910 GLuint cols, GLuint rows,
911 GLint location, GLsizei count,
912 GLboolean transpose,
913 const GLvoid *values, enum glsl_base_type basicType)
914 {
915 unsigned offset;
916 unsigned vectors;
917 unsigned components;
918 unsigned elements;
919 int size_mul;
920 struct gl_uniform_storage *const uni =
921 validate_uniform_parameters(ctx, shProg, location, count,
922 &offset, "glUniformMatrix");
923 if (uni == NULL)
924 return;
925
926 if (!uni->type->is_matrix()) {
927 _mesa_error(ctx, GL_INVALID_OPERATION,
928 "glUniformMatrix(non-matrix uniform)");
929 return;
930 }
931
932 assert(basicType == GLSL_TYPE_FLOAT || basicType == GLSL_TYPE_DOUBLE);
933 size_mul = basicType == GLSL_TYPE_DOUBLE ? 2 : 1;
934
935 assert(!uni->type->is_sampler());
936 vectors = uni->type->matrix_columns;
937 components = uni->type->vector_elements;
938
939 /* Verify that the types are compatible. This is greatly simplified for
940 * matrices because they can only have a float base type.
941 */
942 if (vectors != cols || components != rows) {
943 _mesa_error(ctx, GL_INVALID_OPERATION,
944 "glUniformMatrix(matrix size mismatch)");
945 return;
946 }
947
948 /* GL_INVALID_VALUE is generated if `transpose' is not GL_FALSE.
949 * http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml
950 */
951 if (transpose) {
952 if (ctx->API == API_OPENGLES2 && ctx->Version < 30) {
953 _mesa_error(ctx, GL_INVALID_VALUE,
954 "glUniformMatrix(matrix transpose is not GL_FALSE)");
955 return;
956 }
957 }
958
959 /* Section 2.11.7 (Uniform Variables) of the OpenGL 4.2 Core Profile spec
960 * says:
961 *
962 * "If any of the following conditions occur, an INVALID_OPERATION
963 * error is generated by the Uniform* commands, and no uniform values
964 * are changed:
965 *
966 * ...
967 *
968 * - if the uniform declared in the shader is not of type boolean and
969 * the type indicated in the name of the Uniform* command used does
970 * not match the type of the uniform"
971 *
972 * There are no Boolean matrix types, so we do not need to allow
973 * GLSL_TYPE_BOOL here (as _mesa_uniform does).
974 */
975 if (uni->type->base_type != basicType) {
976 _mesa_error(ctx, GL_INVALID_OPERATION,
977 "glUniformMatrix%ux%u(\"%s\"@%d is %s, not %s)",
978 cols, rows, uni->name, location,
979 glsl_type_name(uni->type->base_type),
980 glsl_type_name(basicType));
981 return;
982 }
983
984 if (unlikely(ctx->_Shader->Flags & GLSL_UNIFORMS)) {
985 log_uniform(values, uni->type->base_type, components, vectors, count,
986 bool(transpose), shProg, location, uni);
987 }
988
989 /* Page 82 (page 96 of the PDF) of the OpenGL 2.1 spec says:
990 *
991 * "When loading N elements starting at an arbitrary position k in a
992 * uniform declared as an array, elements k through k + N - 1 in the
993 * array will be replaced with the new values. Values for any array
994 * element that exceeds the highest array element index used, as
995 * reported by GetActiveUniform, will be ignored by the GL."
996 *
997 * Clamp 'count' to a valid value. Note that for non-arrays a count > 1
998 * will have already generated an error.
999 */
1000 if (uni->array_elements != 0) {
1001 count = MIN2(count, (int) (uni->array_elements - offset));
1002 }
1003
1004 FLUSH_VERTICES(ctx, _NEW_PROGRAM_CONSTANTS);
1005
1006 /* Store the data in the "actual type" backing storage for the uniform.
1007 */
1008 elements = components * vectors;
1009
1010 if (!transpose) {
1011 memcpy(&uni->storage[size_mul * elements * offset], values,
1012 sizeof(uni->storage[0]) * elements * count * size_mul);
1013 } else if (basicType == GLSL_TYPE_FLOAT) {
1014 /* Copy and transpose the matrix.
1015 */
1016 const float *src = (const float *)values;
1017 float *dst = &uni->storage[elements * offset].f;
1018
1019 for (int i = 0; i < count; i++) {
1020 for (unsigned r = 0; r < rows; r++) {
1021 for (unsigned c = 0; c < cols; c++) {
1022 dst[(c * components) + r] = src[c + (r * vectors)];
1023 }
1024 }
1025
1026 dst += elements;
1027 src += elements;
1028 }
1029 } else {
1030 assert(basicType == GLSL_TYPE_DOUBLE);
1031 const double *src = (const double *)values;
1032 double *dst = (double *)&uni->storage[elements * offset].f;
1033
1034 for (int i = 0; i < count; i++) {
1035 for (unsigned r = 0; r < rows; r++) {
1036 for (unsigned c = 0; c < cols; c++) {
1037 dst[(c * components) + r] = src[c + (r * vectors)];
1038 }
1039 }
1040
1041 dst += elements;
1042 src += elements;
1043 }
1044 }
1045
1046 _mesa_propagate_uniforms_to_driver_storage(uni, offset, count);
1047 }
1048
1049
1050 extern "C" bool
1051 _mesa_sampler_uniforms_are_valid(const struct gl_shader_program *shProg,
1052 char *errMsg, size_t errMsgLength)
1053 {
1054 /* Shader does not have samplers. */
1055 if (shProg->NumUniformStorage == 0)
1056 return true;
1057
1058 if (!shProg->SamplersValidated) {
1059 _mesa_snprintf(errMsg, errMsgLength,
1060 "active samplers with a different type "
1061 "refer to the same texture image unit");
1062 return false;
1063 }
1064 return true;
1065 }
1066
1067 extern "C" bool
1068 _mesa_sampler_uniforms_pipeline_are_valid(struct gl_pipeline_object *pipeline)
1069 {
1070 /* Section 2.11.11 (Shader Execution), subheading "Validation," of the
1071 * OpenGL 4.1 spec says:
1072 *
1073 * "[INVALID_OPERATION] is generated by any command that transfers
1074 * vertices to the GL if:
1075 *
1076 * ...
1077 *
1078 * - Any two active samplers in the current program object are of
1079 * different types, but refer to the same texture image unit.
1080 *
1081 * - The number of active samplers in the program exceeds the
1082 * maximum number of texture image units allowed."
1083 */
1084
1085 GLbitfield mask;
1086 GLbitfield TexturesUsed[MAX_COMBINED_TEXTURE_IMAGE_UNITS];
1087 struct gl_linked_shader *shader;
1088 unsigned active_samplers = 0;
1089 const struct gl_shader_program **shProg =
1090 (const struct gl_shader_program **) pipeline->CurrentProgram;
1091
1092
1093 memset(TexturesUsed, 0, sizeof(TexturesUsed));
1094
1095 for (unsigned idx = 0; idx < ARRAY_SIZE(pipeline->CurrentProgram); idx++) {
1096 if (!shProg[idx])
1097 continue;
1098
1099 shader = shProg[idx]->_LinkedShaders[idx];
1100 if (!shader || !shader->Program)
1101 continue;
1102
1103 mask = shader->Program->SamplersUsed;
1104 while (mask) {
1105 const int s = u_bit_scan(&mask);
1106 GLuint unit = shader->SamplerUnits[s];
1107 GLuint tgt = shader->SamplerTargets[s];
1108
1109 /* FIXME: Samplers are initialized to 0 and Mesa doesn't do a
1110 * great job of eliminating unused uniforms currently so for now
1111 * don't throw an error if two sampler types both point to 0.
1112 */
1113 if (unit == 0)
1114 continue;
1115
1116 if (TexturesUsed[unit] & ~(1 << tgt)) {
1117 pipeline->InfoLog =
1118 ralloc_asprintf(pipeline,
1119 "Program %d: "
1120 "Texture unit %d is accessed with 2 different types",
1121 shProg[idx]->Name, unit);
1122 return false;
1123 }
1124
1125 TexturesUsed[unit] |= (1 << tgt);
1126 }
1127
1128 active_samplers += shader->num_samplers;
1129 }
1130
1131 if (active_samplers > MAX_COMBINED_TEXTURE_IMAGE_UNITS) {
1132 pipeline->InfoLog =
1133 ralloc_asprintf(pipeline,
1134 "the number of active samplers %d exceed the "
1135 "maximum %d",
1136 active_samplers, MAX_COMBINED_TEXTURE_IMAGE_UNITS);
1137 return false;
1138 }
1139
1140 return true;
1141 }