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