t_vp_build.c revision 3509fd8c1b38d955a066a2bad429dbfba162fa30
1/*
2 * Mesa 3-D graphics library
3 * Version:  6.3
4 *
5 * Copyright (C) 2005  Tungsten Graphics   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 "Software"),
9 * to deal in the Software without restriction, including without limitation
10 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 * and/or sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included
15 * in all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
20 * TUNGSTEN GRAPHICS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21 * WHETHER IN
22 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 */
25
26/**
27 * \file t_vp_build.c
28 * Create a vertex program to execute the current fixed function T&L pipeline.
29 * \author Keith Whitwell
30 */
31
32
33#include <strings.h>
34
35#include "glheader.h"
36#include "macros.h"
37#include "enums.h"
38#include "t_context.h"
39#include "t_vp_build.h"
40
41#include "shader/program.h"
42#include "shader/nvvertprog.h"
43#include "shader/arbvertparse.h"
44
45
46/* Very useful debugging tool - produces annotated listing of
47 * generated program with line/function references for each
48 * instruction back into this file:
49 */
50#define DISASSEM 0
51
52#define MAX_INSN 200
53
54/* Use uregs to represent registers internally, translate to Mesa's
55 * expected formats on emit.
56 *
57 * NOTE: These are passed by value extensively in this file rather
58 * than as usual by pointer reference.  If this disturbs you, try
59 * remembering they are just 32bits in size.
60 *
61 * GCC is smart enough to deal with these dword-sized structures in
62 * much the same way as if I had defined them as dwords and was using
63 * macros to access and set the fields.  This is much nicer and easier
64 * to evolve.
65 */
66struct ureg {
67   GLuint file:4;
68   GLuint idx:8;
69   GLuint negate:1;
70   GLuint swz:12;
71   GLuint pad:7;
72};
73
74
75struct tnl_program {
76   GLcontext *ctx;
77   struct vertex_program *program;
78
79   GLuint temp_in_use;
80   GLuint temp_reserved;
81
82   struct ureg eye_position;
83   struct ureg eye_position_normalized;
84   struct ureg eye_normal;
85   struct ureg identity;
86
87   GLuint materials;
88   GLuint color_materials;
89};
90
91
92const static struct ureg undef = {
93   ~0,
94   ~0,
95   0,
96   0,
97   0
98};
99
100/* Local shorthand:
101 */
102#define X    SWIZZLE_X
103#define Y    SWIZZLE_Y
104#define Z    SWIZZLE_Z
105#define W    SWIZZLE_W
106
107
108/* Construct a ureg:
109 */
110static struct ureg make_ureg(GLuint file, GLuint idx)
111{
112   struct ureg reg;
113   reg.file = file;
114   reg.idx = idx;
115   reg.negate = 0;
116   reg.swz = SWIZZLE_NOOP;
117   reg.pad = 0;
118   return reg;
119}
120
121
122
123static struct ureg negate( struct ureg reg )
124{
125   reg.negate ^= 1;
126   return reg;
127}
128
129
130static struct ureg swizzle( struct ureg reg, int x, int y, int z, int w )
131{
132   reg.swz = MAKE_SWIZZLE4(GET_SWZ(reg.swz, x),
133			   GET_SWZ(reg.swz, y),
134			   GET_SWZ(reg.swz, z),
135			   GET_SWZ(reg.swz, w));
136
137   return reg;
138}
139
140static struct ureg swizzle1( struct ureg reg, int x )
141{
142   return swizzle(reg, x, x, x, x);
143}
144
145static struct ureg get_temp( struct tnl_program *p )
146{
147   int bit = ffs( ~p->temp_in_use );
148   if (!bit) {
149      fprintf(stderr, "%s: out of temporaries\n", __FILE__);
150      exit(1);
151   }
152
153   p->temp_in_use |= 1<<(bit-1);
154   return make_ureg(PROGRAM_TEMPORARY, bit-1);
155}
156
157static struct ureg reserve_temp( struct tnl_program *p )
158{
159   struct ureg temp = get_temp( p );
160   p->temp_reserved |= 1<<temp.idx;
161   return temp;
162}
163
164static void release_temp( struct tnl_program *p, struct ureg reg )
165{
166   if (reg.file == PROGRAM_TEMPORARY) {
167      p->temp_in_use &= ~(1<<reg.idx);
168      p->temp_in_use |= p->temp_reserved; /* can't release reserved temps */
169   }
170}
171
172static void release_temps( struct tnl_program *p )
173{
174   p->temp_in_use = p->temp_reserved;
175}
176
177
178
179static struct ureg register_input( struct tnl_program *p, GLuint input )
180{
181   p->program->InputsRead |= (1<<input);
182   return make_ureg(PROGRAM_INPUT, input);
183}
184
185static struct ureg register_output( struct tnl_program *p, GLuint output )
186{
187   p->program->OutputsWritten |= (1<<output);
188   return make_ureg(PROGRAM_OUTPUT, output);
189}
190
191static struct ureg register_const4f( struct tnl_program *p,
192			      GLfloat s0,
193			      GLfloat s1,
194			      GLfloat s2,
195			      GLfloat s3)
196{
197   GLfloat values[4];
198   GLuint idx;
199   values[0] = s0;
200   values[1] = s1;
201   values[2] = s2;
202   values[3] = s3;
203   idx = _mesa_add_unnamed_constant( p->program->Parameters, values );
204   return make_ureg(PROGRAM_STATE_VAR, idx);
205}
206
207#define register_const1f(p, s0)         register_const4f(p, s0, 0, 0, 1)
208#define register_const2f(p, s0, s1)     register_const4f(p, s0, s1, 0, 1)
209#define register_const3f(p, s0, s1, s2) register_const4f(p, s0, s1, s2, 1)
210
211static GLboolean is_undef( struct ureg reg )
212{
213   return reg.file == 0xf;
214}
215
216static struct ureg get_identity_param( struct tnl_program *p )
217{
218   if (is_undef(p->identity))
219      p->identity = register_const4f(p, 0,0,0,1);
220
221   return p->identity;
222}
223
224static struct ureg register_param6( struct tnl_program *p,
225				   GLint s0,
226				   GLint s1,
227				   GLint s2,
228				   GLint s3,
229				   GLint s4,
230				   GLint s5)
231{
232   GLint tokens[6];
233   GLuint idx;
234   tokens[0] = s0;
235   tokens[1] = s1;
236   tokens[2] = s2;
237   tokens[3] = s3;
238   tokens[4] = s4;
239   tokens[5] = s5;
240   idx = _mesa_add_state_reference( p->program->Parameters, tokens );
241   return make_ureg(PROGRAM_STATE_VAR, idx);
242}
243
244
245#define register_param1(p,s0)          register_param6(p,s0,0,0,0,0,0)
246#define register_param2(p,s0,s1)       register_param6(p,s0,s1,0,0,0,0)
247#define register_param3(p,s0,s1,s2)    register_param6(p,s0,s1,s2,0,0,0)
248#define register_param4(p,s0,s1,s2,s3) register_param6(p,s0,s1,s2,s3,0,0)
249
250
251static void register_matrix_param6( struct tnl_program *p,
252				    GLint s0,
253				    GLint s1,
254				    GLint s2,
255				    GLint s3,
256				    GLint s4,
257				    GLint s5,
258				    struct ureg *matrix )
259{
260   GLuint i;
261
262   /* This is a bit sad as the support is there to pull the whole
263    * matrix out in one go:
264    */
265   for (i = 0; i <= s4 - s3; i++)
266      matrix[i] = register_param6( p, s0, s1, s2, i, i, s5 );
267}
268
269
270static void emit_arg( struct vp_src_register *src,
271		      struct ureg reg )
272{
273   src->File = reg.file;
274   src->Index = reg.idx;
275   src->Swizzle = reg.swz;
276   src->Negate = reg.negate;
277   src->RelAddr = 0;
278   src->pad = 0;
279}
280
281static void emit_dst( struct vp_dst_register *dst,
282		      struct ureg reg, GLuint mask )
283{
284   dst->File = reg.file;
285   dst->Index = reg.idx;
286   /* allow zero as a shorthand for xyzw */
287   dst->WriteMask = mask ? mask : WRITEMASK_XYZW;
288   dst->pad = 0;
289}
290
291static void debug_insn( struct vp_instruction *inst, const char *fn,
292			GLuint line )
293{
294#if DISASSEM
295   static const char *last_fn;
296
297   if (fn != last_fn) {
298      last_fn = fn;
299      _mesa_printf("%s:\n", fn);
300   }
301
302   _mesa_printf("%d:\t", line);
303   _mesa_debug_vp_inst(1, inst);
304#endif
305}
306
307
308static void emit_op3fn(struct tnl_program *p,
309		       GLuint op,
310		       struct ureg dest,
311		       GLuint mask,
312		       struct ureg src0,
313		       struct ureg src1,
314		       struct ureg src2,
315		       const char *fn,
316		       GLuint line)
317{
318   GLuint nr = p->program->Base.NumInstructions++;
319   struct vp_instruction *inst = &p->program->Instructions[nr];
320
321   if (p->program->Base.NumInstructions > MAX_INSN) {
322      _mesa_problem(p->ctx, "Out of instructions in emit_op3fn\n");
323      return;
324   }
325
326   inst->Opcode = op;
327   inst->StringPos = 0;
328   inst->Data = 0;
329
330   emit_arg( &inst->SrcReg[0], src0 );
331   emit_arg( &inst->SrcReg[1], src1 );
332   emit_arg( &inst->SrcReg[2], src2 );
333
334   emit_dst( &inst->DstReg, dest, mask );
335
336   debug_insn(inst, fn, line);
337}
338
339
340
341#define emit_op3(p, op, dst, mask, src0, src1, src2) \
342   emit_op3fn(p, op, dst, mask, src0, src1, src2, __FUNCTION__, __LINE__)
343
344#define emit_op2(p, op, dst, mask, src0, src1) \
345    emit_op3fn(p, op, dst, mask, src0, src1, undef, __FUNCTION__, __LINE__)
346
347#define emit_op1(p, op, dst, mask, src0) \
348    emit_op3fn(p, op, dst, mask, src0, undef, undef, __FUNCTION__, __LINE__)
349
350
351static struct ureg make_temp( struct tnl_program *p, struct ureg reg )
352{
353   if (reg.file == PROGRAM_TEMPORARY &&
354       !(p->temp_reserved & (1<<reg.idx)))
355      return reg;
356   else {
357      struct ureg temp = get_temp(p);
358      emit_op1(p, VP_OPCODE_MOV, temp, 0, reg);
359      return temp;
360   }
361}
362
363
364/* Currently no tracking performed of input/output/register size or
365 * active elements.  Could be used to reduce these operations, as
366 * could the matrix type.
367 */
368static void emit_matrix_transform_vec4( struct tnl_program *p,
369					struct ureg dest,
370					const struct ureg *mat,
371					struct ureg src)
372{
373   emit_op2(p, VP_OPCODE_DP4, dest, WRITEMASK_X, src, mat[0]);
374   emit_op2(p, VP_OPCODE_DP4, dest, WRITEMASK_Y, src, mat[1]);
375   emit_op2(p, VP_OPCODE_DP4, dest, WRITEMASK_Z, src, mat[2]);
376   emit_op2(p, VP_OPCODE_DP4, dest, WRITEMASK_W, src, mat[3]);
377}
378
379/* This version is much easier to implement if writemasks are not
380 * supported natively on the target or (like SSE), the target doesn't
381 * have a clean/obvious dotproduct implementation.
382 */
383static void emit_transpose_matrix_transform_vec4( struct tnl_program *p,
384						  struct ureg dest,
385						  const struct ureg *mat,
386						  struct ureg src)
387{
388   struct ureg tmp;
389
390   if (dest.file != PROGRAM_TEMPORARY)
391      tmp = get_temp(p);
392   else
393      tmp = dest;
394
395   emit_op2(p, VP_OPCODE_MUL, tmp, 0, swizzle1(src,X), mat[0]);
396   emit_op3(p, VP_OPCODE_MAD, tmp, 0, swizzle1(src,Y), mat[1], tmp);
397   emit_op3(p, VP_OPCODE_MAD, tmp, 0, swizzle1(src,Z), mat[2], tmp);
398   emit_op3(p, VP_OPCODE_MAD, dest, 0, swizzle1(src,W), mat[3], tmp);
399
400   if (dest.file != PROGRAM_TEMPORARY)
401      release_temp(p, tmp);
402}
403
404static void emit_matrix_transform_vec3( struct tnl_program *p,
405					struct ureg dest,
406					const struct ureg *mat,
407					struct ureg src)
408{
409   emit_op2(p, VP_OPCODE_DP3, dest, WRITEMASK_X, src, mat[0]);
410   emit_op2(p, VP_OPCODE_DP3, dest, WRITEMASK_Y, src, mat[1]);
411   emit_op2(p, VP_OPCODE_DP3, dest, WRITEMASK_Z, src, mat[2]);
412}
413
414
415static void emit_normalize_vec3( struct tnl_program *p,
416				 struct ureg dest,
417				 struct ureg src )
418{
419   struct ureg tmp = get_temp(p);
420   emit_op2(p, VP_OPCODE_DP3, tmp, 0, src, src);
421   emit_op1(p, VP_OPCODE_RSQ, tmp, 0, tmp);
422   emit_op2(p, VP_OPCODE_MUL, dest, 0, src, tmp);
423   release_temp(p, tmp);
424}
425
426static struct ureg get_eye_position( struct tnl_program *p )
427{
428   if (is_undef(p->eye_position)) {
429      struct ureg pos = register_input( p, VERT_ATTRIB_POS );
430      struct ureg modelview[4];
431
432      register_matrix_param6( p, STATE_MATRIX, STATE_MODELVIEW, 0, 0, 3,
433			      STATE_MATRIX_TRANSPOSE, modelview );
434      p->eye_position = reserve_temp(p);
435
436      emit_transpose_matrix_transform_vec4(p, p->eye_position, modelview, pos);
437   }
438
439   return p->eye_position;
440}
441
442
443static struct ureg get_eye_position_normalized( struct tnl_program *p )
444{
445   if (is_undef(p->eye_position_normalized)) {
446      struct ureg eye = get_eye_position(p);
447      p->eye_position_normalized = reserve_temp(p);
448      emit_normalize_vec3(p, p->eye_position_normalized, eye);
449   }
450
451   return p->eye_position_normalized;
452}
453
454
455static struct ureg get_eye_normal( struct tnl_program *p )
456{
457   if (is_undef(p->eye_normal)) {
458      struct ureg normal = register_input(p, VERT_ATTRIB_NORMAL );
459      struct ureg mvinv[3];
460
461      register_matrix_param6( p, STATE_MATRIX, STATE_MODELVIEW, 0, 0, 2,
462			      STATE_MATRIX_INVTRANS, mvinv );
463
464      p->eye_normal = reserve_temp(p);
465
466      /* Transform to eye space:
467       */
468      emit_matrix_transform_vec3( p, p->eye_normal, mvinv, normal );
469
470      /* Normalize/Rescale:
471       */
472      if (p->ctx->Transform.Normalize) {
473	 emit_normalize_vec3( p, p->eye_normal, p->eye_normal );
474      }
475      else if (p->ctx->Transform.RescaleNormals) {
476	 struct ureg rescale = register_param2(p, STATE_INTERNAL,
477					       STATE_NORMAL_SCALE);
478
479	 emit_op2( p, VP_OPCODE_MUL, p->eye_normal, 0, normal,
480		   swizzle1(rescale, X));
481      }
482   }
483
484   return p->eye_normal;
485}
486
487
488
489static void build_hpos( struct tnl_program *p )
490{
491   struct ureg pos = register_input( p, VERT_ATTRIB_POS );
492   struct ureg hpos = register_output( p, VERT_RESULT_HPOS );
493   struct ureg mvp[4];
494
495   register_matrix_param6( p, STATE_MATRIX, STATE_MVP, 0, 0, 3,
496			   STATE_MATRIX_TRANSPOSE, mvp );
497   emit_transpose_matrix_transform_vec4( p, hpos, mvp, pos );
498}
499
500
501static GLuint material_attrib( GLuint side, GLuint property )
502{
503   return (_TNL_ATTRIB_MAT_FRONT_AMBIENT +
504	   (property - STATE_AMBIENT) * 2 +
505	   side);
506}
507
508static void set_material_flags( struct tnl_program *p )
509{
510   GLcontext *ctx = p->ctx;
511   TNLcontext *tnl = TNL_CONTEXT(ctx);
512   GLuint i;
513
514   p->color_materials = 0;
515   p->materials = 0;
516
517   if (ctx->Light.ColorMaterialEnabled) {
518      p->materials =
519	 p->color_materials =
520	 ctx->Light.ColorMaterialBitmask << _TNL_ATTRIB_MAT_FRONT_AMBIENT;
521   }
522
523   for (i = _TNL_ATTRIB_MAT_FRONT_AMBIENT ; i < _TNL_ATTRIB_INDEX ; i++)
524      if (tnl->vb.AttribPtr[i]->stride)
525	 p->materials |= 1<<i;
526}
527
528
529static struct ureg get_material( struct tnl_program *p, GLuint side,
530				 GLuint property )
531{
532   GLuint attrib = material_attrib(side, property);
533
534   if (p->color_materials & (1<<attrib))
535      return register_input(p, VERT_ATTRIB_COLOR0);
536   else if (p->materials & (1<<attrib))
537      return register_input( p, attrib );
538   else
539      return register_param3( p, STATE_MATERIAL, side, property );
540}
541
542#define SCENE_COLOR_BITS(side) (( _TNL_BIT_MAT_FRONT_EMISSION | \
543				   _TNL_BIT_MAT_FRONT_AMBIENT | \
544				   _TNL_BIT_MAT_FRONT_DIFFUSE) << (side))
545
546/* Either return a precalculated constant value or emit code to
547 * calculate these values dynamically in the case where material calls
548 * are present between begin/end pairs.
549 *
550 * Probably want to shift this to the program compilation phase - if
551 * we always emitted the calculation here, a smart compiler could
552 * detect that it was constant (given a certain set of inputs), and
553 * lift it out of the main loop.  That way the programs created here
554 * would be independent of the vertex_buffer details.
555 */
556static struct ureg get_scenecolor( struct tnl_program *p, GLuint side )
557{
558   if (p->materials & SCENE_COLOR_BITS(side)) {
559      struct ureg lm_ambient = register_param1(p, STATE_LIGHTMODEL_AMBIENT);
560      struct ureg material_emission = get_material(p, side, STATE_EMISSION);
561      struct ureg material_ambient = get_material(p, side, STATE_AMBIENT);
562      struct ureg material_diffuse = get_material(p, side, STATE_DIFFUSE);
563      struct ureg tmp = make_temp(p, material_diffuse);
564      emit_op3(p, VP_OPCODE_MAD, tmp,  WRITEMASK_XYZ, lm_ambient,
565	       material_ambient, material_emission);
566      return tmp;
567   }
568   else
569      return register_param2( p, STATE_LIGHTMODEL_SCENECOLOR, side );
570}
571
572
573static struct ureg get_lightprod( struct tnl_program *p, GLuint light,
574				  GLuint side, GLuint property )
575{
576   GLuint attrib = material_attrib(side, property);
577   if (p->materials & (1<<attrib)) {
578      struct ureg light_value =
579	 register_param3(p, STATE_LIGHT, light, property);
580      struct ureg material_value = get_material(p, side, property);
581      struct ureg tmp = get_temp(p);
582      emit_op2(p, VP_OPCODE_MUL, tmp,  0, light_value, material_value);
583      return tmp;
584   }
585   else
586      return register_param4(p, STATE_LIGHTPROD, light, side, property);
587}
588
589static struct ureg calculate_light_attenuation( struct tnl_program *p,
590						GLuint i,
591						struct gl_light *light,
592						struct ureg VPpli,
593						struct ureg dist )
594{
595   struct ureg attenuation = register_param3(p, STATE_LIGHT, i,
596					     STATE_ATTENUATION);
597   struct ureg att = get_temp(p);
598
599   /* Calculate spot attenuation:
600    */
601   if (light->SpotCutoff != 180.0F) {
602      struct ureg spot_dir = register_param3(p, STATE_LIGHT, i,
603					     STATE_SPOT_DIRECTION);
604      struct ureg spot = get_temp(p);
605      struct ureg slt = get_temp(p);
606
607      emit_normalize_vec3( p, spot, spot_dir ); /* XXX: precompute! */
608      emit_op2(p, VP_OPCODE_DP3, spot, 0, negate(VPpli), spot_dir);
609      emit_op2(p, VP_OPCODE_SLT, slt, 0, swizzle1(spot_dir,W), spot);
610      emit_op2(p, VP_OPCODE_POW, spot, 0, spot, swizzle1(attenuation, W));
611      emit_op2(p, VP_OPCODE_MUL, att, 0, slt, spot);
612
613      release_temp(p, spot);
614      release_temp(p, slt);
615   }
616
617   /* Calculate distance attenuation:
618    */
619   if (light->ConstantAttenuation != 1.0 ||
620       light->LinearAttenuation != 1.0 ||
621       light->QuadraticAttenuation != 1.0) {
622
623      /* 1/d,d,d,1/d */
624      emit_op1(p, VP_OPCODE_RCP, dist, WRITEMASK_YZ, dist);
625      /* 1,d,d*d,1/d */
626      emit_op2(p, VP_OPCODE_MUL, dist, WRITEMASK_XZ, dist, swizzle1(dist,Y));
627      /* 1/dist-atten */
628      emit_op2(p, VP_OPCODE_DP3, dist, 0, attenuation, dist);
629
630      if (light->SpotCutoff != 180.0F) {
631	 /* dist-atten */
632	 emit_op1(p, VP_OPCODE_RCP, dist, 0, dist);
633	 /* spot-atten * dist-atten */
634	 emit_op2(p, VP_OPCODE_MUL, att, 0, dist, att);
635      } else {
636	 /* dist-atten */
637	 emit_op1(p, VP_OPCODE_RCP, att, 0, dist);
638      }
639   }
640
641   return att;
642}
643
644
645
646
647
648/* Need to add some addtional parameters to allow lighting in object
649 * space - STATE_SPOT_DIRECTION and STATE_HALF implicitly assume eye
650 * space lighting.
651 */
652static void build_lighting( struct tnl_program *p )
653{
654   GLcontext *ctx = p->ctx;
655   const GLboolean twoside = ctx->Light.Model.TwoSide;
656   const GLboolean separate = (ctx->Light.Model.ColorControl ==
657			       GL_SEPARATE_SPECULAR_COLOR);
658   GLuint nr_lights = 0, count = 0;
659   struct ureg normal = get_eye_normal(p);
660   struct ureg lit = get_temp(p);
661   struct ureg dots = get_temp(p);
662   struct ureg _col0 = undef, _col1 = undef;
663   struct ureg _bfc0 = undef, _bfc1 = undef;
664   GLuint i;
665
666   for (i = 0; i < MAX_LIGHTS; i++)
667      if (ctx->Light.Light[i].Enabled)
668	 nr_lights++;
669
670   set_material_flags(p);
671
672   {
673      struct ureg shininess = get_material(p, 0, STATE_SHININESS);
674      emit_op1(p, VP_OPCODE_MOV, dots,  WRITEMASK_W, swizzle1(shininess,X));
675      release_temp(p, shininess);
676
677      _col0 = make_temp(p, get_scenecolor(p, 0));
678      if (separate)
679	 _col1 = make_temp(p, get_identity_param(p));
680      else
681	 _col1 = _col0;
682
683   }
684
685   if (twoside) {
686      struct ureg shininess = get_material(p, 1, STATE_SHININESS);
687      emit_op1(p, VP_OPCODE_MOV, dots, WRITEMASK_Z,
688	       negate(swizzle1(shininess,X)));
689      release_temp(p, shininess);
690
691      _bfc0 = make_temp(p, get_scenecolor(p, 1));
692      if (separate)
693	 _bfc1 = make_temp(p, get_identity_param(p));
694      else
695	 _bfc1 = _bfc0;
696   }
697
698   for (i = 0; i < MAX_LIGHTS; i++) {
699      struct gl_light *light = &ctx->Light.Light[i];
700
701      if (light->Enabled) {
702	 struct ureg half = undef;
703	 struct ureg att = undef, VPpli = undef;
704
705	 count++;
706
707	 if (light->EyePosition[3] == 0) {
708	    /* Can used precomputed constants in this case.
709	     * Attenuation never applies to infinite lights.
710	     */
711	    VPpli = register_param3(p, STATE_LIGHT, i,
712				    STATE_POSITION_NORMALIZED);
713	    half = register_param3(p, STATE_LIGHT, i, STATE_HALF);
714	 }
715	 else {
716	    struct ureg Ppli = register_param3(p, STATE_LIGHT, i,
717					       STATE_POSITION);
718	    struct ureg V = get_eye_position(p);
719	    struct ureg dist = get_temp(p);
720
721	    VPpli = get_temp(p);
722	    half = get_temp(p);
723
724	    /* Calulate VPpli vector
725	     */
726	    emit_op2(p, VP_OPCODE_SUB, VPpli, 0, Ppli, V);
727
728	    /* Normalize VPpli.  The dist value also used in
729	     * attenuation below.
730	     */
731	    emit_op2(p, VP_OPCODE_DP3, dist, 0, VPpli, VPpli);
732	    emit_op1(p, VP_OPCODE_RSQ, dist, 0, dist);
733	    emit_op2(p, VP_OPCODE_MUL, VPpli, 0, VPpli, dist);
734
735
736	    /* Calculate  attenuation:
737	     */
738	    if (light->SpotCutoff != 180.0 ||
739		light->ConstantAttenuation != 1.0 ||
740		light->LinearAttenuation != 1.0 ||
741		light->QuadraticAttenuation != 1.0) {
742	       att = calculate_light_attenuation(p, i, light, VPpli, dist);
743	    }
744
745
746	    /* Calculate viewer direction, or use infinite viewer:
747	     */
748	    if (ctx->Light.Model.LocalViewer) {
749	       struct ureg eye_hat = get_eye_position_normalized(p);
750	       emit_op2(p, VP_OPCODE_SUB, half, 0, VPpli, eye_hat);
751	    }
752	    else {
753	       struct ureg z_dir = swizzle(get_identity_param(p),X,Y,W,Z);
754	       emit_op2(p, VP_OPCODE_ADD, half, 0, VPpli, z_dir);
755	    }
756
757	    emit_normalize_vec3(p, half, half);
758
759	    release_temp(p, dist);
760	 }
761
762	 /* Calculate dot products:
763	  */
764	 emit_op2(p, VP_OPCODE_DP3, dots, WRITEMASK_X, normal, VPpli);
765	 emit_op2(p, VP_OPCODE_DP3, dots, WRITEMASK_Y, normal, half);
766
767
768	 /* Front face lighting:
769	  */
770	 {
771	    struct ureg ambient = get_lightprod(p, i, 0, STATE_AMBIENT);
772	    struct ureg diffuse = get_lightprod(p, i, 0, STATE_DIFFUSE);
773	    struct ureg specular = get_lightprod(p, i, 0, STATE_SPECULAR);
774	    struct ureg res0, res1;
775
776	    emit_op1(p, VP_OPCODE_LIT, lit, 0, dots);
777
778	    if (!is_undef(att))
779	       emit_op2(p, VP_OPCODE_MUL, lit, 0, lit, att);
780
781
782	    if (count == nr_lights) {
783	       if (separate) {
784		  res0 = register_output( p, VERT_RESULT_COL0 );
785		  res1 = register_output( p, VERT_RESULT_COL1 );
786	       }
787	       else {
788		  res0 = _col0;
789		  res1 = register_output( p, VERT_RESULT_COL0 );
790	       }
791	    } else {
792	       res0 = _col0;
793	       res1 = _col1;
794	    }
795
796	    emit_op3(p, VP_OPCODE_MAD, _col0, 0, swizzle1(lit,X), ambient, _col0);
797	    emit_op3(p, VP_OPCODE_MAD, res0, 0, swizzle1(lit,Y), diffuse, _col0);
798	    emit_op3(p, VP_OPCODE_MAD, res1, 0, swizzle1(lit,Z), specular, _col1);
799
800	    release_temp(p, ambient);
801	    release_temp(p, diffuse);
802	    release_temp(p, specular);
803	 }
804
805	 /* Back face lighting:
806	  */
807	 if (twoside) {
808	    struct ureg ambient = get_lightprod(p, i, 1, STATE_AMBIENT);
809	    struct ureg diffuse = get_lightprod(p, i, 1, STATE_DIFFUSE);
810	    struct ureg specular = get_lightprod(p, i, 1, STATE_SPECULAR);
811	    struct ureg res0, res1;
812
813	    emit_op1(p, VP_OPCODE_LIT, lit, 0, negate(swizzle(dots,X,Y,W,Z)));
814
815	    if (!is_undef(att))
816	       emit_op2(p, VP_OPCODE_MUL, lit, 0, lit, att);
817
818	    if (count == nr_lights) {
819	       if (separate) {
820		  res0 = register_output( p, VERT_RESULT_BFC0 );
821		  res1 = register_output( p, VERT_RESULT_BFC1 );
822	       }
823	       else {
824		  res0 = _bfc0;
825		  res1 = register_output( p, VERT_RESULT_BFC0 );
826	       }
827	    } else {
828	       res0 = _bfc0;
829	       res1 = _bfc1;
830	    }
831
832
833	    emit_op3(p, VP_OPCODE_MAD, _bfc0, 0, swizzle1(lit,X), ambient, _bfc0);
834	    emit_op3(p, VP_OPCODE_MAD, res0, 0, swizzle1(lit,Y), diffuse, _bfc0);
835	    emit_op3(p, VP_OPCODE_MAD, res1, 0, swizzle1(lit,Z), specular, _bfc1);
836
837	    release_temp(p, ambient);
838	    release_temp(p, diffuse);
839	    release_temp(p, specular);
840	 }
841
842	 release_temp(p, half);
843	 release_temp(p, VPpli);
844	 release_temp(p, att);
845      }
846   }
847
848   release_temps( p );
849}
850
851
852static void build_fog( struct tnl_program *p )
853{
854   GLcontext *ctx = p->ctx;
855   TNLcontext *tnl = TNL_CONTEXT(ctx);
856   struct ureg fog = register_output(p, VERT_RESULT_FOGC);
857   struct ureg input;
858
859   if (ctx->Fog.FogCoordinateSource == GL_FRAGMENT_DEPTH_EXT) {
860      input = swizzle1(get_eye_position(p), Z);
861   }
862   else {
863      input = swizzle1(register_input(p, VERT_ATTRIB_FOG), X);
864   }
865
866   if (tnl->_DoVertexFog) {
867      struct ureg params = register_param1(p, STATE_FOG_PARAMS);
868      struct ureg tmp = get_temp(p);
869
870      switch (ctx->Fog.Mode) {
871      case GL_LINEAR: {
872	 struct ureg id = get_identity_param(p);
873	 emit_op2(p, VP_OPCODE_SUB, tmp, 0, swizzle1(params,Z), input);
874	 emit_op2(p, VP_OPCODE_MUL, tmp, 0, tmp, swizzle1(params,W));
875	 emit_op2(p, VP_OPCODE_MAX, tmp, 0, tmp, swizzle1(id,X)); /* saturate */
876	 emit_op2(p, VP_OPCODE_MIN, fog, WRITEMASK_X, tmp, swizzle1(id,W));
877	 break;
878      }
879      case GL_EXP:
880	 emit_op1(p, VP_OPCODE_ABS, tmp, 0, input);
881	 emit_op2(p, VP_OPCODE_MUL, tmp, 0, tmp, swizzle1(params,X));
882	 emit_op2(p, VP_OPCODE_POW, fog, WRITEMASK_X,
883		  register_const1f(p, M_E), negate(tmp));
884	 break;
885      case GL_EXP2:
886	 emit_op2(p, VP_OPCODE_MUL, tmp, 0, input, swizzle1(params,X));
887	 emit_op2(p, VP_OPCODE_MUL, tmp, 0, tmp, tmp);
888	 emit_op2(p, VP_OPCODE_POW, fog, WRITEMASK_X,
889		  register_const1f(p, M_E), negate(tmp));
890	 break;
891      }
892
893      release_temp(p, tmp);
894   }
895   else {
896      /* results = incoming fog coords (compute fog per-fragment later)
897       *
898       * KW:  Is it really necessary to do anything in this case?
899       */
900      emit_op1(p, VP_OPCODE_MOV, fog, WRITEMASK_X, input);
901   }
902}
903
904static void build_reflect_texgen( struct tnl_program *p,
905				  struct ureg dest,
906				  GLuint writemask )
907{
908   struct ureg normal = get_eye_normal(p);
909   struct ureg eye_hat = get_eye_position_normalized(p);
910   struct ureg tmp = get_temp(p);
911
912   /* n.u */
913   emit_op2(p, VP_OPCODE_DP3, tmp, 0, normal, eye_hat);
914   /* 2n.u */
915   emit_op2(p, VP_OPCODE_ADD, tmp, 0, tmp, tmp);
916   /* (-2n.u)n + u */
917   emit_op3(p, VP_OPCODE_MAD, dest, writemask, negate(tmp), normal, eye_hat);
918}
919
920static void build_sphere_texgen( struct tnl_program *p,
921				 struct ureg dest,
922				 GLuint writemask )
923{
924   struct ureg normal = get_eye_normal(p);
925   struct ureg eye_hat = get_eye_position_normalized(p);
926   struct ureg tmp = get_temp(p);
927   struct ureg half = register_const1f(p, .5);
928   struct ureg r = get_temp(p);
929   struct ureg inv_m = get_temp(p);
930   struct ureg id = get_identity_param(p);
931
932   /* Could share the above calculations, but it would be
933    * a fairly odd state for someone to set (both sphere and
934    * reflection active for different texture coordinate
935    * components.  Of course - if two texture units enable
936    * reflect and/or sphere, things start to tilt in favour
937    * of seperating this out:
938    */
939
940   /* n.u */
941   emit_op2(p, VP_OPCODE_DP3, tmp, 0, normal, eye_hat);
942   /* 2n.u */
943   emit_op2(p, VP_OPCODE_ADD, tmp, 0, tmp, tmp);
944   /* (-2n.u)n + u */
945   emit_op3(p, VP_OPCODE_MAD, r, 0, negate(tmp), normal, eye_hat);
946   /* r + 0,0,1 */
947   emit_op2(p, VP_OPCODE_ADD, tmp, 0, r, swizzle(id,X,Y,W,Z));
948   /* rx^2 + ry^2 + (rz+1)^2 */
949   emit_op2(p, VP_OPCODE_DP3, tmp, 0, tmp, tmp);
950   /* 2/m */
951   emit_op1(p, VP_OPCODE_RSQ, tmp, 0, tmp);
952   /* 1/m */
953   emit_op2(p, VP_OPCODE_MUL, inv_m, 0, tmp, swizzle1(half,X));
954   /* r/m + 1/2 */
955   emit_op3(p, VP_OPCODE_MAD, dest, writemask, r, inv_m, swizzle1(half,X));
956
957   release_temp(p, tmp);
958   release_temp(p, r);
959   release_temp(p, inv_m);
960}
961
962
963static void build_texture_transform( struct tnl_program *p )
964{
965   GLcontext *ctx = p->ctx;
966   GLuint i, j;
967
968   for (i = 0; i < ctx->Const.MaxTextureCoordUnits; i++) {
969      struct gl_texture_unit *texUnit = &ctx->Texture.Unit[i];
970      GLuint texmat_enabled = ctx->Texture._TexMatEnabled & ENABLE_TEXMAT(i);
971      struct ureg out = register_output(p, VERT_RESULT_TEX0 + i);
972
973      if (texUnit->TexGenEnabled || texmat_enabled) {
974	 struct ureg out_texgen = undef;
975
976	 if (texUnit->TexGenEnabled) {
977	    GLuint copy_mask = 0;
978	    GLuint sphere_mask = 0;
979	    GLuint reflect_mask = 0;
980	    GLuint normal_mask = 0;
981	    GLuint modes[4];
982
983	    if (texmat_enabled)
984	       out_texgen = get_temp(p);
985	    else
986	       out_texgen = out;
987
988	    modes[0] = texUnit->GenModeS;
989	    modes[1] = texUnit->GenModeT;
990	    modes[2] = texUnit->GenModeR;
991	    modes[3] = texUnit->GenModeQ;
992
993	    for (j = 0; j < 4; j++) {
994	       if (texUnit->TexGenEnabled & (1<<j)) {
995		  switch (modes[j]) {
996		  case GL_OBJECT_LINEAR: {
997		     struct ureg obj = register_input(p, VERT_ATTRIB_POS);
998		     struct ureg plane =
999			register_param3(p, STATE_TEXGEN, i,
1000					STATE_TEXGEN_OBJECT_S + j);
1001
1002		     emit_op2(p, VP_OPCODE_DP4, out_texgen, WRITEMASK_X << j,
1003			      obj, plane );
1004		     break;
1005		  }
1006		  case GL_EYE_LINEAR: {
1007		     struct ureg eye = get_eye_position(p);
1008		     struct ureg plane =
1009			register_param3(p, STATE_TEXGEN, i,
1010					STATE_TEXGEN_EYE_S + j);
1011
1012		     emit_op2(p, VP_OPCODE_DP4, out_texgen, WRITEMASK_X << j,
1013			      eye, plane );
1014		     break;
1015		  }
1016		  case GL_SPHERE_MAP:
1017		     sphere_mask |= WRITEMASK_X << j;
1018		     break;
1019		  case GL_REFLECTION_MAP_NV:
1020		     reflect_mask |= WRITEMASK_X << j;
1021		     break;
1022		  case GL_NORMAL_MAP_NV:
1023		     normal_mask |= WRITEMASK_X << j;
1024		     break;
1025		  }
1026	       }
1027	       else
1028		  copy_mask |= WRITEMASK_X << j;
1029	    }
1030
1031
1032	    if (sphere_mask) {
1033	       build_sphere_texgen(p, out_texgen, sphere_mask);
1034	    }
1035
1036	    if (reflect_mask) {
1037	       build_reflect_texgen(p, out_texgen, reflect_mask);
1038	    }
1039
1040	    if (normal_mask) {
1041	       struct ureg normal = get_eye_normal(p);
1042	       emit_op1(p, VP_OPCODE_MOV, out_texgen, normal_mask, normal );
1043	    }
1044
1045	    if (copy_mask) {
1046	       struct ureg in = register_input(p, VERT_ATTRIB_TEX0+i);
1047	       emit_op1(p, VP_OPCODE_MOV, out_texgen, copy_mask, in );
1048	    }
1049	 }
1050
1051	 if (texmat_enabled) {
1052	    struct ureg texmat[4];
1053	    struct ureg in = (!is_undef(out_texgen) ?
1054			      out_texgen :
1055			      register_input(p, VERT_ATTRIB_TEX0+i));
1056	    register_matrix_param6( p, STATE_MATRIX, STATE_TEXTURE, i,
1057				    0, 3, 0, texmat );
1058	    emit_matrix_transform_vec4( p, out, texmat, in );
1059	 }
1060
1061	 release_temps(p);
1062      }
1063   }
1064}
1065
1066
1067/* Seems like it could be tighter:
1068 */
1069static void build_pointsize( struct tnl_program *p )
1070{
1071   struct ureg eye = get_eye_position(p);
1072   struct ureg state_size = register_param1(p, STATE_POINT_SIZE);
1073   struct ureg state_attenuation = register_param1(p, STATE_POINT_ATTENUATION);
1074   struct ureg out = register_output(p, VERT_RESULT_PSIZ);
1075   struct ureg ut = get_temp(p);
1076
1077   /* 1, -Z, Z * Z, 1 */
1078   emit_op1(p, VP_OPCODE_MOV, ut, 0, swizzle1(get_identity_param(p), W));
1079   emit_op2(p, VP_OPCODE_MUL, ut, WRITEMASK_YZ, ut, negate(swizzle1(eye, Z)));
1080   emit_op2(p, VP_OPCODE_MUL, ut, WRITEMASK_Z, ut, negate(swizzle1(eye, Z)));
1081
1082
1083   /* p1 +  p2 * dist + p3 * dist * dist, 0 */
1084   emit_op2(p, VP_OPCODE_DP3, ut, 0, ut, state_attenuation);
1085
1086   /* 1 / factor */
1087   emit_op1(p, VP_OPCODE_RCP, ut, 0, ut );
1088
1089   /* out = pointSize / factor */
1090   emit_op2(p, VP_OPCODE_MUL, out, WRITEMASK_X, ut, state_size);
1091
1092   release_temp(p, ut);
1093}
1094
1095
1096static void build_passthrough( struct tnl_program *p, GLuint inputs )
1097{
1098}
1099
1100
1101static GLboolean programs_eq( struct vertex_program *a,
1102			      struct vertex_program *b )
1103{
1104   if (!a || !b)
1105      return GL_FALSE;
1106
1107   if (a->Base.NumInstructions != b->Base.NumInstructions ||
1108       a->Parameters->NumParameters != b->Parameters->NumParameters)
1109      return GL_FALSE;
1110
1111   if (memcmp(a->Instructions, b->Instructions,
1112	      a->Base.NumInstructions * sizeof(struct vp_instruction)) != 0)
1113      return GL_FALSE;
1114
1115   if (memcmp(a->Parameters->Parameters, b->Parameters->Parameters,
1116	      a->Parameters->NumParameters *
1117	      sizeof(struct program_parameter)) != 0)
1118      return GL_FALSE;
1119
1120   return GL_TRUE;
1121}
1122
1123
1124void _tnl_UpdateFixedFunctionProgram( GLcontext *ctx )
1125{
1126   TNLcontext *tnl = TNL_CONTEXT(ctx);
1127   struct tnl_program p;
1128
1129   if (ctx->VertexProgram._Enabled)
1130      return;
1131
1132
1133   memset(&p, 0, sizeof(p));
1134   p.ctx = ctx;
1135   p.program = (struct vertex_program *)ctx->Driver.NewProgram(ctx, GL_VERTEX_PROGRAM_ARB, 0);
1136   p.eye_position = undef;
1137   p.eye_position_normalized = undef;
1138   p.eye_normal = undef;
1139   p.identity = undef;
1140
1141   p.temp_in_use = 0;
1142
1143   if (ctx->Const.MaxVertexProgramTemps >= sizeof(int) * 8)
1144      p.temp_reserved = 0;
1145   else
1146      p.temp_reserved = ~((1<<ctx->Const.MaxVertexProgramTemps)-1);
1147
1148   p.program->Instructions = MALLOC(sizeof(struct vp_instruction) * MAX_INSN);
1149
1150   /* Initialize the arb_program struct */
1151   p.program->Base.String = 0;
1152   p.program->Base.NumInstructions =
1153   p.program->Base.NumTemporaries =
1154   p.program->Base.NumParameters =
1155   p.program->Base.NumAttributes = p.program->Base.NumAddressRegs = 0;
1156
1157   if (p.program->Parameters)
1158      _mesa_free_parameters(p.program->Parameters);
1159   else
1160      p.program->Parameters = _mesa_new_parameter_list();
1161
1162   p.program->InputsRead = 0;
1163   p.program->OutputsWritten = 0;
1164
1165   /* Emit the program, starting with modelviewproject:
1166    */
1167   build_hpos(&p);
1168
1169   /* Lighting calculations:
1170    */
1171   if (ctx->Light.Enabled)
1172      build_lighting(&p);
1173
1174   if (ctx->Fog.Enabled)
1175      build_fog(&p);
1176
1177   if (ctx->Texture._TexGenEnabled || ctx->Texture._TexMatEnabled)
1178      build_texture_transform(&p);
1179
1180   if (ctx->Point._Attenuated)
1181      build_pointsize(&p);
1182
1183   /* Is there a need to copy inputs to outputs?  The software
1184    * implementation might do this more efficiently by just assigning
1185    * the missing results to point at input arrays.
1186    */
1187   if (/* tnl->vp_copy_inputs &&  */
1188       (tnl->render_inputs & ~p.program->OutputsWritten)) {
1189      build_passthrough(&p, tnl->render_inputs);
1190   }
1191
1192
1193   /* Finish up:
1194    */
1195   emit_op1(&p, VP_OPCODE_END, undef, 0, undef);
1196
1197   /* Disassemble:
1198    */
1199   if (DISASSEM) {
1200      _mesa_printf ("\n");
1201   }
1202
1203
1204   /* Notify driver the fragment program has (actually) changed.
1205    */
1206   if (!programs_eq(ctx->_TnlProgram, p.program) != 0) {
1207      if (ctx->_TnlProgram)
1208	 ctx->Driver.DeleteProgram( ctx, &ctx->_TnlProgram->Base );
1209      ctx->_TnlProgram = p.program;
1210   }
1211   else if (p.program) {
1212      /* Nothing changed...
1213       */
1214      ctx->Driver.DeleteProgram( ctx, &p.program->Base );
1215   }
1216}
1217