OSDN Git Service

mesa: added const qualifiers, move local var
[android-x86/external-mesa.git] / src / mesa / main / texenvprogram.c
1 /**************************************************************************
2  * 
3  * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
4  * All Rights Reserved.
5  * Copyright 2009 VMware, Inc.  All Rights Reserved.
6  * 
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the
9  * "Software"), to deal in the Software without restriction, including
10  * without limitation the rights to use, copy, modify, merge, publish,
11  * distribute, sub license, and/or sell copies of the Software, and to
12  * permit persons to whom the Software is furnished to do so, subject to
13  * the following conditions:
14  * 
15  * The above copyright notice and this permission notice (including the
16  * next paragraph) shall be included in all copies or substantial portions
17  * of the Software.
18  * 
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
20  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
22  * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
23  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26  * 
27  **************************************************************************/
28
29 #include "glheader.h"
30 #include "macros.h"
31 #include "enums.h"
32 #include "shader/program.h"
33 #include "shader/prog_parameter.h"
34 #include "shader/prog_cache.h"
35 #include "shader/prog_instruction.h"
36 #include "shader/prog_print.h"
37 #include "shader/prog_statevars.h"
38 #include "shader/programopt.h"
39 #include "texenvprogram.h"
40
41
42 /*
43  * Note on texture units:
44  *
45  * The number of texture units supported by fixed-function fragment
46  * processing is MAX_TEXTURE_COORD_UNITS, not MAX_TEXTURE_IMAGE_UNITS.
47  * That's because there's a one-to-one correspondence between texture
48  * coordinates and samplers in fixed-function processing.
49  *
50  * Since fixed-function vertex processing is limited to MAX_TEXTURE_COORD_UNITS
51  * sets of texcoords, so is fixed-function fragment processing.
52  *
53  * We can safely use ctx->Const.MaxTextureUnits for loop bounds.
54  */
55
56
57 struct texenvprog_cache_item
58 {
59    GLuint hash;
60    void *key;
61    struct gl_fragment_program *data;
62    struct texenvprog_cache_item *next;
63 };
64
65 static GLboolean
66 texenv_doing_secondary_color(GLcontext *ctx)
67 {
68    if (ctx->Light.Enabled &&
69        (ctx->Light.Model.ColorControl == GL_SEPARATE_SPECULAR_COLOR))
70       return GL_TRUE;
71
72    if (ctx->Fog.ColorSumEnabled)
73       return GL_TRUE;
74
75    return GL_FALSE;
76 }
77
78 /**
79  * Up to nine instructions per tex unit, plus fog, specular color.
80  */
81 #define MAX_INSTRUCTIONS ((MAX_TEXTURE_COORD_UNITS * 9) + 12)
82
83 #define DISASSEM (MESA_VERBOSE & VERBOSE_DISASSEM)
84
85 struct mode_opt {
86    GLuint Source:4;
87    GLuint Operand:3;
88 };
89
90 struct state_key {
91    GLuint nr_enabled_units:8;
92    GLuint enabled_units:8;
93    GLuint separate_specular:1;
94    GLuint fog_enabled:1;
95    GLuint fog_mode:2;
96    GLuint inputs_available:12;
97
98    struct {
99       GLuint enabled:1;
100       GLuint source_index:3;   /* one of TEXTURE_1D/2D/3D/CUBE/RECT_INDEX */
101       GLuint shadow:1;
102       GLuint ScaleShiftRGB:2;
103       GLuint ScaleShiftA:2;
104
105       GLuint NumArgsRGB:3;
106       GLuint ModeRGB:5;
107       struct mode_opt OptRGB[MAX_COMBINER_TERMS];
108
109       GLuint NumArgsA:3;
110       GLuint ModeA:5;
111       struct mode_opt OptA[MAX_COMBINER_TERMS];
112    } unit[8];
113 };
114
115 #define FOG_LINEAR  0
116 #define FOG_EXP     1
117 #define FOG_EXP2    2
118 #define FOG_UNKNOWN 3
119
120 static GLuint translate_fog_mode( GLenum mode )
121 {
122    switch (mode) {
123    case GL_LINEAR: return FOG_LINEAR;
124    case GL_EXP: return FOG_EXP;
125    case GL_EXP2: return FOG_EXP2;
126    default: return FOG_UNKNOWN;
127    }
128 }
129
130 #define OPR_SRC_COLOR           0
131 #define OPR_ONE_MINUS_SRC_COLOR 1
132 #define OPR_SRC_ALPHA           2
133 #define OPR_ONE_MINUS_SRC_ALPHA 3
134 #define OPR_ZERO                4
135 #define OPR_ONE                 5
136 #define OPR_UNKNOWN             7
137
138 static GLuint translate_operand( GLenum operand )
139 {
140    switch (operand) {
141    case GL_SRC_COLOR: return OPR_SRC_COLOR;
142    case GL_ONE_MINUS_SRC_COLOR: return OPR_ONE_MINUS_SRC_COLOR;
143    case GL_SRC_ALPHA: return OPR_SRC_ALPHA;
144    case GL_ONE_MINUS_SRC_ALPHA: return OPR_ONE_MINUS_SRC_ALPHA;
145    case GL_ZERO: return OPR_ZERO;
146    case GL_ONE: return OPR_ONE;
147    default:
148       assert(0);
149       return OPR_UNKNOWN;
150    }
151 }
152
153 #define SRC_TEXTURE  0
154 #define SRC_TEXTURE0 1
155 #define SRC_TEXTURE1 2
156 #define SRC_TEXTURE2 3
157 #define SRC_TEXTURE3 4
158 #define SRC_TEXTURE4 5
159 #define SRC_TEXTURE5 6
160 #define SRC_TEXTURE6 7
161 #define SRC_TEXTURE7 8
162 #define SRC_CONSTANT 9
163 #define SRC_PRIMARY_COLOR 10
164 #define SRC_PREVIOUS 11
165 #define SRC_ZERO     12
166 #define SRC_UNKNOWN  15
167
168 static GLuint translate_source( GLenum src )
169 {
170    switch (src) {
171    case GL_TEXTURE: return SRC_TEXTURE;
172    case GL_TEXTURE0:
173    case GL_TEXTURE1:
174    case GL_TEXTURE2:
175    case GL_TEXTURE3:
176    case GL_TEXTURE4:
177    case GL_TEXTURE5:
178    case GL_TEXTURE6:
179    case GL_TEXTURE7: return SRC_TEXTURE0 + (src - GL_TEXTURE0);
180    case GL_CONSTANT: return SRC_CONSTANT;
181    case GL_PRIMARY_COLOR: return SRC_PRIMARY_COLOR;
182    case GL_PREVIOUS: return SRC_PREVIOUS;
183    case GL_ZERO:
184       return SRC_ZERO;
185    default:
186       assert(0);
187       return SRC_UNKNOWN;
188    }
189 }
190
191 #define MODE_REPLACE                     0  /* r = a0 */
192 #define MODE_MODULATE                    1  /* r = a0 * a1 */
193 #define MODE_ADD                         2  /* r = a0 + a1 */
194 #define MODE_ADD_SIGNED                  3  /* r = a0 + a1 - 0.5 */
195 #define MODE_INTERPOLATE                 4  /* r = a0 * a2 + a1 * (1 - a2) */
196 #define MODE_SUBTRACT                    5  /* r = a0 - a1 */
197 #define MODE_DOT3_RGB                    6  /* r = a0 . a1 */
198 #define MODE_DOT3_RGB_EXT                7  /* r = a0 . a1 */
199 #define MODE_DOT3_RGBA                   8  /* r = a0 . a1 */
200 #define MODE_DOT3_RGBA_EXT               9  /* r = a0 . a1 */
201 #define MODE_MODULATE_ADD_ATI           10  /* r = a0 * a2 + a1 */
202 #define MODE_MODULATE_SIGNED_ADD_ATI    11  /* r = a0 * a2 + a1 - 0.5 */
203 #define MODE_MODULATE_SUBTRACT_ATI      12  /* r = a0 * a2 - a1 */
204 #define MODE_ADD_PRODUCTS               13  /* r = a0 * a1 + a2 * a3 */
205 #define MODE_ADD_PRODUCTS_SIGNED        14  /* r = a0 * a1 + a2 * a3 - 0.5 */
206 #define MODE_BUMP_ENVMAP_ATI            15  /* special */
207 #define MODE_UNKNOWN                    16
208
209 /**
210  * Translate GL combiner state into a MODE_x value
211  */
212 static GLuint translate_mode( GLenum envMode, GLenum mode )
213 {
214    switch (mode) {
215    case GL_REPLACE: return MODE_REPLACE;
216    case GL_MODULATE: return MODE_MODULATE;
217    case GL_ADD:
218       if (envMode == GL_COMBINE4_NV)
219          return MODE_ADD_PRODUCTS;
220       else
221          return MODE_ADD;
222    case GL_ADD_SIGNED:
223       if (envMode == GL_COMBINE4_NV)
224          return MODE_ADD_PRODUCTS_SIGNED;
225       else
226          return MODE_ADD_SIGNED;
227    case GL_INTERPOLATE: return MODE_INTERPOLATE;
228    case GL_SUBTRACT: return MODE_SUBTRACT;
229    case GL_DOT3_RGB: return MODE_DOT3_RGB;
230    case GL_DOT3_RGB_EXT: return MODE_DOT3_RGB_EXT;
231    case GL_DOT3_RGBA: return MODE_DOT3_RGBA;
232    case GL_DOT3_RGBA_EXT: return MODE_DOT3_RGBA_EXT;
233    case GL_MODULATE_ADD_ATI: return MODE_MODULATE_ADD_ATI;
234    case GL_MODULATE_SIGNED_ADD_ATI: return MODE_MODULATE_SIGNED_ADD_ATI;
235    case GL_MODULATE_SUBTRACT_ATI: return MODE_MODULATE_SUBTRACT_ATI;
236    case GL_BUMP_ENVMAP_ATI: return MODE_BUMP_ENVMAP_ATI;
237    default:
238       assert(0);
239       return MODE_UNKNOWN;
240    }
241 }
242
243 #define TEXTURE_UNKNOWN_INDEX 7
244 static GLuint translate_tex_src_bit( GLbitfield bit )
245 {
246    /* make sure number of switch cases is correct */
247    assert(NUM_TEXTURE_TARGETS == 7);
248    switch (bit) {
249    case TEXTURE_1D_BIT:   return TEXTURE_1D_INDEX;
250    case TEXTURE_2D_BIT:   return TEXTURE_2D_INDEX;
251    case TEXTURE_RECT_BIT: return TEXTURE_RECT_INDEX;
252    case TEXTURE_3D_BIT:   return TEXTURE_3D_INDEX;
253    case TEXTURE_CUBE_BIT: return TEXTURE_CUBE_INDEX;
254    case TEXTURE_1D_ARRAY_BIT: return TEXTURE_1D_ARRAY_INDEX;
255    case TEXTURE_2D_ARRAY_BIT: return TEXTURE_2D_ARRAY_INDEX;
256    default:
257       assert(0);
258       return TEXTURE_UNKNOWN_INDEX;
259    }
260 }
261
262 #define VERT_BIT_TEX_ANY    (0xff << VERT_ATTRIB_TEX0)
263 #define VERT_RESULT_TEX_ANY (0xff << VERT_RESULT_TEX0)
264
265 /**
266  * Identify all possible varying inputs.  The fragment program will
267  * never reference non-varying inputs, but will track them via state
268  * constants instead.
269  *
270  * This function figures out all the inputs that the fragment program
271  * has access to.  The bitmask is later reduced to just those which
272  * are actually referenced.
273  */
274 static GLbitfield get_fp_input_mask( GLcontext *ctx )
275 {
276    /* _NEW_PROGRAM */
277    const GLboolean vertexShader = (ctx->Shader.CurrentProgram &&
278                                    ctx->Shader.CurrentProgram->LinkStatus &&
279                                    ctx->Shader.CurrentProgram->VertexProgram);
280    const GLboolean vertexProgram = ctx->VertexProgram._Enabled;
281    GLbitfield fp_inputs = 0x0;
282
283    if (ctx->VertexProgram._Overriden) {
284       /* Somebody's messing with the vertex program and we don't have
285        * a clue what's happening.  Assume that it could be producing
286        * all possible outputs.
287        */
288       fp_inputs = ~0;
289    }
290    else if (ctx->RenderMode == GL_FEEDBACK) {
291       /* _NEW_RENDERMODE */
292       fp_inputs = (FRAG_BIT_COL0 | FRAG_BIT_TEX0);
293    }
294    else if (!(vertexProgram || vertexShader) ||
295             !ctx->VertexProgram._Current) {
296       /* Fixed function vertex logic */
297       /* _NEW_ARRAY */
298       GLbitfield varying_inputs = ctx->varying_vp_inputs;
299
300       /* These get generated in the setup routine regardless of the
301        * vertex program:
302        */
303       /* _NEW_POINT */
304       if (ctx->Point.PointSprite)
305          varying_inputs |= FRAG_BITS_TEX_ANY;
306
307       /* First look at what values may be computed by the generated
308        * vertex program:
309        */
310       /* _NEW_LIGHT */
311       if (ctx->Light.Enabled) {
312          fp_inputs |= FRAG_BIT_COL0;
313
314          if (texenv_doing_secondary_color(ctx))
315             fp_inputs |= FRAG_BIT_COL1;
316       }
317
318       /* _NEW_TEXTURE */
319       fp_inputs |= (ctx->Texture._TexGenEnabled |
320                     ctx->Texture._TexMatEnabled) << FRAG_ATTRIB_TEX0;
321
322       /* Then look at what might be varying as a result of enabled
323        * arrays, etc:
324        */
325       if (varying_inputs & VERT_BIT_COLOR0)
326          fp_inputs |= FRAG_BIT_COL0;
327       if (varying_inputs & VERT_BIT_COLOR1)
328          fp_inputs |= FRAG_BIT_COL1;
329
330       fp_inputs |= (((varying_inputs & VERT_BIT_TEX_ANY) >> VERT_ATTRIB_TEX0) 
331                     << FRAG_ATTRIB_TEX0);
332
333    }
334    else {
335       /* calculate from vp->outputs */
336       struct gl_vertex_program *vprog;
337       GLbitfield vp_outputs;
338
339       /* Choose GLSL vertex shader over ARB vertex program.  Need this
340        * since vertex shader state validation comes after fragment state
341        * validation (see additional comments in state.c).
342        */
343       if (vertexShader)
344          vprog = ctx->Shader.CurrentProgram->VertexProgram;
345       else
346          vprog = ctx->VertexProgram.Current;
347
348       vp_outputs = vprog->Base.OutputsWritten;
349
350       /* These get generated in the setup routine regardless of the
351        * vertex program:
352        */
353       /* _NEW_POINT */
354       if (ctx->Point.PointSprite)
355          vp_outputs |= FRAG_BITS_TEX_ANY;
356
357       if (vp_outputs & (1 << VERT_RESULT_COL0))
358          fp_inputs |= FRAG_BIT_COL0;
359       if (vp_outputs & (1 << VERT_RESULT_COL1))
360          fp_inputs |= FRAG_BIT_COL1;
361
362       fp_inputs |= (((vp_outputs & VERT_RESULT_TEX_ANY) >> VERT_RESULT_TEX0) 
363                     << FRAG_ATTRIB_TEX0);
364    }
365    
366    return fp_inputs;
367 }
368
369
370 /**
371  * Examine current texture environment state and generate a unique
372  * key to identify it.
373  */
374 static void make_state_key( GLcontext *ctx,  struct state_key *key )
375 {
376    GLuint i, j;
377    GLbitfield inputs_referenced = FRAG_BIT_COL0;
378    GLbitfield inputs_available = get_fp_input_mask( ctx );
379
380    memset(key, 0, sizeof(*key));
381
382    /* _NEW_TEXTURE */
383    for (i = 0; i < ctx->Const.MaxTextureUnits; i++) {
384       const struct gl_texture_unit *texUnit = &ctx->Texture.Unit[i];
385       GLenum format;
386
387       if (!texUnit->_ReallyEnabled || !texUnit->Enabled)
388          continue;
389
390       format = texUnit->_Current->Image[0][texUnit->_Current->BaseLevel]->_BaseFormat;
391
392       key->unit[i].enabled = 1;
393       key->enabled_units |= (1<<i);
394       key->nr_enabled_units = i+1;
395       inputs_referenced |= FRAG_BIT_TEX(i);
396
397       key->unit[i].source_index = 
398          translate_tex_src_bit(texUnit->_ReallyEnabled);                
399       key->unit[i].shadow = ((texUnit->_Current->CompareMode == GL_COMPARE_R_TO_TEXTURE) && 
400                              ((format == GL_DEPTH_COMPONENT) || 
401                               (format == GL_DEPTH_STENCIL_EXT)));
402
403       key->unit[i].NumArgsRGB = texUnit->_CurrentCombine->_NumArgsRGB;
404       key->unit[i].NumArgsA = texUnit->_CurrentCombine->_NumArgsA;
405
406       key->unit[i].ModeRGB =
407          translate_mode(texUnit->EnvMode, texUnit->_CurrentCombine->ModeRGB);
408       key->unit[i].ModeA =
409          translate_mode(texUnit->EnvMode, texUnit->_CurrentCombine->ModeA);
410
411       key->unit[i].ScaleShiftRGB = texUnit->_CurrentCombine->ScaleShiftRGB;
412       key->unit[i].ScaleShiftA = texUnit->_CurrentCombine->ScaleShiftA;
413
414       for (j = 0; j < MAX_COMBINER_TERMS; j++) {
415          key->unit[i].OptRGB[j].Operand =
416             translate_operand(texUnit->_CurrentCombine->OperandRGB[j]);
417          key->unit[i].OptA[j].Operand =
418             translate_operand(texUnit->_CurrentCombine->OperandA[j]);
419          key->unit[i].OptRGB[j].Source =
420             translate_source(texUnit->_CurrentCombine->SourceRGB[j]);
421          key->unit[i].OptA[j].Source =
422             translate_source(texUnit->_CurrentCombine->SourceA[j]);
423       }
424
425       if (key->unit[i].ModeRGB == MODE_BUMP_ENVMAP_ATI) {
426          /* requires some special translation */
427          key->unit[i].NumArgsRGB = 2;
428          key->unit[i].ScaleShiftRGB = 0;
429          key->unit[i].OptRGB[0].Operand = OPR_SRC_COLOR;
430          key->unit[i].OptRGB[0].Source = SRC_TEXTURE;
431          key->unit[i].OptRGB[1].Operand = OPR_SRC_COLOR;
432          key->unit[i].OptRGB[1].Source = texUnit->BumpTarget - GL_TEXTURE0 + SRC_TEXTURE0;
433        }
434    }
435
436    /* _NEW_LIGHT | _NEW_FOG */
437    if (texenv_doing_secondary_color(ctx)) {
438       key->separate_specular = 1;
439       inputs_referenced |= FRAG_BIT_COL1;
440    }
441
442    /* _NEW_FOG */
443    if (ctx->Fog.Enabled) {
444       key->fog_enabled = 1;
445       key->fog_mode = translate_fog_mode(ctx->Fog.Mode);
446       inputs_referenced |= FRAG_BIT_FOGC; /* maybe */
447    }
448
449    key->inputs_available = (inputs_available & inputs_referenced);
450 }
451
452 /**
453  * Use uregs to represent registers internally, translate to Mesa's
454  * expected formats on emit.  
455  *
456  * NOTE: These are passed by value extensively in this file rather
457  * than as usual by pointer reference.  If this disturbs you, try
458  * remembering they are just 32bits in size.
459  *
460  * GCC is smart enough to deal with these dword-sized structures in
461  * much the same way as if I had defined them as dwords and was using
462  * macros to access and set the fields.  This is much nicer and easier
463  * to evolve.
464  */
465 struct ureg {
466    GLuint file:4;
467    GLuint idx:8;
468    GLuint negatebase:1;
469    GLuint abs:1;
470    GLuint negateabs:1;
471    GLuint swz:12;
472    GLuint pad:5;
473 };
474
475 static const struct ureg undef = { 
476    PROGRAM_UNDEFINED,
477    ~0,
478    0,
479    0,
480    0,
481    0,
482    0
483 };
484
485
486 /** State used to build the fragment program:
487  */
488 struct texenv_fragment_program {
489    struct gl_fragment_program *program;
490    GLcontext *ctx;
491    struct state_key *state;
492
493    GLbitfield alu_temps;        /**< Track texture indirections, see spec. */
494    GLbitfield temps_output;     /**< Track texture indirections, see spec. */
495    GLbitfield temp_in_use;      /**< Tracks temporary regs which are in use. */
496    GLboolean error;
497
498    struct ureg src_texture[MAX_TEXTURE_COORD_UNITS];   
499    /* Reg containing each texture unit's sampled texture color,
500     * else undef.
501     */
502
503    struct ureg texcoord_tex[MAX_TEXTURE_COORD_UNITS];
504    /* Reg containing texcoord for a texture unit,
505     * needed for bump mapping, else undef.
506     */
507
508    struct ureg src_previous;    /**< Reg containing color from previous 
509                                  * stage.  May need to be decl'd.
510                                  */
511
512    GLuint last_tex_stage;       /**< Number of last enabled texture unit */
513
514    struct ureg half;
515    struct ureg one;
516    struct ureg zero;
517 };
518
519
520
521 static struct ureg make_ureg(GLuint file, GLuint idx)
522 {
523    struct ureg reg;
524    reg.file = file;
525    reg.idx = idx;
526    reg.negatebase = 0;
527    reg.abs = 0;
528    reg.negateabs = 0;
529    reg.swz = SWIZZLE_NOOP;
530    reg.pad = 0;
531    return reg;
532 }
533
534 static struct ureg swizzle( struct ureg reg, int x, int y, int z, int w )
535 {
536    reg.swz = MAKE_SWIZZLE4(GET_SWZ(reg.swz, x),
537                            GET_SWZ(reg.swz, y),
538                            GET_SWZ(reg.swz, z),
539                            GET_SWZ(reg.swz, w));
540
541    return reg;
542 }
543
544 static struct ureg swizzle1( struct ureg reg, int x )
545 {
546    return swizzle(reg, x, x, x, x);
547 }
548
549 static struct ureg negate( struct ureg reg )
550 {
551    reg.negatebase ^= 1;
552    return reg;
553 }
554
555 static GLboolean is_undef( struct ureg reg )
556 {
557    return reg.file == PROGRAM_UNDEFINED;
558 }
559
560
561 static struct ureg get_temp( struct texenv_fragment_program *p )
562 {
563    GLint bit;
564    
565    /* First try and reuse temps which have been used already:
566     */
567    bit = _mesa_ffs( ~p->temp_in_use & p->alu_temps );
568
569    /* Then any unused temporary:
570     */
571    if (!bit)
572       bit = _mesa_ffs( ~p->temp_in_use );
573
574    if (!bit) {
575       _mesa_problem(NULL, "%s: out of temporaries\n", __FILE__);
576       _mesa_exit(1);
577    }
578
579    if ((GLuint) bit > p->program->Base.NumTemporaries)
580       p->program->Base.NumTemporaries = bit;
581
582    p->temp_in_use |= 1<<(bit-1);
583    return make_ureg(PROGRAM_TEMPORARY, (bit-1));
584 }
585
586 static struct ureg get_tex_temp( struct texenv_fragment_program *p )
587 {
588    int bit;
589    
590    /* First try to find available temp not previously used (to avoid
591     * starting a new texture indirection).  According to the spec, the
592     * ~p->temps_output isn't necessary, but will keep it there for
593     * now:
594     */
595    bit = _mesa_ffs( ~p->temp_in_use & ~p->alu_temps & ~p->temps_output );
596
597    /* Then any unused temporary:
598     */
599    if (!bit) 
600       bit = _mesa_ffs( ~p->temp_in_use );
601
602    if (!bit) {
603       _mesa_problem(NULL, "%s: out of temporaries\n", __FILE__);
604       _mesa_exit(1);
605    }
606
607    if ((GLuint) bit > p->program->Base.NumTemporaries)
608       p->program->Base.NumTemporaries = bit;
609
610    p->temp_in_use |= 1<<(bit-1);
611    return make_ureg(PROGRAM_TEMPORARY, (bit-1));
612 }
613
614
615 /** Mark a temp reg as being no longer allocatable. */
616 static void reserve_temp( struct texenv_fragment_program *p, struct ureg r )
617 {
618    if (r.file == PROGRAM_TEMPORARY)
619       p->temps_output |= (1 << r.idx);
620 }
621
622
623 static void release_temps(GLcontext *ctx, struct texenv_fragment_program *p )
624 {
625    GLuint max_temp = ctx->Const.FragmentProgram.MaxTemps;
626
627    /* KW: To support tex_env_crossbar, don't release the registers in
628     * temps_output.
629     */
630    if (max_temp >= sizeof(int) * 8)
631       p->temp_in_use = p->temps_output;
632    else
633       p->temp_in_use = ~((1<<max_temp)-1) | p->temps_output;
634 }
635
636
637 static struct ureg register_param5( struct texenv_fragment_program *p, 
638                                     GLint s0,
639                                     GLint s1,
640                                     GLint s2,
641                                     GLint s3,
642                                     GLint s4)
643 {
644    gl_state_index tokens[STATE_LENGTH];
645    GLuint idx;
646    tokens[0] = s0;
647    tokens[1] = s1;
648    tokens[2] = s2;
649    tokens[3] = s3;
650    tokens[4] = s4;
651    idx = _mesa_add_state_reference( p->program->Base.Parameters, tokens );
652    return make_ureg(PROGRAM_STATE_VAR, idx);
653 }
654
655
656 #define register_param1(p,s0)          register_param5(p,s0,0,0,0,0)
657 #define register_param2(p,s0,s1)       register_param5(p,s0,s1,0,0,0)
658 #define register_param3(p,s0,s1,s2)    register_param5(p,s0,s1,s2,0,0)
659 #define register_param4(p,s0,s1,s2,s3) register_param5(p,s0,s1,s2,s3,0)
660
661 static GLuint frag_to_vert_attrib( GLuint attrib )
662 {
663    switch (attrib) {
664    case FRAG_ATTRIB_COL0: return VERT_ATTRIB_COLOR0;
665    case FRAG_ATTRIB_COL1: return VERT_ATTRIB_COLOR1;
666    default:
667       assert(attrib >= FRAG_ATTRIB_TEX0);
668       assert(attrib <= FRAG_ATTRIB_TEX7);
669       return attrib - FRAG_ATTRIB_TEX0 + VERT_ATTRIB_TEX0;
670    }
671 }
672
673
674 static struct ureg register_input( struct texenv_fragment_program *p, GLuint input )
675 {
676    if (p->state->inputs_available & (1<<input)) {
677       p->program->Base.InputsRead |= (1 << input);
678       return make_ureg(PROGRAM_INPUT, input);
679    }
680    else {
681       GLuint idx = frag_to_vert_attrib( input );
682       return register_param3( p, STATE_INTERNAL, STATE_CURRENT_ATTRIB, idx );
683    }
684 }
685
686
687 static void emit_arg( struct prog_src_register *reg,
688                       struct ureg ureg )
689 {
690    reg->File = ureg.file;
691    reg->Index = ureg.idx;
692    reg->Swizzle = ureg.swz;
693    reg->Negate = ureg.negatebase ? NEGATE_XYZW : NEGATE_NONE;
694    reg->Abs = ureg.abs;
695 }
696
697 static void emit_dst( struct prog_dst_register *dst,
698                       struct ureg ureg, GLuint mask )
699 {
700    dst->File = ureg.file;
701    dst->Index = ureg.idx;
702    dst->WriteMask = mask;
703    dst->CondMask = COND_TR;  /* always pass cond test */
704    dst->CondSwizzle = SWIZZLE_NOOP;
705 }
706
707 static struct prog_instruction *
708 emit_op(struct texenv_fragment_program *p,
709         enum prog_opcode op,
710         struct ureg dest,
711         GLuint mask,
712         GLboolean saturate,
713         struct ureg src0,
714         struct ureg src1,
715         struct ureg src2 )
716 {
717    GLuint nr = p->program->Base.NumInstructions++;
718    struct prog_instruction *inst = &p->program->Base.Instructions[nr];
719
720    assert(nr < MAX_INSTRUCTIONS);
721
722    _mesa_init_instructions(inst, 1);
723    inst->Opcode = op;
724    
725    emit_arg( &inst->SrcReg[0], src0 );
726    emit_arg( &inst->SrcReg[1], src1 );
727    emit_arg( &inst->SrcReg[2], src2 );
728    
729    inst->SaturateMode = saturate ? SATURATE_ZERO_ONE : SATURATE_OFF;
730
731    emit_dst( &inst->DstReg, dest, mask );
732
733 #if 0
734    /* Accounting for indirection tracking:
735     */
736    if (dest.file == PROGRAM_TEMPORARY)
737       p->temps_output |= 1 << dest.idx;
738 #endif
739
740    return inst;
741 }
742    
743
744 static struct ureg emit_arith( struct texenv_fragment_program *p,
745                                enum prog_opcode op,
746                                struct ureg dest,
747                                GLuint mask,
748                                GLboolean saturate,
749                                struct ureg src0,
750                                struct ureg src1,
751                                struct ureg src2 )
752 {
753    emit_op(p, op, dest, mask, saturate, src0, src1, src2);
754    
755    /* Accounting for indirection tracking:
756     */
757    if (src0.file == PROGRAM_TEMPORARY)
758       p->alu_temps |= 1 << src0.idx;
759
760    if (!is_undef(src1) && src1.file == PROGRAM_TEMPORARY)
761       p->alu_temps |= 1 << src1.idx;
762
763    if (!is_undef(src2) && src2.file == PROGRAM_TEMPORARY)
764       p->alu_temps |= 1 << src2.idx;
765
766    if (dest.file == PROGRAM_TEMPORARY)
767       p->alu_temps |= 1 << dest.idx;
768        
769    p->program->Base.NumAluInstructions++;
770    return dest;
771 }
772
773 static struct ureg emit_texld( struct texenv_fragment_program *p,
774                                enum prog_opcode op,
775                                struct ureg dest,
776                                GLuint destmask,
777                                GLuint tex_unit,
778                                GLuint tex_idx,
779                                GLuint tex_shadow,
780                                struct ureg coord )
781 {
782    struct prog_instruction *inst = emit_op( p, op, 
783                                           dest, destmask, 
784                                           GL_FALSE,     /* don't saturate? */
785                                           coord,        /* arg 0? */
786                                           undef,
787                                           undef);
788    
789    inst->TexSrcTarget = tex_idx;
790    inst->TexSrcUnit = tex_unit;
791    inst->TexShadow = tex_shadow;
792
793    p->program->Base.NumTexInstructions++;
794
795    /* Accounting for indirection tracking:
796     */
797    reserve_temp(p, dest);
798
799 #if 0
800    /* Is this a texture indirection?
801     */
802    if ((coord.file == PROGRAM_TEMPORARY &&
803         (p->temps_output & (1<<coord.idx))) ||
804        (dest.file == PROGRAM_TEMPORARY &&
805         (p->alu_temps & (1<<dest.idx)))) {
806       p->program->Base.NumTexIndirections++;
807       p->temps_output = 1<<coord.idx;
808       p->alu_temps = 0;
809       assert(0);                /* KW: texture env crossbar */
810    }
811 #endif
812
813    return dest;
814 }
815
816
817 static struct ureg register_const4f( struct texenv_fragment_program *p, 
818                                      GLfloat s0,
819                                      GLfloat s1,
820                                      GLfloat s2,
821                                      GLfloat s3)
822 {
823    GLfloat values[4];
824    GLuint idx, swizzle;
825    struct ureg r;
826    values[0] = s0;
827    values[1] = s1;
828    values[2] = s2;
829    values[3] = s3;
830    idx = _mesa_add_unnamed_constant( p->program->Base.Parameters, values, 4,
831                                      &swizzle );
832    r = make_ureg(PROGRAM_CONSTANT, idx);
833    r.swz = swizzle;
834    return r;
835 }
836
837 #define register_scalar_const(p, s0)    register_const4f(p, s0, s0, s0, s0)
838 #define register_const1f(p, s0)         register_const4f(p, s0, 0, 0, 1)
839 #define register_const2f(p, s0, s1)     register_const4f(p, s0, s1, 0, 1)
840 #define register_const3f(p, s0, s1, s2) register_const4f(p, s0, s1, s2, 1)
841
842
843 static struct ureg get_one( struct texenv_fragment_program *p )
844 {
845    if (is_undef(p->one)) 
846       p->one = register_scalar_const(p, 1.0);
847    return p->one;
848 }
849
850 static struct ureg get_half( struct texenv_fragment_program *p )
851 {
852    if (is_undef(p->half)) 
853       p->half = register_scalar_const(p, 0.5);
854    return p->half;
855 }
856
857 static struct ureg get_zero( struct texenv_fragment_program *p )
858 {
859    if (is_undef(p->zero)) 
860       p->zero = register_scalar_const(p, 0.0);
861    return p->zero;
862 }
863
864
865 static void program_error( struct texenv_fragment_program *p, const char *msg )
866 {
867    _mesa_problem(NULL, msg);
868    p->error = 1;
869 }
870
871 static struct ureg get_source( struct texenv_fragment_program *p, 
872                                GLuint src, GLuint unit )
873 {
874    switch (src) {
875    case SRC_TEXTURE: 
876       assert(!is_undef(p->src_texture[unit]));
877       return p->src_texture[unit];
878
879    case SRC_TEXTURE0:
880    case SRC_TEXTURE1:
881    case SRC_TEXTURE2:
882    case SRC_TEXTURE3:
883    case SRC_TEXTURE4:
884    case SRC_TEXTURE5:
885    case SRC_TEXTURE6:
886    case SRC_TEXTURE7: 
887       assert(!is_undef(p->src_texture[src - SRC_TEXTURE0]));
888       return p->src_texture[src - SRC_TEXTURE0];
889
890    case SRC_CONSTANT:
891       return register_param2(p, STATE_TEXENV_COLOR, unit);
892
893    case SRC_PRIMARY_COLOR:
894       return register_input(p, FRAG_ATTRIB_COL0);
895
896    case SRC_ZERO:
897       return get_zero(p);
898
899    case SRC_PREVIOUS:
900       if (is_undef(p->src_previous))
901          return register_input(p, FRAG_ATTRIB_COL0);
902       else
903          return p->src_previous;
904
905    default:
906       assert(0);
907       return undef;
908    }
909 }
910
911 static struct ureg emit_combine_source( struct texenv_fragment_program *p, 
912                                         GLuint mask,
913                                         GLuint unit,
914                                         GLuint source, 
915                                         GLuint operand )
916 {
917    struct ureg arg, src, one;
918
919    src = get_source(p, source, unit);
920
921    switch (operand) {
922    case OPR_ONE_MINUS_SRC_COLOR: 
923       /* Get unused tmp,
924        * Emit tmp = 1.0 - arg.xyzw
925        */
926       arg = get_temp( p );
927       one = get_one( p );
928       return emit_arith( p, OPCODE_SUB, arg, mask, 0, one, src, undef);
929
930    case OPR_SRC_ALPHA: 
931       if (mask == WRITEMASK_W)
932          return src;
933       else
934          return swizzle1( src, SWIZZLE_W );
935    case OPR_ONE_MINUS_SRC_ALPHA: 
936       /* Get unused tmp,
937        * Emit tmp = 1.0 - arg.wwww
938        */
939       arg = get_temp(p);
940       one = get_one(p);
941       return emit_arith(p, OPCODE_SUB, arg, mask, 0,
942                         one, swizzle1(src, SWIZZLE_W), undef);
943    case OPR_ZERO:
944       return get_zero(p);
945    case OPR_ONE:
946       return get_one(p);
947    case OPR_SRC_COLOR: 
948       return src;
949    default:
950       assert(0);
951       return src;
952    }
953 }
954
955 static GLboolean args_match( const struct state_key *key, GLuint unit )
956 {
957    GLuint i, nr = key->unit[unit].NumArgsRGB;
958
959    for (i = 0 ; i < nr ; i++) {
960       if (key->unit[unit].OptA[i].Source != key->unit[unit].OptRGB[i].Source) 
961          return GL_FALSE;
962
963       switch(key->unit[unit].OptA[i].Operand) {
964       case OPR_SRC_ALPHA: 
965          switch(key->unit[unit].OptRGB[i].Operand) {
966          case OPR_SRC_COLOR: 
967          case OPR_SRC_ALPHA: 
968             break;
969          default:
970             return GL_FALSE;
971          }
972          break;
973       case OPR_ONE_MINUS_SRC_ALPHA: 
974          switch(key->unit[unit].OptRGB[i].Operand) {
975          case OPR_ONE_MINUS_SRC_COLOR: 
976          case OPR_ONE_MINUS_SRC_ALPHA: 
977             break;
978          default:
979             return GL_FALSE;
980          }
981          break;
982       default: 
983          return GL_FALSE;       /* impossible */
984       }
985    }
986
987    return GL_TRUE;
988 }
989
990 static struct ureg emit_combine( struct texenv_fragment_program *p,
991                                  struct ureg dest,
992                                  GLuint mask,
993                                  GLboolean saturate,
994                                  GLuint unit,
995                                  GLuint nr,
996                                  GLuint mode,
997                                  const struct mode_opt *opt)
998 {
999    struct ureg src[MAX_COMBINER_TERMS];
1000    struct ureg tmp, half;
1001    GLuint i;
1002
1003    assert(nr <= MAX_COMBINER_TERMS);
1004
1005    tmp = undef; /* silence warning (bug 5318) */
1006
1007    for (i = 0; i < nr; i++)
1008       src[i] = emit_combine_source( p, mask, unit, opt[i].Source, opt[i].Operand );
1009
1010    switch (mode) {
1011    case MODE_REPLACE: 
1012       if (mask == WRITEMASK_XYZW && !saturate)
1013          return src[0];
1014       else
1015          return emit_arith( p, OPCODE_MOV, dest, mask, saturate, src[0], undef, undef );
1016    case MODE_MODULATE: 
1017       return emit_arith( p, OPCODE_MUL, dest, mask, saturate,
1018                          src[0], src[1], undef );
1019    case MODE_ADD: 
1020       return emit_arith( p, OPCODE_ADD, dest, mask, saturate, 
1021                          src[0], src[1], undef );
1022    case MODE_ADD_SIGNED:
1023       /* tmp = arg0 + arg1
1024        * result = tmp - .5
1025        */
1026       half = get_half(p);
1027       tmp = get_temp( p );
1028       emit_arith( p, OPCODE_ADD, tmp, mask, 0, src[0], src[1], undef );
1029       emit_arith( p, OPCODE_SUB, dest, mask, saturate, tmp, half, undef );
1030       return dest;
1031    case MODE_INTERPOLATE: 
1032       /* Arg0 * (Arg2) + Arg1 * (1-Arg2) -- note arguments are reordered:
1033        */
1034       return emit_arith( p, OPCODE_LRP, dest, mask, saturate, src[2], src[0], src[1] );
1035
1036    case MODE_SUBTRACT: 
1037       return emit_arith( p, OPCODE_SUB, dest, mask, saturate, src[0], src[1], undef );
1038
1039    case MODE_DOT3_RGBA:
1040    case MODE_DOT3_RGBA_EXT: 
1041    case MODE_DOT3_RGB_EXT:
1042    case MODE_DOT3_RGB: {
1043       struct ureg tmp0 = get_temp( p );
1044       struct ureg tmp1 = get_temp( p );
1045       struct ureg neg1 = register_scalar_const(p, -1);
1046       struct ureg two  = register_scalar_const(p, 2);
1047
1048       /* tmp0 = 2*src0 - 1
1049        * tmp1 = 2*src1 - 1
1050        *
1051        * dst = tmp0 dot3 tmp1 
1052        */
1053       emit_arith( p, OPCODE_MAD, tmp0, WRITEMASK_XYZW, 0, 
1054                   two, src[0], neg1);
1055
1056       if (_mesa_memcmp(&src[0], &src[1], sizeof(struct ureg)) == 0)
1057          tmp1 = tmp0;
1058       else
1059          emit_arith( p, OPCODE_MAD, tmp1, WRITEMASK_XYZW, 0, 
1060                      two, src[1], neg1);
1061       emit_arith( p, OPCODE_DP3, dest, mask, saturate, tmp0, tmp1, undef);
1062       return dest;
1063    }
1064    case MODE_MODULATE_ADD_ATI:
1065       /* Arg0 * Arg2 + Arg1 */
1066       return emit_arith( p, OPCODE_MAD, dest, mask, saturate,
1067                          src[0], src[2], src[1] );
1068    case MODE_MODULATE_SIGNED_ADD_ATI: {
1069       /* Arg0 * Arg2 + Arg1 - 0.5 */
1070       struct ureg tmp0 = get_temp(p);
1071       half = get_half(p);
1072       emit_arith( p, OPCODE_MAD, tmp0, mask, 0, src[0], src[2], src[1] );
1073       emit_arith( p, OPCODE_SUB, dest, mask, saturate, tmp0, half, undef );
1074       return dest;
1075    }
1076    case MODE_MODULATE_SUBTRACT_ATI:
1077       /* Arg0 * Arg2 - Arg1 */
1078       emit_arith( p, OPCODE_MAD, dest, mask, 0, src[0], src[2], negate(src[1]) );
1079       return dest;
1080    case MODE_ADD_PRODUCTS:
1081       /* Arg0 * Arg1 + Arg2 * Arg3 */
1082       {
1083          struct ureg tmp0 = get_temp(p);
1084          emit_arith( p, OPCODE_MUL, tmp0, mask, 0, src[0], src[1], undef );
1085          emit_arith( p, OPCODE_MAD, dest, mask, saturate, src[2], src[3], tmp0 );
1086       }
1087       return dest;
1088    case MODE_ADD_PRODUCTS_SIGNED:
1089       /* Arg0 * Arg1 + Arg2 * Arg3 - 0.5 */
1090       {
1091          struct ureg tmp0 = get_temp(p);
1092          half = get_half(p);
1093          emit_arith( p, OPCODE_MUL, tmp0, mask, 0, src[0], src[1], undef );
1094          emit_arith( p, OPCODE_MAD, tmp0, mask, 0, src[2], src[3], tmp0 );
1095          emit_arith( p, OPCODE_SUB, dest, mask, saturate, tmp0, half, undef );
1096       }
1097       return dest;
1098    case MODE_BUMP_ENVMAP_ATI:
1099       /* special - not handled here */
1100       assert(0);
1101       return src[0];
1102    default: 
1103       assert(0);
1104       return src[0];
1105    }
1106 }
1107
1108
1109 /**
1110  * Generate instructions for one texture unit's env/combiner mode.
1111  */
1112 static struct ureg
1113 emit_texenv(struct texenv_fragment_program *p, GLuint unit)
1114 {
1115    const struct state_key *key = p->state;
1116    GLboolean saturate;
1117    GLuint rgb_shift, alpha_shift;
1118    struct ureg out, dest;
1119
1120    if (!key->unit[unit].enabled) {
1121       return get_source(p, SRC_PREVIOUS, 0);
1122    }
1123    if (key->unit[unit].ModeRGB == MODE_BUMP_ENVMAP_ATI) {
1124       /* this isn't really a env stage delivering a color and handled elsewhere */
1125       return get_source(p, SRC_PREVIOUS, 0);
1126    }
1127    
1128    switch (key->unit[unit].ModeRGB) {
1129    case MODE_DOT3_RGB_EXT:
1130       alpha_shift = key->unit[unit].ScaleShiftA;
1131       rgb_shift = 0;
1132       break;
1133    case MODE_DOT3_RGBA_EXT:
1134       alpha_shift = 0;
1135       rgb_shift = 0;
1136       break;
1137    default:
1138       rgb_shift = key->unit[unit].ScaleShiftRGB;
1139       alpha_shift = key->unit[unit].ScaleShiftA;
1140       break;
1141    }
1142    
1143    /* If we'll do rgb/alpha shifting don't saturate in emit_combine().
1144     * We don't want to clamp twice.
1145     */
1146    saturate = !(rgb_shift || alpha_shift);
1147
1148    /* If this is the very last calculation, emit direct to output reg:
1149     */
1150    if (key->separate_specular ||
1151        unit != p->last_tex_stage ||
1152        alpha_shift ||
1153        rgb_shift)
1154       dest = get_temp( p );
1155    else
1156       dest = make_ureg(PROGRAM_OUTPUT, FRAG_RESULT_COLOR);
1157
1158    /* Emit the RGB and A combine ops
1159     */
1160    if (key->unit[unit].ModeRGB == key->unit[unit].ModeA &&
1161        args_match(key, unit)) {
1162       out = emit_combine( p, dest, WRITEMASK_XYZW, saturate,
1163                           unit,
1164                           key->unit[unit].NumArgsRGB,
1165                           key->unit[unit].ModeRGB,
1166                           key->unit[unit].OptRGB);
1167    }
1168    else if (key->unit[unit].ModeRGB == MODE_DOT3_RGBA_EXT ||
1169             key->unit[unit].ModeRGB == MODE_DOT3_RGBA) {
1170       out = emit_combine( p, dest, WRITEMASK_XYZW, saturate,
1171                           unit,
1172                           key->unit[unit].NumArgsRGB,
1173                           key->unit[unit].ModeRGB,
1174                           key->unit[unit].OptRGB);
1175    }
1176    else {
1177       /* Need to do something to stop from re-emitting identical
1178        * argument calculations here:
1179        */
1180       out = emit_combine( p, dest, WRITEMASK_XYZ, saturate,
1181                           unit,
1182                           key->unit[unit].NumArgsRGB,
1183                           key->unit[unit].ModeRGB,
1184                           key->unit[unit].OptRGB);
1185       out = emit_combine( p, dest, WRITEMASK_W, saturate,
1186                           unit,
1187                           key->unit[unit].NumArgsA,
1188                           key->unit[unit].ModeA,
1189                           key->unit[unit].OptA);
1190    }
1191
1192    /* Deal with the final shift:
1193     */
1194    if (alpha_shift || rgb_shift) {
1195       struct ureg shift;
1196
1197       saturate = GL_TRUE;  /* always saturate at this point */
1198
1199       if (rgb_shift == alpha_shift) {
1200          shift = register_scalar_const(p, (GLfloat)(1<<rgb_shift));
1201       }
1202       else {
1203          shift = register_const4f(p, 
1204                                   (GLfloat)(1<<rgb_shift),
1205                                   (GLfloat)(1<<rgb_shift),
1206                                   (GLfloat)(1<<rgb_shift),
1207                                   (GLfloat)(1<<alpha_shift));
1208       }
1209       return emit_arith( p, OPCODE_MUL, dest, WRITEMASK_XYZW, 
1210                          saturate, out, shift, undef );
1211    }
1212    else
1213       return out;
1214 }
1215
1216
1217 /**
1218  * Generate instruction for getting a texture source term.
1219  */
1220 static void load_texture( struct texenv_fragment_program *p, GLuint unit )
1221 {
1222    if (is_undef(p->src_texture[unit])) {
1223       GLuint texTarget = p->state->unit[unit].source_index;
1224       struct ureg texcoord;
1225       struct ureg tmp = get_tex_temp( p );
1226
1227       if (is_undef(p->texcoord_tex[unit])) {
1228          texcoord = register_input(p, FRAG_ATTRIB_TEX0+unit);
1229       }
1230       else {
1231          /* might want to reuse this reg for tex output actually */
1232          texcoord = p->texcoord_tex[unit];
1233       }
1234
1235       if (texTarget == TEXTURE_UNKNOWN_INDEX)
1236          program_error(p, "TexSrcBit");
1237                           
1238       /* TODO: Use D0_MASK_XY where possible.
1239        */
1240       if (p->state->unit[unit].enabled) {
1241          GLboolean shadow = GL_FALSE;
1242
1243          if (p->state->unit[unit].shadow) {
1244             p->program->Base.ShadowSamplers |= 1 << unit;
1245             shadow = GL_TRUE;
1246          }
1247
1248          p->src_texture[unit] = emit_texld( p, OPCODE_TXP,
1249                                             tmp, WRITEMASK_XYZW, 
1250                                             unit, texTarget, shadow,
1251                                             texcoord );
1252
1253          p->program->Base.SamplersUsed |= (1 << unit);
1254          /* This identity mapping should already be in place
1255           * (see _mesa_init_program_struct()) but let's be safe.
1256           */
1257          p->program->Base.SamplerUnits[unit] = unit;
1258       }
1259       else
1260          p->src_texture[unit] = get_zero(p);
1261    }
1262 }
1263
1264 static GLboolean load_texenv_source( struct texenv_fragment_program *p, 
1265                                      GLuint src, GLuint unit )
1266 {
1267    switch (src) {
1268    case SRC_TEXTURE:
1269       load_texture(p, unit);
1270       break;
1271
1272    case SRC_TEXTURE0:
1273    case SRC_TEXTURE1:
1274    case SRC_TEXTURE2:
1275    case SRC_TEXTURE3:
1276    case SRC_TEXTURE4:
1277    case SRC_TEXTURE5:
1278    case SRC_TEXTURE6:
1279    case SRC_TEXTURE7:       
1280       load_texture(p, src - SRC_TEXTURE0);
1281       break;
1282       
1283    default:
1284       /* not a texture src - do nothing */
1285       break;
1286    }
1287  
1288    return GL_TRUE;
1289 }
1290
1291
1292 /**
1293  * Generate instructions for loading all texture source terms.
1294  */
1295 static GLboolean
1296 load_texunit_sources( struct texenv_fragment_program *p, int unit )
1297 {
1298    const struct state_key *key = p->state;
1299    GLuint i;
1300
1301    for (i = 0; i < key->unit[unit].NumArgsRGB; i++) {
1302       load_texenv_source( p, key->unit[unit].OptRGB[i].Source, unit );
1303    }
1304
1305    for (i = 0; i < key->unit[unit].NumArgsA; i++) {
1306       load_texenv_source( p, key->unit[unit].OptA[i].Source, unit );
1307    }
1308
1309    return GL_TRUE;
1310 }
1311
1312 /**
1313  * Generate instructions for loading bump map textures.
1314  */
1315 static GLboolean
1316 load_texunit_bumpmap( struct texenv_fragment_program *p, int unit )
1317 {
1318    const struct state_key *key = p->state;
1319    GLuint bumpedUnitNr = key->unit[unit].OptRGB[1].Source - SRC_TEXTURE0;
1320    struct ureg texcDst, bumpMapRes;
1321    struct ureg constdudvcolor = register_const4f(p, 0.0, 0.0, 0.0, 1.0);
1322    struct ureg texcSrc = register_input(p, FRAG_ATTRIB_TEX0 + bumpedUnitNr);
1323    struct ureg rotMat0 = register_param3( p, STATE_INTERNAL, STATE_ROT_MATRIX_0, unit );
1324    struct ureg rotMat1 = register_param3( p, STATE_INTERNAL, STATE_ROT_MATRIX_1, unit );
1325
1326    load_texenv_source( p, unit + SRC_TEXTURE0, unit );
1327
1328    bumpMapRes = get_source(p, key->unit[unit].OptRGB[0].Source, unit);
1329    texcDst = get_tex_temp( p );
1330    p->texcoord_tex[bumpedUnitNr] = texcDst;
1331
1332    /* apply rot matrix and add coords to be available in next phase */
1333    /* dest = (Arg0.xxxx * rotMat0 + Arg1) + (Arg0.yyyy * rotMat1) */
1334    /* note only 2 coords are affected the rest are left unchanged (mul by 0) */
1335    emit_arith( p, OPCODE_MAD, texcDst, WRITEMASK_XYZW, 0,
1336                swizzle1(bumpMapRes, SWIZZLE_X), rotMat0, texcSrc );
1337    emit_arith( p, OPCODE_MAD, texcDst, WRITEMASK_XYZW, 0,
1338                swizzle1(bumpMapRes, SWIZZLE_Y), rotMat1, texcDst );
1339
1340    /* move 0,0,0,1 into bumpmap src if someone (crossbar) is foolish
1341       enough to access this later, should optimize away */
1342    emit_arith( p, OPCODE_MOV, bumpMapRes, WRITEMASK_XYZW, 0, constdudvcolor, undef, undef );
1343
1344    return GL_TRUE;
1345 }
1346
1347 /**
1348  * Generate a new fragment program which implements the context's
1349  * current texture env/combine mode.
1350  */
1351 static void
1352 create_new_program(GLcontext *ctx, struct state_key *key,
1353                    struct gl_fragment_program *program)
1354 {
1355    struct prog_instruction instBuffer[MAX_INSTRUCTIONS];
1356    struct texenv_fragment_program p;
1357    GLuint unit;
1358    struct ureg cf, out;
1359
1360    _mesa_memset(&p, 0, sizeof(p));
1361    p.ctx = ctx;
1362    p.state = key;
1363    p.program = program;
1364
1365    /* During code generation, use locally-allocated instruction buffer,
1366     * then alloc dynamic storage below.
1367     */
1368    p.program->Base.Instructions = instBuffer;
1369    p.program->Base.Target = GL_FRAGMENT_PROGRAM_ARB;
1370    p.program->Base.NumTexIndirections = 1;
1371    p.program->Base.NumTexInstructions = 0;
1372    p.program->Base.NumAluInstructions = 0;
1373    p.program->Base.String = NULL;
1374    p.program->Base.NumInstructions =
1375    p.program->Base.NumTemporaries =
1376    p.program->Base.NumParameters =
1377    p.program->Base.NumAttributes = p.program->Base.NumAddressRegs = 0;
1378    p.program->Base.Parameters = _mesa_new_parameter_list();
1379
1380    p.program->Base.InputsRead = 0;
1381    p.program->Base.OutputsWritten = 1 << FRAG_RESULT_COLOR;
1382
1383    for (unit = 0; unit < ctx->Const.MaxTextureUnits; unit++) {
1384       p.src_texture[unit] = undef;
1385       p.texcoord_tex[unit] = undef;
1386    }
1387
1388    p.src_previous = undef;
1389    p.half = undef;
1390    p.zero = undef;
1391    p.one = undef;
1392
1393    p.last_tex_stage = 0;
1394    release_temps(ctx, &p);
1395
1396    if (key->enabled_units) {
1397        GLboolean needbumpstage = GL_FALSE;
1398       /* Zeroth pass - bump map textures first */
1399       for (unit = 0 ; unit < ctx->Const.MaxTextureUnits ; unit++)
1400          if (key->unit[unit].enabled && key->unit[unit].ModeRGB == MODE_BUMP_ENVMAP_ATI) {
1401             needbumpstage = GL_TRUE;
1402             load_texunit_bumpmap( &p, unit );
1403          }
1404       if (needbumpstage)
1405          p.program->Base.NumTexIndirections++;
1406
1407       /* First pass - to support texture_env_crossbar, first identify
1408        * all referenced texture sources and emit texld instructions
1409        * for each:
1410        */
1411       for (unit = 0 ; unit < ctx->Const.MaxTextureUnits ; unit++)
1412          if (key->unit[unit].enabled) {
1413             load_texunit_sources( &p, unit );
1414             p.last_tex_stage = unit;
1415          }
1416
1417       /* Second pass - emit combine instructions to build final color:
1418        */
1419       for (unit = 0 ; unit < ctx->Const.MaxTextureUnits; unit++)
1420          if (key->enabled_units & (1<<unit)) {
1421             p.src_previous = emit_texenv( &p, unit );
1422             reserve_temp(&p, p.src_previous); /* don't re-use this temp reg */
1423             release_temps(ctx, &p);     /* release all temps */
1424          }
1425    }
1426
1427    cf = get_source( &p, SRC_PREVIOUS, 0 );
1428    out = make_ureg( PROGRAM_OUTPUT, FRAG_RESULT_COLOR );
1429
1430    if (key->separate_specular) {
1431       /* Emit specular add.
1432        */
1433       struct ureg s = register_input(&p, FRAG_ATTRIB_COL1);
1434       emit_arith( &p, OPCODE_ADD, out, WRITEMASK_XYZ, 0, cf, s, undef );
1435       emit_arith( &p, OPCODE_MOV, out, WRITEMASK_W, 0, cf, undef, undef );
1436    }
1437    else if (_mesa_memcmp(&cf, &out, sizeof(cf)) != 0) {
1438       /* Will wind up in here if no texture enabled or a couple of
1439        * other scenarios (GL_REPLACE for instance).
1440        */
1441       emit_arith( &p, OPCODE_MOV, out, WRITEMASK_XYZW, 0, cf, undef, undef );
1442    }
1443
1444    /* Finish up:
1445     */
1446    emit_arith( &p, OPCODE_END, undef, WRITEMASK_XYZW, 0, undef, undef, undef);
1447
1448    if (key->fog_enabled) {
1449       /* Pull fog mode from GLcontext, the value in the state key is
1450        * a reduced value and not what is expected in FogOption
1451        */
1452       p.program->FogOption = ctx->Fog.Mode;
1453       p.program->Base.InputsRead |= FRAG_BIT_FOGC; /* XXX new */
1454    } else
1455       p.program->FogOption = GL_NONE;
1456
1457    if (p.program->Base.NumTexIndirections > ctx->Const.FragmentProgram.MaxTexIndirections) 
1458       program_error(&p, "Exceeded max nr indirect texture lookups");
1459
1460    if (p.program->Base.NumTexInstructions > ctx->Const.FragmentProgram.MaxTexInstructions)
1461       program_error(&p, "Exceeded max TEX instructions");
1462
1463    if (p.program->Base.NumAluInstructions > ctx->Const.FragmentProgram.MaxAluInstructions)
1464       program_error(&p, "Exceeded max ALU instructions");
1465
1466    ASSERT(p.program->Base.NumInstructions <= MAX_INSTRUCTIONS);
1467
1468    /* Allocate final instruction array */
1469    p.program->Base.Instructions
1470       = _mesa_alloc_instructions(p.program->Base.NumInstructions);
1471    if (!p.program->Base.Instructions) {
1472       _mesa_error(ctx, GL_OUT_OF_MEMORY,
1473                   "generating tex env program");
1474       return;
1475    }
1476    _mesa_copy_instructions(p.program->Base.Instructions, instBuffer,
1477                            p.program->Base.NumInstructions);
1478
1479    if (p.program->FogOption) {
1480       _mesa_append_fog_code(ctx, p.program);
1481       p.program->FogOption = GL_NONE;
1482    }
1483
1484
1485    /* Notify driver the fragment program has (actually) changed.
1486     */
1487    if (ctx->Driver.ProgramStringNotify) {
1488       ctx->Driver.ProgramStringNotify( ctx, GL_FRAGMENT_PROGRAM_ARB, 
1489                                        &p.program->Base );
1490    }
1491
1492    if (DISASSEM) {
1493       _mesa_print_program(&p.program->Base);
1494       _mesa_printf("\n");
1495    }
1496 }
1497
1498
1499 /**
1500  * Return a fragment program which implements the current
1501  * fixed-function texture, fog and color-sum operations.
1502  */
1503 struct gl_fragment_program *
1504 _mesa_get_fixed_func_fragment_program(GLcontext *ctx)
1505 {
1506    struct gl_fragment_program *prog;
1507    struct state_key key;
1508         
1509    make_state_key(ctx, &key);
1510       
1511    prog = (struct gl_fragment_program *)
1512       _mesa_search_program_cache(ctx->FragmentProgram.Cache,
1513                                  &key, sizeof(key));
1514
1515    if (!prog) {
1516       prog = (struct gl_fragment_program *) 
1517          ctx->Driver.NewProgram(ctx, GL_FRAGMENT_PROGRAM_ARB, 0);
1518
1519       create_new_program(ctx, &key, prog);
1520
1521       _mesa_program_cache_insert(ctx, ctx->FragmentProgram.Cache,
1522                                  &key, sizeof(key), &prog->Base);
1523    }
1524
1525    return prog;
1526 }