First new particle code:
[blender-staging.git] / source / blender / render / intern / source / convertblender.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * Contributors: 2004/2005/2006 Blender Foundation, full recode
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 #include <math.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <limits.h>
33
34 #include "MTC_matrixops.h"
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_arithb.h"
39 #include "BLI_blenlib.h"
40 #include "BLI_rand.h"
41 #include "BLI_memarena.h"
42 #include "BLI_ghash.h"
43
44 #include "DNA_armature_types.h"
45 #include "DNA_camera_types.h"
46 #include "DNA_material_types.h"
47 #include "DNA_curve_types.h"
48 #include "DNA_effect_types.h"
49 #include "DNA_group_types.h"
50 #include "DNA_lamp_types.h"
51 #include "DNA_image_types.h"
52 #include "DNA_lattice_types.h"
53 #include "DNA_mesh_types.h"
54 #include "DNA_meshdata_types.h"
55 #include "DNA_meta_types.h"
56 #include "DNA_modifier_types.h"
57 #include "DNA_node_types.h"
58 #include "DNA_object_types.h"
59 #include "DNA_object_force.h"
60 #include "DNA_object_fluidsim.h"
61 #include "DNA_particle_types.h"
62 #include "DNA_scene_types.h"
63 #include "DNA_texture_types.h"
64 #include "DNA_view3d_types.h"
65
66 #include "BKE_anim.h"
67 #include "BKE_armature.h"
68 #include "BKE_action.h"
69 #include "BKE_curve.h"
70 #include "BKE_customdata.h"
71 #include "BKE_colortools.h"
72 #include "BKE_constraint.h"
73 #include "BKE_displist.h"
74 #include "BKE_deform.h"
75 #include "BKE_DerivedMesh.h"
76 #include "BKE_effect.h"
77 #include "BKE_global.h"
78 #include "BKE_group.h"
79 #include "BKE_key.h"
80 #include "BKE_ipo.h"
81 #include "BKE_image.h"
82 #include "BKE_lattice.h"
83 #include "BKE_library.h"
84 #include "BKE_material.h"
85 #include "BKE_main.h"
86 #include "BKE_mball.h"
87 #include "BKE_mesh.h"
88 #include "BKE_modifier.h"
89 #include "BKE_node.h"
90 #include "BKE_object.h"
91 #include "BKE_particle.h"
92 #include "BKE_scene.h"
93 #include "BKE_subsurf.h"
94 #include "BKE_texture.h"
95 #include "BKE_utildefines.h"
96 #include "BKE_world.h"
97
98 #include "PIL_time.h"
99 #include "IMB_imbuf_types.h"
100
101 #include "envmap.h"
102 #include "occlusion.h"
103 #include "render_types.h"
104 #include "rendercore.h"
105 #include "renderdatabase.h"
106 #include "renderpipeline.h"
107 #include "radio.h"
108 #include "shadbuf.h"
109 #include "shading.h"
110 #include "strand.h"
111 #include "texture.h"
112 #include "sss.h"
113 #include "strand.h"
114 #include "zbuf.h"
115 #include "sunsky.h"
116
117
118 /* 10 times larger than normal epsilon, test it on default nurbs sphere with ray_transp (for quad detection) */
119 /* or for checking vertex normal flips */
120 #define FLT_EPSILON10 1.19209290e-06F
121
122 /* ------------------------------------------------------------------------- */
123
124 /* Stuff for stars. This sits here because it uses gl-things. Part of
125 this code may move down to the converter.  */
126 /* ------------------------------------------------------------------------- */
127 /* this is a bad beast, since it is misused by the 3d view drawing as well. */
128
129 static HaloRen *initstar(Render *re, ObjectRen *obr, float *vec, float hasize)
130 {
131         HaloRen *har;
132         float hoco[4];
133         
134         projectverto(vec, re->winmat, hoco);
135         
136         har= RE_findOrAddHalo(obr, obr->tothalo++);
137         
138         /* projectvert is done in function zbufvlaggen again, because of parts */
139         VECCOPY(har->co, vec);
140         har->hasize= hasize;
141         
142         har->zd= 0.0;
143         
144         return har;
145 }
146
147 /* there must be a 'fixed' amount of stars generated between
148 *         near and far
149 * all stars must by preference lie on the far and solely
150 *        differ in clarity/color
151 */
152
153 void RE_make_stars(Render *re, Scene *scenev3d, void (*initfunc)(void),
154                                    void (*vertexfunc)(float*),  void (*termfunc)(void))
155 {
156         extern unsigned char hash[512];
157         ObjectRen *obr= NULL;
158         World *wrld= NULL;
159         HaloRen *har;
160         Scene *scene;
161         Camera *camera;
162         double dblrand, hlfrand;
163         float vec[4], fx, fy, fz;
164         float fac, starmindist, clipend;
165         float mat[4][4], stargrid, maxrand, maxjit, force, alpha;
166         int x, y, z, sx, sy, sz, ex, ey, ez, done = 0;
167         
168         if(initfunc) {
169                 scene= scenev3d;
170                 wrld= scene->world;
171         }
172         else {
173                 scene= re->scene;
174                 wrld= &(re->wrld);
175         }
176         
177         stargrid = wrld->stardist;                      /* distance between stars */
178         maxrand = 2.0;                                          /* amount a star can be shifted (in grid units) */
179         maxjit = (wrld->starcolnoise);          /* amount a color is being shifted */
180         
181         /* size of stars */
182         force = ( wrld->starsize );
183         
184         /* minimal free space (starting at camera) */
185         starmindist= wrld->starmindist;
186         
187         if (stargrid <= 0.10) return;
188         
189         if (re) re->flag |= R_HALO;
190         else stargrid *= 1.0;                           /* then it draws fewer */
191         
192         if(re) MTC_Mat4Invert(mat, re->viewmat);
193         else MTC_Mat4One(mat);
194         
195         /* BOUNDING BOX CALCULATION
196                 * bbox goes from z = loc_near_var | loc_far_var,
197                 * x = -z | +z,
198                 * y = -z | +z
199                 */
200         
201         if(scene->camera==NULL)
202                 return;
203         camera = scene->camera->data;
204         clipend = camera->clipend;
205         
206         /* convert to grid coordinates */
207         
208         sx = ((mat[3][0] - clipend) / stargrid) - maxrand;
209         sy = ((mat[3][1] - clipend) / stargrid) - maxrand;
210         sz = ((mat[3][2] - clipend) / stargrid) - maxrand;
211         
212         ex = ((mat[3][0] + clipend) / stargrid) + maxrand;
213         ey = ((mat[3][1] + clipend) / stargrid) + maxrand;
214         ez = ((mat[3][2] + clipend) / stargrid) + maxrand;
215         
216         dblrand = maxrand * stargrid;
217         hlfrand = 2.0 * dblrand;
218         
219         if (initfunc) {
220                 initfunc();     
221         }
222
223         if(re) /* add render object for stars */
224                 obr= RE_addRenderObject(re, NULL, NULL, 0, 0, 0);
225         
226         for (x = sx, fx = sx * stargrid; x <= ex; x++, fx += stargrid) {
227                 for (y = sy, fy = sy * stargrid; y <= ey ; y++, fy += stargrid) {
228                         for (z = sz, fz = sz * stargrid; z <= ez; z++, fz += stargrid) {
229
230                                 BLI_srand((hash[z & 0xff] << 24) + (hash[y & 0xff] << 16) + (hash[x & 0xff] << 8));
231                                 vec[0] = fx + (hlfrand * BLI_drand()) - dblrand;
232                                 vec[1] = fy + (hlfrand * BLI_drand()) - dblrand;
233                                 vec[2] = fz + (hlfrand * BLI_drand()) - dblrand;
234                                 vec[3] = 1.0;
235                                 
236                                 if (vertexfunc) {
237                                         if(done & 1) vertexfunc(vec);
238                                         done++;
239                                 }
240                                 else {
241                                         MTC_Mat4MulVecfl(re->viewmat, vec);
242                                         
243                                         /* in vec are global coordinates
244                                         * calculate distance to camera
245                                         * and using that, define the alpha
246                                         */
247                                         
248                                         {
249                                                 float tx, ty, tz;
250                                                 
251                                                 tx = vec[0];
252                                                 ty = vec[1];
253                                                 tz = vec[2];
254                                                 
255                                                 alpha = sqrt(tx * tx + ty * ty + tz * tz);
256                                                 
257                                                 if (alpha >= clipend) alpha = 0.0;
258                                                 else if (alpha <= starmindist) alpha = 0.0;
259                                                 else if (alpha <= 2.0 * starmindist) {
260                                                         alpha = (alpha - starmindist) / starmindist;
261                                                 } else {
262                                                         alpha -= 2.0 * starmindist;
263                                                         alpha /= (clipend - 2.0 * starmindist);
264                                                         alpha = 1.0 - alpha;
265                                                 }
266                                         }
267                                         
268                                         
269                                         if (alpha != 0.0) {
270                                                 fac = force * BLI_drand();
271                                                 
272                                                 har = initstar(re, obr, vec, fac);
273                                                 
274                                                 if (har) {
275                                                         har->alfa = sqrt(sqrt(alpha));
276                                                         har->add= 255;
277                                                         har->r = har->g = har->b = 1.0;
278                                                         if (maxjit) {
279                                                                 har->r += ((maxjit * BLI_drand()) ) - maxjit;
280                                                                 har->g += ((maxjit * BLI_drand()) ) - maxjit;
281                                                                 har->b += ((maxjit * BLI_drand()) ) - maxjit;
282                                                         }
283                                                         har->hard = 32;
284                                                         har->lay= -1;
285                                                         har->type |= HA_ONLYSKY;
286                                                         done++;
287                                                 }
288                                         }
289                                 }
290                         }
291                         /* do not call blender_test_break() here, since it is used in UI as well, confusing the callback system */
292                         /* main cause is G.afbreek of course, a global again... (ton) */
293                 }
294         }
295         if (termfunc) termfunc();
296
297         if(obr)
298                 re->tothalo += obr->tothalo;
299 }
300
301
302 /* ------------------------------------------------------------------------- */
303 /* tool functions/defines for ad hoc simplification and possible future 
304    cleanup      */
305 /* ------------------------------------------------------------------------- */
306
307 #define UVTOINDEX(u,v) (startvlak + (u) * sizev + (v))
308 /*
309
310 NOTE THAT U/V COORDINATES ARE SOMETIMES SWAPPED !!
311         
312 ^       ()----p4----p3----()
313 |       |     |     |     |
314 u       |     |  F1 |  F2 |
315         |     |     |     |
316         ()----p1----p2----()
317                v ->
318 */
319
320 /* ------------------------------------------------------------------------- */
321
322 static void split_v_renderfaces(ObjectRen *obr, int startvlak, int startvert, int usize, int vsize, int uIndex, int cyclu, int cyclv)
323 {
324         int vLen = vsize-1+(!!cyclv);
325         int v;
326
327         for (v=0; v<vLen; v++) {
328                 VlakRen *vlr = RE_findOrAddVlak(obr, startvlak + vLen*uIndex + v);
329                 VertRen *vert = RE_vertren_copy(obr, vlr->v2);
330
331                 if (cyclv) {
332                         vlr->v2 = vert;
333
334                         if (v==vLen-1) {
335                                 VlakRen *vlr = RE_findOrAddVlak(obr, startvlak + vLen*uIndex + 0);
336                                 vlr->v1 = vert;
337                         } else {
338                                 VlakRen *vlr = RE_findOrAddVlak(obr, startvlak + vLen*uIndex + v+1);
339                                 vlr->v1 = vert;
340                         }
341                 } else {
342                         vlr->v2 = vert;
343
344                         if (v<vLen-1) {
345                                 VlakRen *vlr = RE_findOrAddVlak(obr, startvlak + vLen*uIndex + v+1);
346                                 vlr->v1 = vert;
347                         }
348
349                         if (v==0) {
350                                 vlr->v1 = RE_vertren_copy(obr, vlr->v1);
351                         } 
352                 }
353         }
354 }
355
356 /* ------------------------------------------------------------------------- */
357
358 static int check_vnormal(float *n, float *veno)
359 {
360         float inp;
361
362         inp=n[0]*veno[0]+n[1]*veno[1]+n[2]*veno[2];
363         if(inp < -FLT_EPSILON10) return 1;
364         return 0;
365 }
366
367 /* ------------------------------------------------------------------------- */
368 /* Stress, tangents and normals                                              */
369 /* ------------------------------------------------------------------------- */
370
371 static void calc_edge_stress_add(float *accum, VertRen *v1, VertRen *v2)
372 {
373         float len= VecLenf(v1->co, v2->co)/VecLenf(v1->orco, v2->orco);
374         float *acc;
375         
376         acc= accum + 2*v1->index;
377         acc[0]+= len;
378         acc[1]+= 1.0f;
379         
380         acc= accum + 2*v2->index;
381         acc[0]+= len;
382         acc[1]+= 1.0f;
383 }
384
385 static void calc_edge_stress(Render *re, ObjectRen *obr, Mesh *me)
386 {
387         float loc[3], size[3], *accum, *acc, *accumoffs, *stress;
388         int a;
389         
390         if(obr->totvert==0) return;
391         
392         mesh_get_texspace(me, loc, NULL, size);
393         
394         accum= MEM_callocN(2*sizeof(float)*obr->totvert, "temp accum for stress");
395         
396         /* de-normalize orco */
397         for(a=0; a<obr->totvert; a++) {
398                 VertRen *ver= RE_findOrAddVert(obr, a);
399                 if(ver->orco) {
400                         ver->orco[0]= ver->orco[0]*size[0] +loc[0];
401                         ver->orco[1]= ver->orco[1]*size[1] +loc[1];
402                         ver->orco[2]= ver->orco[2]*size[2] +loc[2];
403                 }
404         }
405         
406         /* add stress values */
407         accumoffs= accum;       /* so we can use vertex index */
408         for(a=0; a<obr->totvlak; a++) {
409                 VlakRen *vlr= RE_findOrAddVlak(obr, a);
410
411                 if(vlr->v1->orco && vlr->v4) {
412                         calc_edge_stress_add(accumoffs, vlr->v1, vlr->v2);
413                         calc_edge_stress_add(accumoffs, vlr->v2, vlr->v3);
414                         calc_edge_stress_add(accumoffs, vlr->v3, vlr->v1);
415                         if(vlr->v4) {
416                                 calc_edge_stress_add(accumoffs, vlr->v3, vlr->v4);
417                                 calc_edge_stress_add(accumoffs, vlr->v4, vlr->v1);
418                                 calc_edge_stress_add(accumoffs, vlr->v2, vlr->v4);
419                         }
420                 }
421         }
422         
423         for(a=0; a<obr->totvert; a++) {
424                 VertRen *ver= RE_findOrAddVert(obr, a);
425                 if(ver->orco) {
426                         /* find stress value */
427                         acc= accumoffs + 2*ver->index;
428                         if(acc[1]!=0.0f)
429                                 acc[0]/= acc[1];
430                         stress= RE_vertren_get_stress(obr, ver, 1);
431                         *stress= *acc;
432                         
433                         /* restore orcos */
434                         ver->orco[0] = (ver->orco[0]-loc[0])/size[0];
435                         ver->orco[1] = (ver->orco[1]-loc[1])/size[1];
436                         ver->orco[2] = (ver->orco[2]-loc[2])/size[2];
437                 }
438         }
439         
440         MEM_freeN(accum);
441 }
442
443 /* gets tangent from tface or orco */
444 static void calc_tangent_vector(ObjectRen *obr, VertexTangent **vtangents, MemArena *arena, VlakRen *vlr, int do_nmap_tangent, int do_tangent)
445 {
446         MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
447         VertRen *v1=vlr->v1, *v2=vlr->v2, *v3=vlr->v3, *v4=vlr->v4;
448         float tang[3], *tav;
449         float *uv1, *uv2, *uv3, *uv4;
450         float uv[4][2];
451         
452         if(tface) {
453                 uv1= tface->uv[0];
454                 uv2= tface->uv[1];
455                 uv3= tface->uv[2];
456                 uv4= tface->uv[3];
457         }
458         else if(v1->orco) {
459                 uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
460                 spheremap(v1->orco[0], v1->orco[1], v1->orco[2], &uv[0][0], &uv[0][1]);
461                 spheremap(v2->orco[0], v2->orco[1], v2->orco[2], &uv[1][0], &uv[1][1]);
462                 spheremap(v3->orco[0], v3->orco[1], v3->orco[2], &uv[2][0], &uv[2][1]);
463                 if(v4)
464                         spheremap(v4->orco[0], v4->orco[1], v4->orco[2], &uv[3][0], &uv[3][1]);
465         }
466         else return;
467
468         tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, vlr->n, tang);
469         
470         if(do_tangent) {
471                 tav= RE_vertren_get_tangent(obr, v1, 1);
472                 VECADD(tav, tav, tang);
473                 tav= RE_vertren_get_tangent(obr, v2, 1);
474                 VECADD(tav, tav, tang);
475                 tav= RE_vertren_get_tangent(obr, v3, 1);
476                 VECADD(tav, tav, tang);
477         }
478         
479         if(do_nmap_tangent) {
480                 sum_or_add_vertex_tangent(arena, &vtangents[v1->index], tang, uv1);
481                 sum_or_add_vertex_tangent(arena, &vtangents[v2->index], tang, uv2);
482                 sum_or_add_vertex_tangent(arena, &vtangents[v3->index], tang, uv3);
483         }
484
485         if(v4) {
486                 tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, vlr->n, tang);
487                 
488                 if(do_tangent) {
489                         tav= RE_vertren_get_tangent(obr, v1, 1);
490                         VECADD(tav, tav, tang);
491                         tav= RE_vertren_get_tangent(obr, v3, 1);
492                         VECADD(tav, tav, tang);
493                         tav= RE_vertren_get_tangent(obr, v4, 1);
494                         VECADD(tav, tav, tang);
495                 }
496
497                 if(do_nmap_tangent) {
498                         sum_or_add_vertex_tangent(arena, &vtangents[v1->index], tang, uv1);
499                         sum_or_add_vertex_tangent(arena, &vtangents[v3->index], tang, uv3);
500                         sum_or_add_vertex_tangent(arena, &vtangents[v4->index], tang, uv4);
501                 }
502         }
503 }
504
505
506 static void calc_vertexnormals(Render *re, ObjectRen *obr, int do_tangent, int do_nmap_tangent)
507 {
508         MemArena *arena= NULL;
509         VertexTangent **vtangents= NULL;
510         int a;
511
512         if(do_nmap_tangent) {
513                 arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
514                 BLI_memarena_use_calloc(arena);
515
516                 vtangents= MEM_callocN(sizeof(VertexTangent*)*obr->totvert, "VertexTangent");
517         }
518
519                 /* clear all vertex normals */
520         for(a=0; a<obr->totvert; a++) {
521                 VertRen *ver= RE_findOrAddVert(obr, a);
522                 ver->n[0]=ver->n[1]=ver->n[2]= 0.0f;
523         }
524
525                 /* calculate cos of angles and point-masses, use as weight factor to
526                    add face normal to vertex */
527         for(a=0; a<obr->totvlak; a++) {
528                 VlakRen *vlr= RE_findOrAddVlak(obr, a);
529                 if(vlr->flag & ME_SMOOTH) {
530                         VertRen *v1= vlr->v1;
531                         VertRen *v2= vlr->v2;
532                         VertRen *v3= vlr->v3;
533                         VertRen *v4= vlr->v4;
534                         float n1[3], n2[3], n3[3], n4[3];
535                         float fac1, fac2, fac3, fac4=0.0f;
536                         
537                         if(re->flag & R_GLOB_NOPUNOFLIP)
538                                 vlr->flag |= R_NOPUNOFLIP;
539                         
540                         VecSubf(n1, v2->co, v1->co);
541                         Normalize(n1);
542                         VecSubf(n2, v3->co, v2->co);
543                         Normalize(n2);
544                         if(v4==NULL) {
545                                 VecSubf(n3, v1->co, v3->co);
546                                 Normalize(n3);
547
548                                 fac1= saacos(-n1[0]*n3[0]-n1[1]*n3[1]-n1[2]*n3[2]);
549                                 fac2= saacos(-n1[0]*n2[0]-n1[1]*n2[1]-n1[2]*n2[2]);
550                                 fac3= saacos(-n2[0]*n3[0]-n2[1]*n3[1]-n2[2]*n3[2]);
551                         }
552                         else {
553                                 VecSubf(n3, v4->co, v3->co);
554                                 Normalize(n3);
555                                 VecSubf(n4, v1->co, v4->co);
556                                 Normalize(n4);
557
558                                 fac1= saacos(-n4[0]*n1[0]-n4[1]*n1[1]-n4[2]*n1[2]);
559                                 fac2= saacos(-n1[0]*n2[0]-n1[1]*n2[1]-n1[2]*n2[2]);
560                                 fac3= saacos(-n2[0]*n3[0]-n2[1]*n3[1]-n2[2]*n3[2]);
561                                 fac4= saacos(-n3[0]*n4[0]-n3[1]*n4[1]-n3[2]*n4[2]);
562
563                                 if(!(vlr->flag & R_NOPUNOFLIP)) {
564                                         if( check_vnormal(vlr->n, v4->n) ) fac4= -fac4;
565                                 }
566
567                                 v4->n[0] +=fac4*vlr->n[0];
568                                 v4->n[1] +=fac4*vlr->n[1];
569                                 v4->n[2] +=fac4*vlr->n[2];
570                         }
571
572                         if(!(vlr->flag & R_NOPUNOFLIP)) {
573                                 if( check_vnormal(vlr->n, v1->n) ) fac1= -fac1;
574                                 if( check_vnormal(vlr->n, v2->n) ) fac2= -fac2;
575                                 if( check_vnormal(vlr->n, v3->n) ) fac3= -fac3;
576                         }
577
578                         v1->n[0] +=fac1*vlr->n[0];
579                         v1->n[1] +=fac1*vlr->n[1];
580                         v1->n[2] +=fac1*vlr->n[2];
581
582                         v2->n[0] +=fac2*vlr->n[0];
583                         v2->n[1] +=fac2*vlr->n[1];
584                         v2->n[2] +=fac2*vlr->n[2];
585
586                         v3->n[0] +=fac3*vlr->n[0];
587                         v3->n[1] +=fac3*vlr->n[1];
588                         v3->n[2] +=fac3*vlr->n[2];
589                         
590                 }
591                 if(do_nmap_tangent || do_tangent) {
592                         /* tangents still need to be calculated for flat faces too */
593                         /* weighting removed, they are not vertexnormals */
594                         calc_tangent_vector(obr, vtangents, arena, vlr, do_nmap_tangent, do_tangent);
595                 }
596         }
597
598                 /* do solid faces */
599         for(a=0; a<obr->totvlak; a++) {
600                 VlakRen *vlr= RE_findOrAddVlak(obr, a);
601                 if((vlr->flag & ME_SMOOTH)==0) {
602                         float *f1= vlr->v1->n;
603                         if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
604                         f1= vlr->v2->n;
605                         if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
606                         f1= vlr->v3->n;
607                         if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
608                         if(vlr->v4) {
609                                 f1= vlr->v4->n;
610                                 if(f1[0]==0.0 && f1[1]==0.0 && f1[2]==0.0) VECCOPY(f1, vlr->n);
611                         }
612                 }
613
614                 if(do_nmap_tangent) {
615                         VertRen *v1=vlr->v1, *v2=vlr->v2, *v3=vlr->v3, *v4=vlr->v4;
616                         MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->actmtface, NULL, 0);
617
618                         if(tface) {
619                                 float *vtang, *ftang= RE_vlakren_get_nmap_tangent(obr, vlr, 1);
620
621                                 vtang= find_vertex_tangent(vtangents[v1->index], tface->uv[0]);
622                                 VECCOPY(ftang, vtang);
623                                 Normalize(ftang);
624                                 vtang= find_vertex_tangent(vtangents[v2->index], tface->uv[1]);
625                                 VECCOPY(ftang+3, vtang);
626                                 Normalize(ftang+3);
627                                 vtang= find_vertex_tangent(vtangents[v3->index], tface->uv[2]);
628                                 VECCOPY(ftang+6, vtang);
629                                 Normalize(ftang+6);
630                                 if(v4) {
631                                         vtang= find_vertex_tangent(vtangents[v4->index], tface->uv[3]);
632                                         VECCOPY(ftang+9, vtang);
633                                         Normalize(ftang+9);
634                                 }
635                         }
636                 }
637         }
638         
639                 /* normalize vertex normals */
640         for(a=0; a<obr->totvert; a++) {
641                 VertRen *ver= RE_findOrAddVert(obr, a);
642                 Normalize(ver->n);
643                 if(do_tangent) {
644                         float *tav= RE_vertren_get_tangent(obr, ver, 0);
645                         if (tav) {
646                                 /* orthonorm. */
647                                 float tdn = tav[0]*ver->n[0] + tav[1]*ver->n[1] + tav[2]*ver->n[2];
648                                 tav[0] -= ver->n[0]*tdn;
649                                 tav[1] -= ver->n[1]*tdn;
650                                 tav[2] -= ver->n[2]*tdn;
651                                 Normalize(tav);
652                         }
653                 }
654         }
655
656
657         if(arena)
658                 BLI_memarena_free(arena);
659         if(vtangents)
660                 MEM_freeN(vtangents);
661 }
662
663 /* ------------------------------------------------------------------------- */
664 /* Autosmoothing:                                                            */
665 /* ------------------------------------------------------------------------- */
666
667 typedef struct ASvert {
668         int totface;
669         ListBase faces;
670 } ASvert;
671
672 typedef struct ASface {
673         struct ASface *next, *prev;
674         VlakRen *vlr[4];
675         VertRen *nver[4];
676 } ASface;
677
678 static void as_addvert(ASvert *asv, VertRen *v1, VlakRen *vlr)
679 {
680         ASface *asf;
681         int a;
682         
683         if(v1 == NULL) return;
684         
685         if(asv->faces.first==NULL) {
686                 asf= MEM_callocN(sizeof(ASface), "asface");
687                 BLI_addtail(&asv->faces, asf);
688         }
689         
690         asf= asv->faces.last;
691         for(a=0; a<4; a++) {
692                 if(asf->vlr[a]==NULL) {
693                         asf->vlr[a]= vlr;
694                         asv->totface++;
695                         break;
696                 }
697         }
698         
699         /* new face struct */
700         if(a==4) {
701                 asf= MEM_callocN(sizeof(ASface), "asface");
702                 BLI_addtail(&asv->faces, asf);
703                 asf->vlr[0]= vlr;
704                 asv->totface++;
705         }
706 }
707
708 static int as_testvertex(VlakRen *vlr, VertRen *ver, ASvert *asv, float thresh) 
709 {
710         /* return 1: vertex needs a copy */
711         ASface *asf;
712         float inp;
713         int a;
714         
715         if(vlr==0) return 0;
716         
717         asf= asv->faces.first;
718         while(asf) {
719                 for(a=0; a<4; a++) {
720                         if(asf->vlr[a] && asf->vlr[a]!=vlr) {
721                                 inp= fabs( vlr->n[0]*asf->vlr[a]->n[0] + vlr->n[1]*asf->vlr[a]->n[1] + vlr->n[2]*asf->vlr[a]->n[2] );
722                                 if(inp < thresh) return 1;
723                         }
724                 }
725                 asf= asf->next;
726         }
727         
728         return 0;
729 }
730
731 static VertRen *as_findvertex(VlakRen *vlr, VertRen *ver, ASvert *asv, float thresh) 
732 {
733         /* return when new vertex already was made */
734         ASface *asf;
735         float inp;
736         int a;
737         
738         asf= asv->faces.first;
739         while(asf) {
740                 for(a=0; a<4; a++) {
741                         if(asf->vlr[a] && asf->vlr[a]!=vlr) {
742                                 /* this face already made a copy for this vertex! */
743                                 if(asf->nver[a]) {
744                                         inp= fabs( vlr->n[0]*asf->vlr[a]->n[0] + vlr->n[1]*asf->vlr[a]->n[1] + vlr->n[2]*asf->vlr[a]->n[2] );
745                                         if(inp >= thresh) {
746                                                 return asf->nver[a];
747                                         }
748                                 }
749                         }
750                 }
751                 asf= asf->next;
752         }
753         
754         return NULL;
755 }
756
757 /* note; autosmooth happens in object space still, after applying autosmooth we rotate */
758 /* note2; actually, when original mesh and displist are equal sized, face normals are from original mesh */
759 static void autosmooth(Render *re, ObjectRen *obr, float mat[][4], int degr)
760 {
761         ASvert *asv, *asverts;
762         ASface *asf;
763         VertRen *ver, *v1;
764         VlakRen *vlr;
765         float thresh;
766         int a, b, totvert;
767         
768         if(obr->totvert==0) return;
769         asverts= MEM_callocN(sizeof(ASvert)*obr->totvert, "all smooth verts");
770         
771         thresh= cos( M_PI*(0.5f+(float)degr)/180.0 );
772         
773         /* step zero: give faces normals of original mesh, if this is provided */
774         
775         
776         /* step one: construct listbase of all vertices and pointers to faces */
777         for(a=0; a<obr->totvlak; a++) {
778                 vlr= RE_findOrAddVlak(obr, a);
779                 /* skip wire faces */
780                 if(vlr->v2 != vlr->v3) {
781                         as_addvert(asverts+vlr->v1->index, vlr->v1, vlr);
782                         as_addvert(asverts+vlr->v2->index, vlr->v2, vlr);
783                         as_addvert(asverts+vlr->v3->index, vlr->v3, vlr);
784                         if(vlr->v4) 
785                                 as_addvert(asverts+vlr->v4->index, vlr->v4, vlr);
786                 }
787         }
788         
789         totvert= obr->totvert;
790         /* we now test all vertices, when faces have a normal too much different: they get a new vertex */
791         for(a=0, asv=asverts; a<totvert; a++, asv++) {
792                 if(asv && asv->totface>1) {
793                         ver= RE_findOrAddVert(obr, a);
794
795                         asf= asv->faces.first;
796                         while(asf) {
797                                 for(b=0; b<4; b++) {
798                                 
799                                         /* is there a reason to make a new vertex? */
800                                         vlr= asf->vlr[b];
801                                         if( as_testvertex(vlr, ver, asv, thresh) ) {
802                                                 
803                                                 /* already made a new vertex within threshold? */
804                                                 v1= as_findvertex(vlr, ver, asv, thresh);
805                                                 if(v1==NULL) {
806                                                         /* make a new vertex */
807                                                         v1= RE_vertren_copy(obr, ver);
808                                                 }
809                                                 asf->nver[b]= v1;
810                                                 if(vlr->v1==ver) vlr->v1= v1;
811                                                 if(vlr->v2==ver) vlr->v2= v1;
812                                                 if(vlr->v3==ver) vlr->v3= v1;
813                                                 if(vlr->v4==ver) vlr->v4= v1;
814                                         }
815                                 }
816                                 asf= asf->next;
817                         }
818                 }
819         }
820         
821         /* free */
822         for(a=0; a<totvert; a++) {
823                 BLI_freelistN(&asverts[a].faces);
824         }
825         MEM_freeN(asverts);
826         
827         /* rotate vertices and calculate normal of faces */
828         for(a=0; a<obr->totvert; a++) {
829                 ver= RE_findOrAddVert(obr, a);
830                 MTC_Mat4MulVecfl(mat, ver->co);
831         }
832         for(a=0; a<obr->totvlak; a++) {
833                 vlr= RE_findOrAddVlak(obr, a);
834                 
835                 /* skip wire faces */
836                 if(vlr->v2 != vlr->v3) {
837                         if(vlr->v4) 
838                                 CalcNormFloat4(vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
839                         else 
840                                 CalcNormFloat(vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
841                 }
842         }               
843 }
844
845 /* ------------------------------------------------------------------------- */
846 /* Orco hash and Materials                                                   */
847 /* ------------------------------------------------------------------------- */
848
849 static float *get_object_orco(Render *re, Object *ob)
850 {
851         float *orco;
852         
853         if (!re->orco_hash)
854                 re->orco_hash = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
855         
856         orco = BLI_ghash_lookup(re->orco_hash, ob);
857         
858         if (!orco) {
859                 if (ELEM(ob->type, OB_CURVE, OB_FONT)) {
860                         orco = make_orco_curve(re->scene, ob);
861                 } else if (ob->type==OB_SURF) {
862                         orco = make_orco_surf(ob);
863                 } else if (ob->type==OB_MBALL) {
864                         orco = make_orco_mball(ob);
865                 }
866                 
867                 if (orco)
868                         BLI_ghash_insert(re->orco_hash, ob, orco);
869         }
870         
871         return orco;
872 }
873
874 static void set_object_orco(Render *re, void *ob, float *orco)
875 {
876         if (!re->orco_hash)
877                 re->orco_hash = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
878         
879         BLI_ghash_insert(re->orco_hash, ob, orco);
880 }
881
882 static void free_mesh_orco_hash(Render *re) 
883 {
884         if (re->orco_hash) {
885                 BLI_ghash_free(re->orco_hash, NULL, (GHashValFreeFP)MEM_freeN);
886                 re->orco_hash = NULL;
887         }
888 }
889
890 static void flag_render_node_material(Render *re, bNodeTree *ntree)
891 {
892         bNode *node;
893
894         for(node=ntree->nodes.first; node; node= node->next) {
895                 if(node->id) {
896                         if(GS(node->id->name)==ID_MA) {
897                                 Material *ma= (Material *)node->id;
898
899                                 if(ma->mode & MA_ZTRA)
900                                         re->flag |= R_ZTRA;
901
902                                 ma->flag |= MA_IS_USED;
903                         }
904                         else if(node->type==NODE_GROUP)
905                                 flag_render_node_material(re, (bNodeTree *)node->id);
906                 }
907         }
908 }
909
910 static Material *give_render_material(Render *re, Object *ob, int nr)
911 {
912         extern Material defmaterial;    /* material.c */
913         Material *ma;
914         
915         ma= give_current_material(ob, nr);
916         if(ma==NULL) 
917                 ma= &defmaterial;
918         
919         if(re->r.mode & R_SPEED) ma->texco |= NEED_UV;
920         
921         if(ma->mode & MA_ZTRA)
922                 re->flag |= R_ZTRA;
923         
924         /* for light groups */
925         ma->flag |= MA_IS_USED;
926
927         if(ma->nodetree && ma->use_nodes)
928                 flag_render_node_material(re, ma->nodetree);
929         
930         return ma;
931 }
932
933 /* ------------------------------------------------------------------------- */
934 /* Particles                                                                 */
935 /* ------------------------------------------------------------------------- */
936 typedef struct ParticleStrandData
937 {
938         struct MCol *mcol;
939         float *orco, *uvco, *surfnor;
940         float time, adapt_angle, adapt_pix, size;
941         int totuv, totcol;
942         int first, line, adapt, override_uv;
943 }
944 ParticleStrandData;
945 /* future thread problem... */
946 static void static_particle_strand(Render *re, ObjectRen *obr, Material *ma, ParticleStrandData *sd, float *vec, float *vec1)
947 {
948         static VertRen *v1= NULL, *v2= NULL;
949         VlakRen *vlr= NULL;
950         float nor[3], cross[3], crosslen, w, dx, dy, width;
951         static float anor[3], avec[3];
952         int flag, i;
953         static int second=0;
954         
955         VecSubf(nor, vec, vec1);
956         Normalize(nor);         // nor needed as tangent 
957         Crossf(cross, vec, nor);
958
959         /* turn cross in pixelsize */
960         w= vec[2]*re->winmat[2][3] + re->winmat[3][3];
961         dx= re->winx*cross[0]*re->winmat[0][0];
962         dy= re->winy*cross[1]*re->winmat[1][1];
963         w= sqrt(dx*dx + dy*dy)/w;
964         
965         if(w!=0.0f) {
966                 float fac;
967                 if(ma->strand_ease!=0.0f) {
968                         if(ma->strand_ease<0.0f)
969                                 fac= pow(sd->time, 1.0+ma->strand_ease);
970                         else
971                                 fac= pow(sd->time, 1.0/(1.0f-ma->strand_ease));
972                 }
973                 else fac= sd->time;
974
975                 width= ((1.0f-fac)*ma->strand_sta + (fac)*ma->strand_end);
976
977                 /* use actual Blender units for strand width and fall back to minimum width */
978                 if(ma->mode & MA_STR_B_UNITS){
979             crosslen= VecLength(cross);
980             w= 2.0f*crosslen*ma->strand_min/w;
981
982                         if(width < w)
983                                 width= w;
984
985                         /*cross is the radius of the strand so we want it to be half of full width */
986                         VecMulf(cross,0.5/crosslen);
987                 }
988                 else
989                         width/=w;
990
991                 VecMulf(cross, width);
992         }
993         else width= 1.0f;
994         
995         if(ma->mode & MA_TANGENT_STR)
996                 flag= R_SMOOTH|R_NOPUNOFLIP|R_TANGENT;
997         else
998                 flag= R_SMOOTH;
999         
1000         /* only 1 pixel wide strands filled in as quads now, otherwise zbuf errors */
1001         if(ma->strand_sta==1.0f)
1002                 flag |= R_STRAND;
1003         
1004         /* single face line */
1005         if(sd->line) {
1006                 vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1007                 vlr->flag= flag;
1008                 vlr->v1= RE_findOrAddVert(obr, obr->totvert++);
1009                 vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
1010                 vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
1011                 vlr->v4= RE_findOrAddVert(obr, obr->totvert++);
1012                 
1013                 VECCOPY(vlr->v1->co, vec);
1014                 VecAddf(vlr->v1->co, vlr->v1->co, cross);
1015                 VECCOPY(vlr->v1->n, nor);
1016                 vlr->v1->orco= sd->orco;
1017                 vlr->v1->accum= -1.0f;  // accum abuse for strand texco
1018                 
1019                 VECCOPY(vlr->v2->co, vec);
1020                 VecSubf(vlr->v2->co, vlr->v2->co, cross);
1021                 VECCOPY(vlr->v2->n, nor);
1022                 vlr->v2->orco= sd->orco;
1023                 vlr->v2->accum= vlr->v1->accum;
1024
1025                 VECCOPY(vlr->v4->co, vec1);
1026                 VecAddf(vlr->v4->co, vlr->v4->co, cross);
1027                 VECCOPY(vlr->v4->n, nor);
1028                 vlr->v4->orco= sd->orco;
1029                 vlr->v4->accum= 1.0f;   // accum abuse for strand texco
1030                 
1031                 VECCOPY(vlr->v3->co, vec1);
1032                 VecSubf(vlr->v3->co, vlr->v3->co, cross);
1033                 VECCOPY(vlr->v3->n, nor);
1034                 vlr->v3->orco= sd->orco;
1035                 vlr->v3->accum= vlr->v4->accum;
1036
1037                 CalcNormFloat4(vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
1038                 
1039                 vlr->mat= ma;
1040                 vlr->ec= ME_V2V3;
1041
1042                 if(sd->surfnor) {
1043                         float *snor= RE_vlakren_get_surfnor(obr, vlr, 1);
1044                         VECCOPY(snor, sd->surfnor);
1045                 }
1046
1047                 if(sd->uvco){
1048                         for(i=0; i<sd->totuv; i++){
1049                                 MTFace *mtf;
1050                                 mtf=RE_vlakren_get_tface(obr,vlr,i,NULL,1);
1051                                 mtf->uv[0][0]=mtf->uv[1][0]=
1052                                 mtf->uv[2][0]=mtf->uv[3][0]=(sd->uvco+2*i)[0];
1053                                 mtf->uv[0][1]=mtf->uv[1][1]=
1054                                 mtf->uv[2][1]=mtf->uv[3][1]=(sd->uvco+2*i)[1];
1055                         }
1056                         if(sd->override_uv>=0){
1057                                 MTFace *mtf;
1058                                 mtf=RE_vlakren_get_tface(obr,vlr,sd->override_uv,NULL,0);
1059                                 
1060                                 mtf->uv[0][0]=mtf->uv[3][0]=0.0f;
1061                                 mtf->uv[1][0]=mtf->uv[2][0]=1.0f;
1062
1063                                 mtf->uv[0][1]=mtf->uv[1][1]=0.0f;
1064                                 mtf->uv[2][1]=mtf->uv[3][1]=1.0f;
1065                         }
1066                 }
1067                 if(sd->mcol){
1068                         for(i=0; i<sd->totcol; i++){
1069                                 MCol *mc;
1070                                 mc=RE_vlakren_get_mcol(obr,vlr,i,NULL,1);
1071                                 mc[0]=mc[1]=mc[2]=mc[3]=sd->mcol[i];
1072                                 mc[0]=mc[1]=mc[2]=mc[3]=sd->mcol[i];
1073                         }
1074                 }
1075         }
1076         /* first two vertices of a strand */
1077         else if(sd->first) {
1078                 if(sd->adapt){
1079                         VECCOPY(anor, nor);
1080                         VECCOPY(avec, vec);
1081                         second=1;
1082                 }
1083
1084                 v1= RE_findOrAddVert(obr, obr->totvert++);
1085                 v2= RE_findOrAddVert(obr, obr->totvert++);
1086                 
1087                 VECCOPY(v1->co, vec);
1088                 VecAddf(v1->co, v1->co, cross);
1089                 VECCOPY(v1->n, nor);
1090                 v1->orco= sd->orco;
1091                 v1->accum= -1.0f;       // accum abuse for strand texco
1092                 
1093                 VECCOPY(v2->co, vec);
1094                 VecSubf(v2->co, v2->co, cross);
1095                 VECCOPY(v2->n, nor);
1096                 v2->orco= sd->orco;
1097                 v2->accum= v1->accum;
1098         }
1099         /* more vertices & faces to strand */
1100         else {
1101                 if(sd->adapt==0 || second){
1102                         vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1103                         vlr->flag= flag;
1104                         vlr->v1= v1;
1105                         vlr->v2= v2;
1106                         vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
1107                         vlr->v4= RE_findOrAddVert(obr, obr->totvert++);
1108                         
1109                         v1= vlr->v4; // cycle
1110                         v2= vlr->v3; // cycle
1111
1112                         
1113                         if(sd->adapt){
1114                                 second=0;
1115                                 VECCOPY(anor,nor);
1116                                 VECCOPY(avec,vec);
1117                         }
1118
1119                 }
1120                 else if(sd->adapt){
1121                         float dvec[3],pvec[3];
1122                         VecSubf(dvec,avec,vec);
1123                         Projf(pvec,dvec,vec);
1124                         VecSubf(dvec,dvec,pvec);
1125
1126                         w= vec[2]*re->winmat[2][3] + re->winmat[3][3];
1127                         dx= re->winx*dvec[0]*re->winmat[0][0]/w;
1128                         dy= re->winy*dvec[1]*re->winmat[1][1]/w;
1129                         w= sqrt(dx*dx + dy*dy);
1130                         if(Inpf(anor,nor)<sd->adapt_angle && w>sd->adapt_pix){
1131                                 vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1132                                 vlr->flag= flag;
1133                                 vlr->v1= v1;
1134                                 vlr->v2= v2;
1135                                 vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
1136                                 vlr->v4= RE_findOrAddVert(obr, obr->totvert++);
1137                                 
1138                                 v1= vlr->v4; // cycle
1139                                 v2= vlr->v3; // cycle
1140
1141                                 VECCOPY(anor,nor);
1142                                 VECCOPY(avec,vec);
1143                         }
1144                         else{
1145                                 vlr= RE_findOrAddVlak(obr, obr->totvlak-1);
1146                         }
1147                 }
1148         
1149                 VECCOPY(vlr->v4->co, vec);
1150                 VecAddf(vlr->v4->co, vlr->v4->co, cross);
1151                 VECCOPY(vlr->v4->n, nor);
1152                 vlr->v4->orco= sd->orco;
1153                 vlr->v4->accum= -1.0f + 2.0f*sd->time;  // accum abuse for strand texco
1154                 
1155                 VECCOPY(vlr->v3->co, vec);
1156                 VecSubf(vlr->v3->co, vlr->v3->co, cross);
1157                 VECCOPY(vlr->v3->n, nor);
1158                 vlr->v3->orco= sd->orco;
1159                 vlr->v3->accum= vlr->v4->accum;
1160                 
1161                 CalcNormFloat4(vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
1162                 
1163                 vlr->mat= ma;
1164                 vlr->ec= ME_V2V3;
1165
1166                 if(sd->surfnor) {
1167                         float *snor= RE_vlakren_get_surfnor(obr, vlr, 1);
1168                         VECCOPY(snor, sd->surfnor);
1169                 }
1170
1171                 if(sd->uvco){
1172                         for(i=0; i<sd->totuv; i++){
1173                                 MTFace *mtf;
1174                                 mtf=RE_vlakren_get_tface(obr,vlr,i,NULL,1);
1175                                 mtf->uv[0][0]=mtf->uv[1][0]=
1176                                 mtf->uv[2][0]=mtf->uv[3][0]=(sd->uvco+2*i)[0];
1177                                 mtf->uv[0][1]=mtf->uv[1][1]=
1178                                 mtf->uv[2][1]=mtf->uv[3][1]=(sd->uvco+2*i)[1];
1179                         }
1180                         if(sd->override_uv>=0){
1181                                 MTFace *mtf;
1182                                 mtf=RE_vlakren_get_tface(obr,vlr,sd->override_uv,NULL,0);
1183                                 
1184                                 mtf->uv[0][0]=mtf->uv[3][0]=0.0f;
1185                                 mtf->uv[1][0]=mtf->uv[2][0]=1.0f;
1186
1187                                 mtf->uv[0][1]=mtf->uv[1][1]=(vlr->v1->accum+1.0f)/2.0f;
1188                                 mtf->uv[2][1]=mtf->uv[3][1]=(vlr->v3->accum+1.0f)/2.0f;
1189                         }
1190                 }
1191                 if(sd->mcol){
1192                         for(i=0; i<sd->totcol; i++){
1193                                 MCol *mc;
1194                                 mc=RE_vlakren_get_mcol(obr,vlr,i,NULL,1);
1195                                 mc[0]=mc[1]=mc[2]=mc[3]=sd->mcol[i];
1196                                 mc[0]=mc[1]=mc[2]=mc[3]=sd->mcol[i];
1197                         }
1198                 }
1199         }
1200 }
1201
1202 static void static_particle_wire(ObjectRen *obr, Material *ma, float *vec, float *vec1, int first, int line)
1203 {
1204         VlakRen *vlr;
1205         static VertRen *v1;
1206
1207         if(line) {
1208                 vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1209                 vlr->v1= RE_findOrAddVert(obr, obr->totvert++);
1210                 vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
1211                 vlr->v3= vlr->v2;
1212                 vlr->v4= NULL;
1213                 
1214                 VECCOPY(vlr->v1->co, vec);
1215                 VECCOPY(vlr->v2->co, vec1);
1216                 
1217                 VecSubf(vlr->n, vec, vec1);
1218                 Normalize(vlr->n);
1219                 VECCOPY(vlr->v1->n, vlr->n);
1220                 VECCOPY(vlr->v2->n, vlr->n);
1221                 
1222                 vlr->mat= ma;
1223                 vlr->ec= ME_V1V2;
1224
1225         }
1226         else if(first) {
1227                 v1= RE_findOrAddVert(obr, obr->totvert++);
1228                 VECCOPY(v1->co, vec);
1229         }
1230         else {
1231                 vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1232                 vlr->v1= v1;
1233                 vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
1234                 vlr->v3= vlr->v2;
1235                 vlr->v4= NULL;
1236                 
1237                 v1= vlr->v2; // cycle
1238                 VECCOPY(v1->co, vec);
1239                 
1240                 VecSubf(vlr->n, vec, vec1);
1241                 Normalize(vlr->n);
1242                 VECCOPY(v1->n, vlr->n);
1243                 
1244                 vlr->mat= ma;
1245                 vlr->ec= ME_V1V2;
1246         }
1247
1248 }
1249
1250 static void particle_billboard(Render *re, ObjectRen *obr, Material *ma, ParticleBillboardData *bb)
1251 {
1252         VlakRen *vlr;
1253         MTFace *mtf;
1254         float xvec[3], yvec[3], zvec[3], bb_center[3];
1255         float uvx = 0.0f, uvy = 0.0f, uvdx = 1.0f, uvdy = 1.0f, time = 0.0f;
1256
1257         vlr= RE_findOrAddVlak(obr, obr->totvlak++);
1258         vlr->v1= RE_findOrAddVert(obr, obr->totvert++);
1259         vlr->v2= RE_findOrAddVert(obr, obr->totvert++);
1260         vlr->v3= RE_findOrAddVert(obr, obr->totvert++);
1261         vlr->v4= RE_findOrAddVert(obr, obr->totvert++);
1262
1263         psys_make_billboard(bb, xvec, yvec, zvec, bb_center);
1264
1265         VECADD(vlr->v1->co, bb_center, xvec);
1266         VECADD(vlr->v1->co, vlr->v1->co, yvec);
1267         MTC_Mat4MulVecfl(re->viewmat, vlr->v1->co);
1268
1269         VECSUB(vlr->v2->co, bb_center, xvec);
1270         VECADD(vlr->v2->co, vlr->v2->co, yvec);
1271         MTC_Mat4MulVecfl(re->viewmat, vlr->v2->co);
1272
1273         VECSUB(vlr->v3->co, bb_center, xvec);
1274         VECSUB(vlr->v3->co, vlr->v3->co, yvec);
1275         MTC_Mat4MulVecfl(re->viewmat, vlr->v3->co);
1276
1277         VECADD(vlr->v4->co, bb_center, xvec);
1278         VECSUB(vlr->v4->co, vlr->v4->co, yvec);
1279         MTC_Mat4MulVecfl(re->viewmat, vlr->v4->co);
1280
1281         CalcNormFloat4(vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
1282         VECCOPY(vlr->v1->n,vlr->n);
1283         VECCOPY(vlr->v2->n,vlr->n);
1284         VECCOPY(vlr->v3->n,vlr->n);
1285         VECCOPY(vlr->v4->n,vlr->n);
1286         
1287         vlr->mat= ma;
1288         vlr->ec= ME_V2V3;
1289
1290         if(bb->uv_split > 1){
1291                 uvdx = uvdy = 1.0f / (float)bb->uv_split;
1292                 if(bb->anim == PART_BB_ANIM_TIME) {
1293                         if(bb->split_offset == PART_BB_OFF_NONE)
1294                                 time = bb->time;
1295                         else if(bb->split_offset == PART_BB_OFF_LINEAR)
1296                                 time = (float)fmod(bb->time + (float)bb->num / (float)(bb->uv_split * bb->uv_split), 1.0f);
1297                         else /* split_offset==PART_BB_OFF_RANDOM */
1298                                 time = (float)fmod(bb->time + bb->random, 1.0f);
1299
1300                 }
1301                 else if(bb->anim == PART_BB_ANIM_ANGLE) {
1302                         if(bb->align == PART_BB_VIEW) {
1303                                 time = (float)fmod((bb->tilt + 1.0f) / 2.0f, 1.0);
1304                         }
1305                         else{
1306                                 float axis1[3] = {0.0f,0.0f,0.0f};
1307                                 float axis2[3] = {0.0f,0.0f,0.0f};
1308                                 axis1[(bb->align + 1) % 3] = 1.0f;
1309                                 axis2[(bb->align + 2) % 3] = 1.0f;
1310                                 if(bb->lock == 0) {
1311                                         zvec[bb->align] = 0.0f;
1312                                         Normalize(zvec);
1313                                 }
1314                                 time = saacos(Inpf(zvec, axis1)) / (float)M_PI;
1315                                 if(Inpf(zvec, axis2) < 0.0f)
1316                                         time = 1.0f - time / 2.0f;
1317                                 else
1318                                         time = time / 2.0f;
1319                         }
1320                         if(bb->split_offset == PART_BB_OFF_LINEAR)
1321                                 time = (float)fmod(bb->time + (float)bb->num / (float)(bb->uv_split * bb->uv_split), 1.0f);
1322                         else if(bb->split_offset == PART_BB_OFF_RANDOM)
1323                                 time = (float)fmod(bb->time + bb->random, 1.0f);
1324                 }
1325                 else{
1326                         if(bb->split_offset == PART_BB_OFF_NONE)
1327                                 time = 0.0f;
1328                         else if(bb->split_offset == PART_BB_OFF_LINEAR)
1329                                 time = (float)fmod((float)bb->num /(float)(bb->uv_split * bb->uv_split) , 1.0f);
1330                         else /* split_offset==PART_BB_OFF_RANDOM */
1331                                 time = bb->random;
1332                 }
1333                 uvx = uvdx * floor((float)(bb->uv_split * bb->uv_split) * (float)fmod((double)time, (double)uvdx));
1334                 uvy = uvdy * floor((1.0f - time) * (float)bb->uv_split);
1335                 if(fmod(time, 1.0f / bb->uv_split) == 0.0f)
1336                         uvy -= uvdy;
1337         }
1338
1339         /* normal UVs */
1340         if(bb->uv[0] >= 0){
1341                 mtf = RE_vlakren_get_tface(obr, vlr, bb->uv[0], NULL, 1);
1342                 mtf->uv[0][0] = 1.0f;
1343                 mtf->uv[0][1] = 1.0f;
1344                 mtf->uv[1][0] = 0.0f;
1345                 mtf->uv[1][1] = 1.0f;
1346                 mtf->uv[2][0] = 0.0f;
1347                 mtf->uv[2][1] = 0.0f;
1348                 mtf->uv[3][0] = 1.0f;
1349                 mtf->uv[3][1] = 0.0f;
1350         }
1351
1352         /* time-index UVs */
1353         if(bb->uv[1] >= 0){
1354                 mtf = RE_vlakren_get_tface(obr, vlr, bb->uv[1], NULL, 1);
1355                 mtf->uv[0][0] = mtf->uv[1][0] = mtf->uv[2][0] = mtf->uv[3][0] = bb->time;
1356                 mtf->uv[0][1] = mtf->uv[1][1] = mtf->uv[2][1] = mtf->uv[3][1] = (float)bb->num/(float)bb->totnum;
1357         }
1358
1359         /* split UVs */
1360         if(bb->uv_split > 1 && bb->uv[2] >= 0){
1361                 mtf = RE_vlakren_get_tface(obr, vlr, bb->uv[2], NULL, 1);
1362                 mtf->uv[0][0] = uvx + uvdx;
1363                 mtf->uv[0][1] = uvy + uvdy;
1364                 mtf->uv[1][0] = uvx;
1365                 mtf->uv[1][1] = uvy + uvdy;
1366                 mtf->uv[2][0] = uvx;
1367                 mtf->uv[2][1] = uvy;
1368                 mtf->uv[3][0] = uvx + uvdx;
1369                 mtf->uv[3][1] = uvy;
1370         }
1371 }
1372 static void render_new_particle(Render *re, ObjectRen *obr, DerivedMesh *dm, Material *ma, ParticleStrandData *sd, float *loc, float *loc1,     int seed)
1373 {
1374         HaloRen *har=0;
1375
1376         if(ma->mode&MA_WIRE)
1377                 static_particle_wire(obr, ma, loc, loc1, sd->first, sd->line);
1378         else if(ma->material_type == MA_TYPE_HALO) {
1379                 har= RE_inithalo_particle(re, obr, dm, ma, loc, loc1, sd->orco, sd->uvco, sd->size, 1.0, seed);
1380                 if(har) har->lay= obr->ob->lay;
1381         }
1382         else
1383                 static_particle_strand(re, obr, ma, sd, loc, loc1);
1384 }
1385 static void get_particle_uvco_mcol(short from, DerivedMesh *dm, float *fuv, int num, ParticleStrandData *sd)
1386 {
1387         int i;
1388
1389         /* get uvco */
1390         if(sd->uvco && ELEM(from,PART_FROM_FACE,PART_FROM_VOLUME)) {
1391                 for(i=0; i<sd->totuv; i++) {
1392                         if(num != DMCACHE_NOTFOUND) {
1393                                 MFace *mface = dm->getFaceData(dm, num, CD_MFACE);
1394                                 MTFace *mtface = (MTFace*)CustomData_get_layer_n(&dm->faceData, CD_MTFACE, i);
1395                                 mtface += num;
1396                                 
1397                                 psys_interpolate_uvs(mtface, mface->v4, fuv, sd->uvco + 2 * i);
1398                         }
1399                         else {
1400                                 sd->uvco[2*i] = 0.0f;
1401                                 sd->uvco[2*i + 1] = 0.0f;
1402                         }
1403                 }
1404         }
1405
1406         /* get mcol */
1407         if(sd->mcol && ELEM(from,PART_FROM_FACE,PART_FROM_VOLUME)) {
1408                 for(i=0; i<sd->totcol; i++) {
1409                         if(num != DMCACHE_NOTFOUND) {
1410                                 MFace *mface = dm->getFaceData(dm, num, CD_MFACE);
1411                                 MCol *mc = (MCol*)CustomData_get_layer_n(&dm->faceData, CD_MCOL, i);
1412                                 mc += num * 4;
1413
1414                                 psys_interpolate_mcol(mc, mface->v4, fuv, sd->mcol + i);
1415                         }
1416                         else
1417                                 memset(&sd->mcol[i], 0, sizeof(MCol));
1418                 }
1419         }
1420 }
1421 static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem *psys, int timeoffset)
1422 {
1423         Object *ob= obr->ob;
1424         Object *tob=0;
1425         Material *ma=0;
1426         ParticleSystemModifierData *psmd;
1427         ParticleSystem *tpsys=0;
1428         ParticleSettings *part, *tpart=0;
1429         ParticleData *pars, *pa=0,*tpa=0;
1430         ParticleKey *states=0;
1431         ParticleKey state;
1432         ParticleCacheKey *cache=0;
1433         ParticleBillboardData bb;
1434         ParticleStrandData sd;
1435         StrandBuffer *strandbuf=0;
1436         StrandVert *svert=0;
1437         StrandBound *sbound= 0;
1438         StrandRen *strand=0;
1439         RNG *rng= 0;
1440         float loc[3],loc1[3],loc0[3],vel[3],mat[4][4],nmat[3][3],co[3],nor[3],time;
1441         float strandlen=0.0f, curlen=0.0f;
1442         float hasize, pa_size, pa_time, r_tilt, cfra=bsystem_time(re->scene, ob, (float)re->scene->r.cfra, 0.0);
1443         float random, simplify[2];
1444         int i, a, k, max_k=0, totpart, dosimplify = 0, dosurfacecache = 0;
1445         int totchild=0;
1446         int seed, path_nbr=0, orco1=0, num;
1447         int totface, *origindex = 0;
1448         char **uv_name=0;
1449
1450 /* 1. check that everything is ok & updated */
1451         if(psys==NULL)
1452                 return 0;
1453         
1454         totchild=psys->totchild;
1455
1456         part=psys->part;
1457         pars=psys->particles;
1458
1459         if(part==NULL || pars==NULL || !psys_check_enabled(ob, psys))
1460                 return 0;
1461         
1462         if(part->ren_as==PART_DRAW_OB || part->ren_as==PART_DRAW_GR || part->ren_as==PART_DRAW_NOT)
1463                 return 1;
1464
1465 /* 2. start initialising things */
1466         if(part->phystype==PART_PHYS_KEYED){
1467                 if(psys->flag & PSYS_FIRST_KEYED)
1468                         psys_count_keyed_targets(ob,psys);
1469                 else
1470                         return 1;
1471         }
1472
1473         /* last possibility to bail out! */
1474         psmd= psys_get_modifier(ob,psys);
1475         if(!(psmd->modifier.mode & eModifierMode_Render))
1476                 return 0;
1477
1478         if(G.rendering == 0) { /* preview render */
1479                 totchild = (int)((float)totchild * (float)part->disp / 100.0f);
1480         }
1481
1482         psys->flag |= PSYS_DRAWING;
1483
1484         rng= rng_new(psys->seed);
1485
1486         totpart=psys->totpart;
1487
1488         memset(&sd, 0, sizeof(ParticleStrandData));
1489         sd.override_uv = -1;
1490
1491 /* 2.1 setup material stff */
1492         ma= give_render_material(re, ob, part->omat);
1493         
1494 #if 0 // XXX old animation system
1495         if(ma->ipo){
1496                 calc_ipo(ma->ipo, cfra);
1497                 execute_ipo((ID *)ma, ma->ipo);
1498         }
1499 #endif // XXX old animation system
1500
1501         hasize = ma->hasize;
1502         seed = ma->seed1;
1503
1504         re->flag |= R_HALO;
1505
1506         RE_set_customdata_names(obr, &psmd->dm->faceData);
1507         sd.totuv = CustomData_number_of_layers(&psmd->dm->faceData, CD_MTFACE);
1508         sd.totcol = CustomData_number_of_layers(&psmd->dm->faceData, CD_MCOL);
1509
1510         if(ma->texco & TEXCO_UV && sd.totuv) {
1511                 sd.uvco = MEM_callocN(sd.totuv * 2 * sizeof(float), "particle_uvs");
1512
1513                 if(ma->strand_uvname[0]) {
1514                         sd.override_uv = CustomData_get_named_layer_index(&psmd->dm->faceData, CD_MTFACE, ma->strand_uvname);
1515                         sd.override_uv -= CustomData_get_layer_index(&psmd->dm->faceData, CD_MTFACE);
1516                 }
1517         }
1518         else
1519                 sd.uvco = NULL;
1520
1521         if(sd.totcol)
1522                 sd.mcol = MEM_callocN(sd.totcol * sizeof(MCol), "particle_mcols");
1523
1524 /* 2.2 setup billboards */
1525         if(part->ren_as == PART_DRAW_BB) {
1526                 int first_uv = CustomData_get_layer_index(&psmd->dm->faceData, CD_MTFACE);
1527
1528                 bb.uv[0] = CustomData_get_named_layer_index(&psmd->dm->faceData, CD_MTFACE, psys->bb_uvname[0]);
1529                 if(bb.uv[0] < 0)
1530                         bb.uv[0] = CustomData_get_active_layer_index(&psmd->dm->faceData, CD_MTFACE);
1531
1532                 bb.uv[1] = CustomData_get_named_layer_index(&psmd->dm->faceData, CD_MTFACE, psys->bb_uvname[1]);
1533
1534                 bb.uv[2] = CustomData_get_named_layer_index(&psmd->dm->faceData, CD_MTFACE, psys->bb_uvname[2]);
1535
1536                 if(first_uv >= 0) {
1537                         bb.uv[0] -= first_uv;
1538                         bb.uv[1] -= first_uv;
1539                         bb.uv[2] -= first_uv;
1540                 }
1541
1542                 bb.align = part->bb_align;
1543                 bb.anim = part->bb_anim;
1544                 bb.lock = part->draw & PART_DRAW_BB_LOCK;
1545                 bb.ob = (part->bb_ob ? part->bb_ob : re->scene->camera);
1546                 bb.offset[0] = part->bb_offset[0];
1547                 bb.offset[1] = part->bb_offset[1];
1548                 bb.split_offset = part->bb_split_offset;
1549                 bb.totnum = totpart+totchild;
1550                 bb.uv_split = part->bb_uv_split;
1551         }
1552
1553 #if 0 // XXX old animation system
1554 /* 2.3 setup time */
1555         if(part->flag&PART_ABS_TIME && part->ipo) {
1556                 calc_ipo(part->ipo, cfra);
1557                 execute_ipo((ID *)part, part->ipo);
1558         }
1559 #endif // XXX old animation system
1560
1561         if(part->flag & PART_GLOB_TIME)
1562                 cfra = bsystem_time(re->scene, 0, (float)re->scene->r.cfra, 0.0);
1563
1564 /* 2.4 setup reactors */
1565         if(part->type == PART_REACTOR){
1566                 psys_get_reactor_target(ob, psys, &tob, &tpsys);
1567                 if(tpsys && (part->from==PART_FROM_PARTICLE || part->phystype==PART_PHYS_NO)){
1568                         psmd = psys_get_modifier(tob,tpsys);
1569                         tpart = tpsys->part;
1570                 }
1571         }
1572         
1573 /* 2.5 setup matrices */
1574         MTC_Mat4MulMat4(mat, ob->obmat, re->viewmat);
1575         MTC_Mat4Invert(ob->imat, mat);  /* need to be that way, for imat texture */
1576         Mat3CpyMat4(nmat, ob->imat);
1577         Mat3Transp(nmat);
1578
1579 /* 2.6 setup strand rendering */
1580         if(part->ren_as == PART_DRAW_PATH && psys->pathcache){
1581                 path_nbr=(int)pow(2.0,(double) part->ren_step);
1582
1583                 if(path_nbr) {
1584                         if((ma->material_type != MA_TYPE_HALO) && (ma->mode & MA_WIRE)==0) {
1585                                 sd.orco = MEM_mallocN(3*sizeof(float)*(totpart+totchild), "particle orcos");
1586                                 set_object_orco(re, psys, sd.orco);
1587                         }
1588                 }
1589
1590                 if(part->draw & PART_DRAW_REN_ADAPT) {
1591                         sd.adapt = 1;
1592                         sd.adapt_pix = (float)part->adapt_pix;
1593                         sd.adapt_angle = cos((float)part->adapt_angle * (float)(M_PI / 180.0));
1594                 }
1595
1596                 if(re->r.renderer==R_INTERN && part->draw&PART_DRAW_REN_STRAND) {
1597                         strandbuf= RE_addStrandBuffer(obr, (totpart+totchild)*(path_nbr+1));
1598                         strandbuf->ma= ma;
1599                         strandbuf->lay= ob->lay;
1600                         Mat4CpyMat4(strandbuf->winmat, re->winmat);
1601                         strandbuf->winx= re->winx;
1602                         strandbuf->winy= re->winy;
1603                         strandbuf->maxdepth= 2;
1604                         strandbuf->adaptcos= cos((float)part->adapt_angle*(float)(M_PI/180.0));
1605                         strandbuf->overrideuv= sd.override_uv;
1606                         strandbuf->minwidth= ma->strand_min;
1607
1608                         if(ma->strand_widthfade == 0.0f)
1609                                 strandbuf->widthfade= 0.0f;
1610                         else if(ma->strand_widthfade >= 1.0f)
1611                                 strandbuf->widthfade= 2.0f - ma->strand_widthfade;
1612                         else
1613                                 strandbuf->widthfade= 1.0f/MAX2(ma->strand_widthfade, 1e-5f);
1614
1615                         if(part->flag & PART_HAIR_BSPLINE)
1616                                 strandbuf->flag |= R_STRAND_BSPLINE;
1617                         if(ma->mode & MA_STR_B_UNITS)
1618                                 strandbuf->flag |= R_STRAND_B_UNITS;
1619
1620                         svert= strandbuf->vert;
1621
1622                         if(re->r.mode & R_SPEED)
1623                                 dosurfacecache= 1;
1624                         else if((re->wrld.mode & WO_AMB_OCC) && (re->wrld.ao_gather_method == WO_AOGATHER_APPROX))
1625                                 if(ma->amb != 0.0f)
1626                                         dosurfacecache= 1;
1627
1628                         totface= psmd->dm->getNumFaces(psmd->dm);
1629                         origindex= psmd->dm->getFaceDataArray(psmd->dm, CD_ORIGINDEX);
1630                         if(origindex) {
1631                                 for(a=0; a<totface; a++)
1632                                         strandbuf->totbound= MAX2(strandbuf->totbound, origindex[a]);
1633                                 strandbuf->totbound++;
1634                         }
1635                         strandbuf->totbound++;
1636                         strandbuf->bound= MEM_callocN(sizeof(StrandBound)*strandbuf->totbound, "StrandBound");
1637                         sbound= strandbuf->bound;
1638                         sbound->start= sbound->end= 0;
1639                 }
1640         }
1641
1642         if(sd.orco == 0) {
1643                 sd.orco = MEM_mallocN(3 * sizeof(float), "particle orco");
1644                 orco1 = 1;
1645         }
1646
1647         if(path_nbr == 0)
1648                 psys->lattice = psys_get_lattice(re->scene, ob, psys);
1649
1650 /* 3. start creating renderable things */
1651         for(a=0,pa=pars; a<totpart+totchild; a++, pa++, seed++) {
1652                 random = rng_getFloat(rng);
1653                 /* setup per particle individual stuff */
1654                 if(a<totpart){
1655                         if(pa->flag & PARS_UNEXIST) continue;
1656
1657                         pa_time=(cfra-pa->time)/pa->lifetime;
1658                         if((part->flag&PART_ABS_TIME) == 0){
1659 #if 0 // XXX old animation system
1660                                 if(ma->ipo) {
1661                                         /* correction for lifetime */
1662                                         calc_ipo(ma->ipo, 100.0f * pa_time);
1663                                         execute_ipo((ID *)ma, ma->ipo);
1664                                 }
1665                                 if(part->ipo){
1666                                         /* correction for lifetime */
1667                                         calc_ipo(part->ipo, 100.0f*pa_time);
1668                                         execute_ipo((ID *)part, part->ipo);
1669                                 }
1670 #endif // XXX old animation system
1671                         }
1672
1673                         hasize = ma->hasize;
1674
1675                         /* get orco */
1676                         if(tpsys && (part->from==PART_FROM_PARTICLE || part->phystype==PART_PHYS_NO)){
1677                                 tpa=tpsys->particles+pa->num;
1678                                 psys_particle_on_emitter(psmd,tpart->from,tpa->num,pa->num_dmcache,tpa->fuv,tpa->foffset,co,nor,0,0,sd.orco,0);
1679                         }
1680                         else
1681                                 psys_particle_on_emitter(psmd,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,nor,0,0,sd.orco,0);
1682
1683                         /* get uvco & mcol */
1684                         num= pa->num_dmcache;
1685
1686                         if(num == DMCACHE_NOTFOUND)
1687                                 if(pa->num < psmd->dm->getNumFaces(psmd->dm))
1688                                         num= pa->num;
1689
1690                         get_particle_uvco_mcol(part->from, psmd->dm, pa->fuv, num, &sd);
1691
1692                         pa_size = pa->size;
1693
1694                         r_tilt = 1.0f + pa->r_ave[0];
1695
1696                         if(path_nbr) {
1697                                 cache = psys->pathcache[a];
1698                                 max_k = (int)cache->steps;
1699                         }
1700
1701                         if(totchild && (part->draw&PART_DRAW_PARENT)==0) continue;
1702                 }
1703                 else {
1704                         ChildParticle *cpa= psys->child+a-totpart;
1705
1706                         if(path_nbr) {
1707                                 cache = psys->childcache[a-totpart];
1708
1709                                 if(cache->steps < 0)
1710                                         continue;
1711
1712                                 max_k = (int)cache->steps;
1713                         }
1714                         
1715                         pa_time = psys_get_child_time(psys, cpa, cfra);
1716
1717                         if((part->flag & PART_ABS_TIME) == 0) {
1718 #if 0 // XXX old animation system
1719                                 if(ma->ipo){
1720                                         /* correction for lifetime */
1721                                         calc_ipo(ma->ipo, 100.0f * pa_time);
1722                                         execute_ipo((ID *)ma, ma->ipo);
1723                                 }
1724                                 if(part->ipo) {
1725                                         /* correction for lifetime */
1726                                         calc_ipo(part->ipo, 100.0f * pa_time);
1727                                         execute_ipo((ID *)part, part->ipo);
1728                                 }
1729 #endif // XXX old animation system
1730                         }
1731
1732                         pa_size = psys_get_child_size(psys, cpa, cfra, &pa_time);
1733
1734                         r_tilt = 2.0f * cpa->rand[2];
1735
1736                         num = cpa->num;
1737
1738                         /* get orco */
1739                         if(part->childtype == PART_CHILD_FACES) {
1740                                 psys_particle_on_emitter(psmd,
1741                                         PART_FROM_FACE, cpa->num,DMCACHE_ISCHILD,
1742                                         cpa->fuv,cpa->foffset,co,nor,0,0,sd.orco,0);
1743                         }
1744                         else {
1745                                 ParticleData *par = psys->particles + cpa->parent;
1746                                 psys_particle_on_emitter(psmd, part->from,
1747                                         par->num,DMCACHE_ISCHILD,par->fuv,
1748                                         par->foffset,co,nor,0,0,sd.orco,0);
1749                         }
1750
1751                         /* get uvco & mcol */
1752                         if(part->from!=PART_FROM_PARTICLE && part->childtype==PART_CHILD_FACES) {
1753                                 get_particle_uvco_mcol(PART_FROM_FACE, psmd->dm, cpa->fuv, cpa->num, &sd);
1754                         }
1755                         else {
1756                                 ParticleData *parent = psys->particles + cpa->parent;
1757                                 num = parent->num_dmcache;
1758
1759                                 if(num == DMCACHE_NOTFOUND)
1760                                         if(parent->num < psmd->dm->getNumFaces(psmd->dm))
1761                                                 num = parent->num;
1762
1763                                 get_particle_uvco_mcol(part->from, psmd->dm, pa->fuv, num, &sd);
1764                         }
1765
1766                         dosimplify = psys_render_simplify_params(psys, cpa, simplify);
1767
1768                         if(strandbuf) {
1769                                 if(origindex[cpa->num]+1 > sbound - strandbuf->bound) {
1770                                         sbound= strandbuf->bound + origindex[cpa->num]+1;
1771                                         sbound->start= sbound->end= obr->totstrand;
1772                                 }
1773                         }
1774                 }
1775
1776                 /* surface normal shading setup */
1777                 if(ma->mode_l & MA_STR_SURFDIFF) {
1778                         Mat3MulVecfl(nmat, nor);
1779                         sd.surfnor= nor;
1780                 }
1781                 else
1782                         sd.surfnor= NULL;
1783
1784                 /* strand render setup */
1785                 if(strandbuf) {
1786                         strand= RE_findOrAddStrand(obr, obr->totstrand++);
1787                         strand->buffer= strandbuf;
1788                         strand->vert= svert;
1789                         VECCOPY(strand->orco, sd.orco);
1790
1791                         if(dosimplify) {
1792                                 float *ssimplify= RE_strandren_get_simplify(obr, strand, 1);
1793                                 ssimplify[0]= simplify[0];
1794                                 ssimplify[1]= simplify[1];
1795                         }
1796
1797                         if(sd.surfnor) {
1798                                 float *snor= RE_strandren_get_surfnor(obr, strand, 1);
1799                                 VECCOPY(snor, sd.surfnor);
1800                         }
1801
1802                         if(dosurfacecache && num >= 0) {
1803                                 int *facenum= RE_strandren_get_face(obr, strand, 1);
1804                                 *facenum= num;
1805                         }
1806
1807                         if(sd.uvco) {
1808                                 for(i=0; i<sd.totuv; i++) {
1809                                         if(i != sd.override_uv) {
1810                                                 float *uv= RE_strandren_get_uv(obr, strand, i, NULL, 1);
1811
1812                                                 uv[0]= sd.uvco[2*i];
1813                                                 uv[1]= sd.uvco[2*i+1];
1814                                         }
1815                                 }
1816                         }
1817                         if(sd.mcol) {
1818                                 for(i=0; i<sd.totcol; i++) {
1819                                         MCol *mc= RE_strandren_get_mcol(obr, strand, i, NULL, 1);
1820                                         *mc = sd.mcol[i];
1821                                 }
1822                         }
1823
1824                         sbound->end++;
1825                 }
1826
1827                 /* strandco computation setup */
1828                 if(path_nbr) {
1829                         strandlen= 0.0f;
1830                         curlen= 0.0f;
1831                         for(k=1; k<=path_nbr; k++)
1832                                 if(k<=max_k)
1833                                         strandlen += VecLenf((cache+k-1)->co, (cache+k)->co);
1834                 }
1835
1836                 if(path_nbr) {
1837                         /* render strands */
1838                         for(k=0; k<=path_nbr; k++){
1839                                 if(k<=max_k){
1840                                         VECCOPY(state.co,(cache+k)->co);
1841                                         VECCOPY(state.vel,(cache+k)->vel);
1842                                 }
1843                                 else
1844                                         continue;       
1845
1846                                 if(k > 0)
1847                                         curlen += VecLenf((cache+k-1)->co, (cache+k)->co);
1848                                 time= curlen/strandlen;
1849
1850                                 VECCOPY(loc,state.co);
1851                                 MTC_Mat4MulVecfl(re->viewmat,loc);
1852
1853                                 if(strandbuf) {
1854                                         VECCOPY(svert->co, loc);
1855                                         svert->strandco= -1.0f + 2.0f*time;
1856                                         svert++;
1857                                         strand->totvert++;
1858                                 }
1859                                 else{
1860                                         sd.first = 0;
1861                                         sd.time = time;
1862                                         sd.size = hasize;
1863
1864                                         if(k==1){
1865                                                 sd.first = 1;
1866                                                 sd.time = 0.0f;
1867                                                 VECSUB(loc0,loc1,loc);
1868                                                 VECADD(loc0,loc1,loc0);
1869                                         }
1870
1871                                         if(k)
1872                                                 render_new_particle(re, obr, psmd->dm, ma, &sd, loc, loc1, seed);
1873
1874                                         VECCOPY(loc1,loc);
1875                                 }
1876                         }
1877
1878                 }
1879                 else {
1880                         /* render normal particles */
1881                         time=0.0f;
1882                         state.time=cfra;
1883                         if(psys_get_particle_state(re->scene,ob,psys,a,&state,0)==0)
1884                                 continue;
1885
1886                         VECCOPY(loc,state.co);
1887                         if(part->ren_as!=PART_DRAW_BB)
1888                                 MTC_Mat4MulVecfl(re->viewmat,loc);
1889
1890                         switch(part->ren_as) {
1891                                 case PART_DRAW_LINE:
1892                                         sd.line = 1;
1893                                         sd.time = 0.0f;
1894                                         sd.size = hasize;
1895
1896                                         VECCOPY(vel,state.vel);
1897                                         MTC_Mat4Mul3Vecfl(re->viewmat,vel);
1898                                         Normalize(vel);
1899
1900                                         if(part->draw & PART_DRAW_VEL_LENGTH)
1901                                                 VecMulf(vel,VecLength(state.vel));
1902
1903                                         VECADDFAC(loc0,loc,vel,-part->draw_line[0]);
1904                                         VECADDFAC(loc1,loc,vel,part->draw_line[1]);
1905
1906                                         render_new_particle(re,obr,psmd->dm,ma,&sd,loc0,loc1,seed);
1907
1908                                         break;
1909
1910                                 case PART_DRAW_BB:
1911                                         bb.random = random;
1912                                         bb.size = pa_size;
1913                                         bb.tilt = part->bb_tilt * (1.0f - part->bb_rand_tilt * r_tilt);
1914                                         bb.time = pa_time;
1915                                         bb.num = a;
1916                                         VECCOPY(bb.vec, loc);
1917                                         VECCOPY(bb.vel, state.vel);
1918
1919                                         particle_billboard(re, obr, ma, &bb);
1920
1921                                         break;
1922
1923                                 default:
1924                                 {
1925                                         HaloRen *har=0;
1926
1927                                         har = RE_inithalo_particle(re, obr, psmd->dm, ma, loc, NULL, sd.orco, sd.uvco, hasize, 0.0, seed);
1928                                         
1929                                         if(har) har->lay= obr->ob->lay;
1930
1931                                         break;
1932                                 }
1933                         }
1934                 }
1935
1936                 if(orco1==0)
1937                         sd.orco+=3;
1938
1939                 if(re->test_break(re->tbh))
1940                         break;
1941         }
1942
1943         if(dosurfacecache)
1944                 strandbuf->surface= cache_strand_surface(re, obr, psmd->dm, mat, timeoffset);
1945
1946 /* 4. clean up */
1947 #if 0 // XXX old animation system
1948         if(ma) do_mat_ipo(re->scene, ma);
1949 #endif // XXX old animation system
1950         
1951         if(orco1)
1952                 MEM_freeN(sd.orco);
1953
1954         if(sd.uvco)
1955                 MEM_freeN(sd.uvco);
1956         
1957         if(sd.mcol)
1958                 MEM_freeN(sd.mcol);
1959
1960         if(uv_name)
1961                 MEM_freeN(uv_name);
1962
1963         if(states)
1964                 MEM_freeN(states);
1965         
1966         rng_free(rng);
1967
1968         psys->flag &= ~PSYS_DRAWING;
1969
1970         if(psys->lattice){
1971                 end_latt_deform(psys->lattice);
1972                 psys->lattice= NULL;
1973         }
1974
1975         if(path_nbr && (ma->mode_l & MA_TANGENT_STR)==0)
1976                 calc_vertexnormals(re, obr, 0, 0);
1977
1978         return 1;
1979 }
1980
1981 /* ------------------------------------------------------------------------- */
1982 /* Halo's                                                                                                                                */
1983 /* ------------------------------------------------------------------------- */
1984
1985 static void make_render_halos(Render *re, ObjectRen *obr, Mesh *me, int totvert, MVert *mvert, Material *ma, float *orco)
1986 {
1987         Object *ob= obr->ob;
1988         HaloRen *har;
1989         float xn, yn, zn, nor[3], view[3];
1990         float vec[3], hasize, mat[4][4], imat[3][3];
1991         int a, ok, seed= ma->seed1;
1992
1993         MTC_Mat4MulMat4(mat, ob->obmat, re->viewmat);
1994         MTC_Mat3CpyMat4(imat, ob->imat);
1995
1996         re->flag |= R_HALO;
1997
1998         for(a=0; a<totvert; a++, mvert++) {
1999                 ok= 1;
2000
2001                 if(ok) {
2002                         hasize= ma->hasize;
2003
2004                         VECCOPY(vec, mvert->co);
2005                         MTC_Mat4MulVecfl(mat, vec);
2006
2007                         if(ma->mode & MA_HALOPUNO) {
2008                                 xn= mvert->no[0];
2009                                 yn= mvert->no[1];
2010                                 zn= mvert->no[2];
2011
2012                                 /* transpose ! */
2013                                 nor[0]= imat[0][0]*xn+imat[0][1]*yn+imat[0][2]*zn;
2014                                 nor[1]= imat[1][0]*xn+imat[1][1]*yn+imat[1][2]*zn;
2015                                 nor[2]= imat[2][0]*xn+imat[2][1]*yn+imat[2][2]*zn;
2016                                 Normalize(nor);
2017
2018                                 VECCOPY(view, vec);
2019                                 Normalize(view);
2020
2021                                 zn= nor[0]*view[0]+nor[1]*view[1]+nor[2]*view[2];
2022                                 if(zn>=0.0) hasize= 0.0;
2023                                 else hasize*= zn*zn*zn*zn;
2024                         }
2025
2026                         if(orco) har= RE_inithalo(re, obr, ma, vec, NULL, orco, hasize, 0.0, seed);
2027                         else har= RE_inithalo(re, obr, ma, vec, NULL, mvert->co, hasize, 0.0, seed);
2028                         if(har) har->lay= ob->lay;
2029                 }
2030                 if(orco) orco+= 3;
2031                 seed++;
2032         }
2033 }
2034
2035 static int verghalo(const void *a1, const void *a2)
2036 {
2037         const HaloRen *har1= *(const HaloRen**)a1;
2038         const HaloRen *har2= *(const HaloRen**)a2;
2039         
2040         if(har1->zs < har2->zs) return 1;
2041         else if(har1->zs > har2->zs) return -1;
2042         return 0;
2043 }
2044
2045 static void sort_halos(Render *re, int totsort)
2046 {
2047         ObjectRen *obr;
2048         HaloRen *har= NULL, **haso;
2049         int a;
2050
2051         if(re->tothalo==0) return;
2052
2053         re->sortedhalos= MEM_callocN(sizeof(HaloRen*)*re->tothalo, "sorthalos");
2054         haso= re->sortedhalos;
2055
2056         for(obr=re->objecttable.first; obr; obr=obr->next) {
2057                 for(a=0; a<obr->tothalo; a++) {
2058                         if((a & 255)==0) har= obr->bloha[a>>8];
2059                         else har++;
2060
2061                         *(haso++)= har;
2062                 }
2063         }
2064
2065         qsort(re->sortedhalos, totsort, sizeof(HaloRen*), verghalo);
2066 }
2067
2068 /* ------------------------------------------------------------------------- */
2069 /* Displacement Mapping                                                                                                          */
2070 /* ------------------------------------------------------------------------- */
2071
2072 static short test_for_displace(Render *re, Object *ob)
2073 {
2074         /* return 1 when this object uses displacement textures. */
2075         Material *ma;
2076         int i;
2077         
2078         for (i=1; i<=ob->totcol; i++) {
2079                 ma=give_render_material(re, ob, i);
2080                 /* ma->mapto is ORed total of all mapto channels */
2081                 if(ma && (ma->mapto & MAP_DISPLACE)) return 1;
2082         }
2083         return 0;
2084 }
2085
2086 static void displace_render_vert(Render *re, ObjectRen *obr, ShadeInput *shi, VertRen *vr, int vindex, float *scale, float mat[][4], float imat[][3])
2087 {
2088         MTFace *tface;
2089         short texco= shi->mat->texco;
2090         float sample=0, displace[3];
2091         char *name;
2092         int i;
2093
2094         /* shi->co is current render coord, just make sure at least some vector is here */
2095         VECCOPY(shi->co, vr->co);
2096         /* vertex normal is used for textures type 'col' and 'var' */
2097         VECCOPY(shi->vn, vr->n);
2098
2099         if(mat)
2100                 Mat4MulVecfl(mat, shi->co);
2101
2102         if(imat) {
2103                 shi->vn[0]= imat[0][0]*vr->n[0]+imat[0][1]*vr->n[1]+imat[0][2]*vr->n[2];
2104                 shi->vn[1]= imat[1][0]*vr->n[0]+imat[1][1]*vr->n[1]+imat[1][2]*vr->n[2];
2105                 shi->vn[2]= imat[2][0]*vr->n[0]+imat[2][1]*vr->n[1]+imat[2][2]*vr->n[2];
2106         }
2107
2108         if (texco & TEXCO_UV) {
2109                 shi->totuv= 0;
2110                 shi->actuv= obr->actmtface;
2111
2112                 for (i=0; (tface=RE_vlakren_get_tface(obr, shi->vlr, i, &name, 0)); i++) {
2113                         ShadeInputUV *suv= &shi->uv[i];
2114
2115                         /* shi.uv needs scale correction from tface uv */
2116                         suv->uv[0]= 2*tface->uv[vindex][0]-1.0f;
2117                         suv->uv[1]= 2*tface->uv[vindex][1]-1.0f;
2118                         suv->uv[2]= 0.0f;
2119                         suv->name= name;
2120                         shi->totuv++;
2121                 }
2122         }
2123
2124         /* set all rendercoords, 'texco' is an ORed value for all textures needed */
2125         if ((texco & TEXCO_ORCO) && (vr->orco)) {
2126                 VECCOPY(shi->lo, vr->orco);
2127         }
2128         if (texco & TEXCO_STICKY) {
2129                 float *sticky= RE_vertren_get_sticky(obr, vr, 0);
2130                 if(sticky) {
2131                         shi->sticky[0]= sticky[0];
2132                         shi->sticky[1]= sticky[1];
2133                         shi->sticky[2]= 0.0f;
2134                 }
2135         }
2136         if (texco & TEXCO_GLOB) {
2137                 VECCOPY(shi->gl, shi->co);
2138                 MTC_Mat4MulVecfl(re->viewinv, shi->gl);
2139         }
2140         if (texco & TEXCO_NORM) {
2141                 VECCOPY(shi->orn, shi->vn);
2142         }
2143         if(texco & TEXCO_REFL) {
2144                 /* not (yet?) */
2145         }
2146         
2147         shi->displace[0]= shi->displace[1]= shi->displace[2]= 0.0;
2148         
2149         do_material_tex(shi);
2150         
2151         //printf("no=%f, %f, %f\nbefore co=%f, %f, %f\n", vr->n[0], vr->n[1], vr->n[2], 
2152         //vr->co[0], vr->co[1], vr->co[2]);
2153
2154         displace[0]= shi->displace[0] * scale[0];
2155         displace[1]= shi->displace[1] * scale[1];
2156         displace[2]= shi->displace[2] * scale[2];
2157         
2158         if(mat)
2159                 Mat3MulVecfl(imat, displace);
2160
2161         /* 0.5 could become button once?  */
2162         vr->co[0] += displace[0]; 
2163         vr->co[1] += displace[1];
2164         vr->co[2] += displace[2];
2165         
2166         //printf("after co=%f, %f, %f\n", vr->co[0], vr->co[1], vr->co[2]); 
2167         
2168         /* we just don't do this vertex again, bad luck for other face using same vertex with
2169                 different material... */
2170         vr->flag |= 1;
2171         
2172         /* Pass sample back so displace_face can decide which way to split the quad */
2173         sample  = shi->displace[0]*shi->displace[0];
2174         sample += shi->displace[1]*shi->displace[1];
2175         sample += shi->displace[2]*shi->displace[2];
2176         
2177         vr->accum=sample; 
2178         /* Should be sqrt(sample), but I'm only looking for "bigger".  Save the cycles. */
2179         return;
2180 }
2181
2182 static void displace_render_face(Render *re, ObjectRen *obr, VlakRen *vlr, float *scale, float mat[][4], float imat[][3])
2183 {
2184         ShadeInput shi;
2185
2186         /* Warning, This is not that nice, and possibly a bit slow,
2187         however some variables were not initialized properly in, unless using shade_input_initialize(...), we need to do a memset */
2188         memset(&shi, 0, sizeof(ShadeInput)); 
2189         /* end warning! - Campbell */
2190         
2191         /* set up shadeinput struct for multitex() */
2192         
2193         /* memset above means we dont need this */
2194         /*shi.osatex= 0;*/              /* signal not to use dx[] and dy[] texture AA vectors */
2195
2196         shi.vlr= vlr;           /* current render face */
2197         shi.mat= vlr->mat;              /* current input material */
2198         shi.thread= 0;
2199         
2200         /* Displace the verts, flag is set when done */
2201         if (!vlr->v1->flag)
2202                 displace_render_vert(re, obr, &shi, vlr->v1,0,  scale, mat, imat);
2203         
2204         if (!vlr->v2->flag)
2205                 displace_render_vert(re, obr, &shi, vlr->v2, 1, scale, mat, imat);
2206
2207         if (!vlr->v3->flag)
2208                 displace_render_vert(re, obr, &shi, vlr->v3, 2, scale, mat, imat);
2209
2210         if (vlr->v4) {
2211                 if (!vlr->v4->flag)
2212                         displace_render_vert(re, obr, &shi, vlr->v4, 3, scale, mat, imat);
2213
2214                 /*      closest in displace value.  This will help smooth edges.   */ 
2215                 if ( fabs(vlr->v1->accum - vlr->v3->accum) > fabs(vlr->v2->accum - vlr->v4->accum)) 
2216                         vlr->flag |= R_DIVIDE_24;
2217                 else vlr->flag &= ~R_DIVIDE_24;
2218         }
2219         
2220         /* Recalculate the face normal  - if flipped before, flip now */
2221         if(vlr->v4) {
2222                 CalcNormFloat4(vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
2223         }       
2224         else {
2225                 CalcNormFloat(vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
2226         }
2227 }
2228
2229 static void do_displacement(Render *re, ObjectRen *obr, float mat[][4], float imat[][3])
2230 {
2231         VertRen *vr;
2232         VlakRen *vlr;
2233 //      float min[3]={1e30, 1e30, 1e30}, max[3]={-1e30, -1e30, -1e30};
2234         float scale[3]={1.0f, 1.0f, 1.0f}, temp[3];//, xn
2235         int i; //, texflag=0;
2236         Object *obt;
2237                 
2238         /* Object Size with parenting */
2239         obt=obr->ob;
2240         while(obt){
2241                 VecAddf(temp, obt->size, obt->dsize);
2242                 scale[0]*=temp[0]; scale[1]*=temp[1]; scale[2]*=temp[2];
2243                 obt=obt->parent;
2244         }
2245         
2246         /* Clear all flags */
2247         for(i=0; i<obr->totvert; i++){ 
2248                 vr= RE_findOrAddVert(obr, i);
2249                 vr->flag= 0;
2250         }
2251
2252         for(i=0; i<obr->totvlak; i++){
2253                 vlr=RE_findOrAddVlak(obr, i);
2254                 displace_render_face(re, obr, vlr, scale, mat, imat);
2255         }
2256         
2257         /* Recalc vertex normals */
2258         calc_vertexnormals(re, obr, 0, 0);
2259 }
2260
2261 /* ------------------------------------------------------------------------- */
2262 /* Metaball                                                                                                                              */
2263 /* ------------------------------------------------------------------------- */
2264
2265 static void init_render_mball(Render *re, ObjectRen *obr)
2266 {
2267         Object *ob= obr->ob;
2268         DispList *dl;
2269         VertRen *ver;
2270         VlakRen *vlr, *vlr1;
2271         Material *ma;
2272         float *data, *nors, *orco, mat[4][4], imat[3][3], xn, yn, zn;
2273         int a, need_orco, vlakindex, *index;
2274
2275         if (ob!=find_basis_mball(re->scene, ob))
2276                 return;
2277
2278         MTC_Mat4MulMat4(mat, ob->obmat, re->viewmat);
2279         MTC_Mat4Invert(ob->imat, mat);
2280         MTC_Mat3CpyMat4(imat, ob->imat);
2281
2282         ma= give_render_material(re, ob, 1);
2283
2284         need_orco= 0;
2285         if(ma->texco & TEXCO_ORCO) {
2286                 need_orco= 1;
2287         }
2288         
2289         makeDispListMBall(re->scene, ob);
2290         dl= ob->disp.first;
2291         if(dl==0) return;
2292
2293         data= dl->verts;
2294         nors= dl->nors;
2295         orco= get_object_orco(re, ob);
2296
2297         for(a=0; a<dl->nr; a++, data+=3, nors+=3, orco+=3) {
2298
2299                 ver= RE_findOrAddVert(obr, obr->totvert++);
2300                 VECCOPY(ver->co, data);
2301                 MTC_Mat4MulVecfl(mat, ver->co);
2302
2303                 /* render normals are inverted */
2304                 xn= -nors[0];
2305                 yn= -nors[1];
2306                 zn= -nors[2];
2307
2308                 /* transpose ! */
2309                 ver->n[0]= imat[0][0]*xn+imat[0][1]*yn+imat[0][2]*zn;
2310                 ver->n[1]= imat[1][0]*xn+imat[1][1]*yn+imat[1][2]*zn;
2311                 ver->n[2]= imat[2][0]*xn+imat[2][1]*yn+imat[2][2]*zn;
2312                 Normalize(ver->n);
2313                 //if(ob->transflag & OB_NEG_SCALE) VecMulf(ver->n. -1.0);
2314                 
2315                 if(need_orco) ver->orco= orco;
2316         }
2317
2318         index= dl->index;
2319         for(a=0; a<dl->parts; a++, index+=4) {
2320
2321                 vlr= RE_findOrAddVlak(obr, obr->totvlak++);
2322                 vlr->v1= RE_findOrAddVert(obr, index[0]);
2323                 vlr->v2= RE_findOrAddVert(obr, index[1]);
2324                 vlr->v3= RE_findOrAddVert(obr, index[2]);
2325                 vlr->v4= 0;
2326
2327                 if(ob->transflag & OB_NEG_SCALE) 
2328                         CalcNormFloat(vlr->v1->co, vlr->v2->co, vlr->v3->co, vlr->n);
2329                 else
2330                         CalcNormFloat(vlr->v3->co, vlr->v2->co, vlr->v1->co, vlr->n);
2331
2332                 vlr->mat= ma;
2333                 vlr->flag= ME_SMOOTH+R_NOPUNOFLIP;
2334                 vlr->ec= 0;
2335
2336                 /* mball -too bad- always has triangles, because quads can be non-planar */
2337                 if(index[3] && index[3]!=index[2]) {
2338                         vlr1= RE_findOrAddVlak(obr, obr->totvlak++);
2339                         vlakindex= vlr1->index;
2340                         *vlr1= *vlr;
2341                         vlr1->index= vlakindex;
2342                         vlr1->v2= vlr1->v3;
2343                         vlr1->v3= RE_findOrAddVert(obr, index[3]);
2344                         if(ob->transflag & OB_NEG_SCALE) 
2345                                 CalcNormFloat(vlr1->v1->co, vlr1->v2->co, vlr1->v3->co, vlr1->n);
2346                         else
2347                                 CalcNormFloat(vlr1->v3->co, vlr1->v2->co, vlr1->v1->co, vlr1->n);
2348                 }
2349         }
2350
2351         /* enforce display lists remade */
2352         freedisplist(&ob->disp);
2353         
2354         /* this enforces remake for real, orco displist is small (in scale) */
2355         ob->recalc |= OB_RECALC_DATA;
2356 }
2357
2358 /* ------------------------------------------------------------------------- */
2359 /* Surfaces and Curves                                                                                                           */
2360 /* ------------------------------------------------------------------------- */
2361
2362 /* returns amount of vertices added for orco */
2363 static int dl_surf_to_renderdata(ObjectRen *obr, DispList *dl, Material **matar, float *orco, float mat[4][4])
2364 {
2365         Object *ob= obr->ob;
2366         VertRen *v1, *v2, *v3, *v4, *ver;
2367         VlakRen *vlr, *vlr1, *vlr2, *vlr3;
2368         Curve *cu= ob->data;
2369         float *data, n1[3];
2370         int u, v, orcoret= 0;
2371         int p1, p2, p3, p4, a;
2372         int sizeu, nsizeu, sizev, nsizev;
2373         int startvert, startvlak;
2374         
2375         startvert= obr->totvert;
2376         nsizeu = sizeu = dl->parts; nsizev = sizev = dl->nr; 
2377         
2378         data= dl->verts;
2379         for (u = 0; u < sizeu; u++) {
2380                 v1 = RE_findOrAddVert(obr, obr->totvert++); /* save this for possible V wrapping */
2381                 VECCOPY(v1->co, data); data += 3;
2382                 if(orco) {
2383                         v1->orco= orco; orco+= 3; orcoret++;
2384                 }       
2385                 MTC_Mat4MulVecfl(mat, v1->co);
2386                 
2387                 for (v = 1; v < sizev; v++) {
2388                         ver= RE_findOrAddVert(obr, obr->totvert++);
2389                         VECCOPY(ver->co, data); data += 3;
2390                         if(orco) {
2391                                 ver->orco= orco; orco+= 3; orcoret++;
2392                         }       
2393                         MTC_Mat4MulVecfl(mat, ver->co);
2394                 }
2395                 /* if V-cyclic, add extra vertices at end of the row */
2396                 if (dl->flag & DL_CYCL_U) {
2397                         ver= RE_findOrAddVert(obr, obr->totvert++);
2398                         VECCOPY(ver->co, v1->co);
2399                         if(orco) {
2400                                 ver->orco= orco; orco+=3; orcoret++; //orcobase + 3*(u*sizev + 0);
2401                         }
2402                 }       
2403         }       
2404         
2405         /* Done before next loop to get corner vert */
2406         if (dl->flag & DL_CYCL_U) nsizev++;
2407         if (dl->flag & DL_CYCL_V) nsizeu++;
2408         
2409         /* if U cyclic, add extra row at end of column */
2410         if (dl->flag & DL_CYCL_V) {
2411                 for (v = 0; v < nsizev; v++) {
2412                         v1= RE_findOrAddVert(obr, startvert + v);
2413                         ver= RE_findOrAddVert(obr, obr->totvert++);
2414                         VECCOPY(ver->co, v1->co);
2415                         if(orco) {
2416                                 ver->orco= orco; orco+=3; orcoret++; //ver->orco= orcobase + 3*(0*sizev + v);
2417                         }
2418                 }
2419         }
2420         
2421         sizeu = nsizeu;
2422         sizev = nsizev;
2423         
2424         startvlak= obr->totvlak;
2425         
2426         for(u = 0; u < sizeu - 1; u++) {
2427                 p1 = startvert + u * sizev; /* walk through face list */
2428                 p2 = p1 + 1;
2429                 p3 = p2 + sizev;
2430                 p4 = p3 - 1;
2431                 
2432                 for(v = 0; v < sizev - 1; v++) {
2433                         v1= RE_findOrAddVert(obr, p1);
2434                         v2= RE_findOrAddVert(obr, p2);
2435                         v3= RE_findOrAddVert(obr, p3);
2436                         v4= RE_findOrAddVert(obr, p4);
2437                         
2438                         vlr= RE_findOrAddVlak(obr, obr->totvlak++);
2439                         vlr->v1= v1; vlr->v2= v2; vlr->v3= v3; vlr->v4= v4;
2440                         
2441                         CalcNormFloat4(vlr->v4->co, vlr->v3->co, vlr->v2->co, vlr->v1->co, n1);
2442                         
2443                         VECCOPY(vlr->n, n1);
2444                         
2445                         vlr->mat= matar[ dl->col];
2446                         vlr->ec= ME_V1V2+ME_V2V3;
2447                         vlr->flag= dl->rt;
2448                         if( (cu->flag & CU_NOPUNOFLIP) ) {
2449                                 vlr->flag |= R_NOPUNOFLIP;
2450                         }
2451                         
2452                         VecAddf(v1->n, v1->n, n1);
2453                         VecAddf(v2->n, v2->n, n1);
2454                         VecAddf(v3->n, v3->n, n1);
2455                         VecAddf(v4->n, v4->n, n1);
2456                         
2457                         p1++; p2++; p3++; p4++;
2458                 }
2459         }       
2460         /* fix normals for U resp. V cyclic faces */
2461         sizeu--; sizev--;  /* dec size for face array */
2462         if (dl->flag & DL_CYCL_V) {
2463                 
2464                 for (v = 0; v < sizev; v++)
2465                 {
2466                         /* optimize! :*/
2467                         vlr= RE_findOrAddVlak(obr, UVTOINDEX(sizeu - 1, v));
2468                         vlr1= RE_findOrAddVlak(obr, UVTOINDEX(0, v));
2469                         VecAddf(vlr1->v1->n, vlr1->v1->n, vlr->n);
2470                         VecAddf(vlr1->v2->n, vlr1->v2->n, vlr->n);
2471                         VecAddf(vlr->v3->n, vlr->v3->n, vlr1->n);
2472                         VecAddf(vlr->v4->n, vlr->v4->n, vlr1->n);
2473                 }
2474         }
2475         if (dl->flag & DL_CYCL_U) {
2476                 
2477                 for (u = 0; u < sizeu; u++)
2478                 {
2479                         /* optimize! :*/
2480                         vlr= RE_findOrAddVlak(obr, UVTOINDEX(u, 0));
2481                         vlr1= RE_findOrAddVlak(obr, UVTOINDEX(u, sizev-1));
2482                         VecAddf(vlr1->v2->n, vlr1->v2->n, vlr->n);
2483                         VecAddf(vlr1->v3->n, vlr1->v3->n, vlr->n);
2484                         VecAddf(vlr->v1->n, vlr->v1->n, vlr1->n);
2485                         VecAddf(vlr->v4->n, vlr->v4->n, vlr1->n);
2486                 }
2487         }
2488         /* last vertex is an extra case: 
2489                 
2490                 ^       ()----()----()----()
2491                 |       |     |     ||     |
2492                 u       |     |(0,n)||(0,0)|
2493                 |     |     ||     |
2494                 ()====()====[]====()
2495                 |     |     ||     |
2496                 |     |(m,n)||(m,0)|
2497                 |     |     ||     |
2498                 ()----()----()----()
2499                 v ->
2500                 
2501                 vertex [] is no longer shared, therefore distribute
2502                 normals of the surrounding faces to all of the duplicates of []
2503                 */
2504         
2505         if ((dl->flag & DL_CYCL_V) && (dl->flag & DL_CYCL_U))
2506         {
2507                 vlr= RE_findOrAddVlak(obr, UVTOINDEX(sizeu - 1, sizev - 1)); /* (m,n) */
2508                 vlr1= RE_findOrAddVlak(obr, UVTOINDEX(0,0));  /* (0,0) */
2509                 VecAddf(n1, vlr->n, vlr1->n);
2510                 vlr2= RE_findOrAddVlak(obr, UVTOINDEX(0, sizev-1)); /* (0,n) */
2511                 VecAddf(n1, n1, vlr2->n);
2512                 vlr3= RE_findOrAddVlak(obr, UVTOINDEX(sizeu-1, 0)); /* (m,0) */
2513                 VecAddf(n1, n1, vlr3->n);
2514                 VECCOPY(vlr->v3->n, n1);
2515                 VECCOPY(vlr1->v1->n, n1);
2516                 VECCOPY(vlr2->v2->n, n1);
2517                 VECCOPY(vlr3->v4->n, n1);
2518         }
2519         for(a = startvert; a < obr->totvert; a++) {
2520                 ver= RE_findOrAddVert(obr, a);
2521                 Normalize(ver->n);
2522         }
2523         
2524         
2525         return orcoret;
2526 }
2527
2528 static void init_render_surf(Render *re, ObjectRen *obr)
2529 {
2530         Object *ob= obr->ob;
2531         Nurb *nu=0;
2532         Curve *cu;
2533         ListBase displist;
2534         DispList *dl;
2535         Material *matar[32];
2536         float *orco=NULL, *orcobase=NULL, mat[4][4];
2537         int a, need_orco=0;
2538
2539         cu= ob->data;
2540         nu= cu->nurb.first;
2541         if(nu==0) return;
2542
2543         MTC_Mat4MulMat4(mat, ob->obmat, re->viewmat);
2544         MTC_Mat4Invert(ob->imat, mat);
2545
2546         /* material array */
2547         memset(matar, 0, 4*32);
2548         matar[0]= give_render_material(re, ob, 0);
2549         for(a=0; a<ob->totcol; a++) {
2550                 matar[a]= give_render_material(re, ob, a+1);
2551                 if(matar[a] && matar[a]->texco & TEXCO_ORCO) {
2552                         need_orco= 1;
2553                 }
2554         }
2555
2556         if(ob->parent && (ob->parent->type==OB_LATTICE)) need_orco= 1;
2557
2558         if(need_orco) orcobase= orco= get_object_orco(re, ob);
2559
2560         displist.first= displist.last= 0;
2561         makeDispListSurf(re->scene, ob, &displist, 1);
2562
2563         dl= displist.first;
2564         /* walk along displaylist and create rendervertices/-faces */
2565         while(dl) {
2566                         /* watch out: u ^= y, v ^= x !! */
2567                 if(dl->type==DL_SURF) {
2568                         orco+= 3*dl_surf_to_renderdata(obr, dl, matar, orco, mat);
2569                 }
2570
2571                 dl= dl->next;
2572         }
2573         freedisplist(&displist);
2574 }
2575
2576 static void init_render_curve(Render *re, ObjectRen *obr, int timeoffset)
2577 {
2578         Object *ob= obr->ob;
2579         Curve *cu;
2580         VertRen *ver;
2581         VlakRen *vlr;
2582         DispList *dl;
2583         ListBase olddl={NULL, NULL};
2584         Material *matar[32];
2585         float len, *data, *fp, *orco=NULL, *orcobase= NULL;
2586         float n[3], mat[4][4];
2587         int nr, startvert, startvlak, a, b;
2588         int frontside, need_orco=0;
2589
2590         cu= ob->data;
2591         if(ob->type==OB_FONT && cu->str==NULL) return;
2592         else if(ob->type==OB_CURVE && cu->nurb.first==NULL) return;
2593
2594         /* no modifier call here, is in makedisp */
2595
2596         if(cu->resolu_ren) 
2597                 SWAP(ListBase, olddl, cu->disp);
2598         
2599         /* test displist */
2600         if(cu->disp.first==NULL) 
2601                 makeDispListCurveTypes(re->scene, ob, 0);
2602         dl= cu->disp.first;
2603         if(cu->disp.first==NULL) return;
2604         
2605         MTC_Mat4MulMat4(mat, ob->obmat, re->viewmat);
2606         MTC_Mat4Invert(ob->imat, mat);
2607
2608         /* material array */
2609         memset(matar, 0, 4*32);
2610         matar[0]= give_render_material(re, ob, 0);
2611         for(a=0; a<ob->totcol; a++) {
2612                 matar[a]= give_render_material(re, ob, a+1);
2613                 if(matar[a]->texco & TEXCO_ORCO) {
2614                         need_orco= 1;
2615                 }
2616         }
2617
2618         if(need_orco) orcobase=orco= get_object_orco(re, ob);
2619
2620         dl= cu->disp.first;
2621         while(dl) {
2622                 if(dl->type==DL_INDEX3) {
2623                         int *index;
2624
2625                         startvert= obr->totvert;
2626                         data= dl->verts;
2627
2628                         n[0]= ob->imat[0][2];
2629                         n[1]= ob->imat[1][2];
2630                         n[2]= ob->imat[2][2];
2631                         Normalize(n);
2632
2633                         for(a=0; a<dl->nr; a++, data+=3) {
2634                                 ver= RE_findOrAddVert(obr, obr->totvert++);
2635                                 VECCOPY(ver->co, data);
2636
2637                                 /* flip normal if face is backfacing, also used in face loop below */
2638                                 if(ver->co[2] < 0.0) {
2639                                         VECCOPY(ver->n, n);
2640                                         ver->flag = 1;
2641                                 }
2642                                 else {
2643                                         ver->n[0]= -n[0]; ver->n[1]= -n[1]; ver->n[2]= -n[2];
2644                                         ver->flag = 0;
2645                                 }
2646
2647                                 MTC_Mat4MulVecfl(mat, ver->co);
2648                                 
2649                                 if (orco) {
2650                                         ver->orco = orco;
2651                                         orco += 3;
2652                                 }
2653                         }
2654                         
2655                         if(timeoffset==0) {
2656                                 startvlak= obr->totvlak;
2657                                 index= dl->index;
2658                                 for(a=0; a<dl->parts; a++, index+=3) {
2659
2660                                         vlr= RE_findOrAddVlak(obr, obr->totvlak++);
2661                                         vlr->v1= RE_findOrAddVert(obr, startvert+index[0]);
2662                                         vlr->v2= RE_findOrAddVert(obr, startvert+index[1]);
2663                                         vlr->v3= RE_findOrAddVert(obr, startvert+index[2]);
2664                                         vlr->v4= NULL;
2665                                         
2666                                         if(vlr->v1->flag) {
2667                                                 VECCOPY(vlr->n, n);
2668                                         }
2669                                         else {
2670                                                 vlr->n[0]= -n[0]; vlr->n[1]= -n[1]; vlr->n[2]= -n[2];
2671                                         }
2672                                         
2673                                         vlr->mat= matar[ dl->col ];
2674                                         vlr->flag= 0;
2675                                         if( (cu->flag & CU_NOPUNOFLIP) ) {
2676                                                 vlr->flag |= R_NOPUNOFLIP;
2677                                         }
2678                                         vlr->ec= 0;
2679                                 }
2680                         }
2681                 }
2682                 else if (dl->type==DL_SURF) {
2683                         
2684                         /* cyclic U means an extruded full circular curve, we skip bevel splitting then */
2685                         if (dl->flag & DL_CYCL_U) {
2686                                 orco+= 3*dl_surf_to_renderdata(obr, dl, matar, orco, mat);
2687                         }
2688                         else {
2689                                 int p1,p2,p3,p4;
2690
2691                                 fp= dl->verts;
2692                                 startvert= obr->totvert;
2693                                 nr= dl->nr*dl->parts;
2694
2695                                 while(nr--) {
2696                                         ver= RE_findOrAddVert(obr, obr->totvert++);
2697                                                 
2698                                         VECCOPY(ver->co, fp);
2699                                         MTC_Mat4MulVecfl(mat, ver->co);
2700                                         fp+= 3;
2701
2702                                         if (orco) {
2703                                                 ver->orco = orco;
2704                                                 orco += 3;
2705                                         }
2706                                 }
2707
2708                                 if(dl->bevelSplitFlag || timeoffset==0) {
2709                                         startvlak= obr->totvlak;
2710
2711                                         for(a=0; a<dl->parts; a++) {
2712
2713                                                 frontside= (a >= dl->nr/2);
2714                                                 
2715                                                 if (surfindex_displist(dl, a, &b, &p1, &p2, &p3, &p4)==0)
2716                                                         break;
2717                                                 
2718                                                 p1+= startvert;
2719                                                 p2+= startvert;
2720                                                 p3+= startvert;
2721                                                 p4+= startvert;
2722
2723                                                 for(; b<dl->nr; b++) {
2724                                                         vlr= RE_findOrAddVlak(obr, obr->totvlak++);
2725                                                         vlr->v1= RE_findOrAddVert(obr, p2);
2726                                                         vlr->v2= RE_findOrAddVert(obr, p1);
2727                                                         vlr->v3= RE_findOrAddVert(obr, p3);
2728                                                         vlr->v4= RE_findOrAddVert(obr, p4);
2729                                                         vlr->ec= ME_V2V3+ME_V3V4;
2730                                                         if(a==0) vlr->ec+= ME_V1V2;
2731
2732                                                         vlr->flag= dl->rt;
2733
2734                                                         /* this is not really scientific: the vertices
2735                                                                 * 2, 3 en 4 seem to give better vertexnormals than 1 2 3:
2736                                                                 * front and backside treated different!!
2737                                                                 */
2738
2739                                                         if(frontside)
2740                                                                 CalcNormFloat(vlr->v2->co, vlr->v3->co, vlr->v4->co, vlr->n);
2741                                                         else 
2742                                                                 CalcNormFloat(vlr->v1->co, vlr->v2->co, vlr->v3->co, vlr->n);
2743
2744                                                         vlr->mat= matar[ dl->col ];
2745
2746                                                         p4= p3;
2747                                                         p3++;
2748                                                         p2= p1;
2749                                                         p1++;
2750                                                 }
2751                                         }
2752
2753                                         if (dl->bevelSplitFlag) {
2754                                                 for(a=0; a<dl->parts-1+!!(dl->flag&DL_CYCL_V); a++)
2755                                                         if(dl->bevelSplitFlag[a>>5]&(1<<(a&0x1F)))
2756                                                                 split_v_renderfaces(obr, startvlak, startvert, dl->parts, dl->nr, a, dl->flag&DL_CYCL_V, dl->flag&DL_CYCL_U);
2757                                         }
2758
2759                                         /* vertex normals */
2760                                         for(a= startvlak; a<obr->totvlak; a++) {
2761                                                 vlr= RE_findOrAddVlak(obr, a);
2762
2763                                                 VecAddf(vlr->v1->n, vlr->v1->n, vlr->n);
2764                                                 VecAddf(vlr->v3->n, vlr->v3->n, vlr->n);
2765                                                 VecAddf(vlr->v2->n, vlr->v2->n, vlr->n);
2766                                                 VecAddf(vlr->v4->n, vlr->v4->n, vlr->n);
2767                                         }
2768                                         for(a=startvert; a<obr->totvert; a++) {
2769                                                 ver= RE_findOrAddVert(obr, a);
2770                                                 len= Normalize(ver->n);
2771                                                 if(len==0.0) ver->flag= 1;      /* flag abuse, its only used in zbuf now  */
2772                                                 else ver->flag= 0;
2773                                         }
2774                                         for(a= startvlak; a<obr->totvlak; a++) {
2775                                                 vlr= RE_findOrAddVlak(obr, a);
2776                                                 if(vlr->v1->flag) VECCOPY(vlr->v1->n, vlr->n);
2777                                                 if(vlr->v2->flag) VECCOPY(vlr->v2->n, vlr->n);
2778                                                 if(vlr->v3->flag) VECCOPY(vlr->v3->n, vlr->n);
2779                                                 if(vlr->v4->flag) VECCOPY(vlr->v4->n, vlr->n);
2780                                         }
2781                                 }
2782                         }
2783                 }
2784
2785                 dl= dl->next;
2786         }
2787         
2788         /* not very elegant... but we want original displist in UI */
2789         if(cu->resolu_ren) {
2790                 freedisplist(&cu->disp);
2791                 SWAP(ListBase, olddl, cu->disp);
2792         }
2793 }
2794
2795 /* ------------------------------------------------------------------------- */
2796 /* Mesh                                                                                                                                  */
2797 /* ------------------------------------------------------------------------- */
2798
2799 struct edgesort {
2800         int v1, v2;
2801         int f;
2802         int i1, i2;
2803 };
2804
2805 /* edges have to be added with lowest index first for sorting */
2806 static void to_edgesort(struct edgesort *ed, int i1, int i2, int v1, int v2, int f)
2807 {
2808         if(v1>v2) {
2809                 SWAP(int, v1, v2);
2810                 SWAP(int, i1, i2);
2811         }
2812
2813         ed->v1= v1;
2814         ed->v2= v2;
2815         ed->i1= i1;
2816         ed->i2= i2;
2817         ed->f = f;
2818 }
2819
2820 static int vergedgesort(const void *v1, const void *v2)
2821 {
2822         const struct edgesort *x1=v1, *x2=v2;
2823         
2824         if( x1->v1 > x2->v1) return 1;
2825         else if( x1->v1 < x2->v1) return -1;
2826         else if( x1->v2 > x2->v2) return 1;
2827         else if( x1->v2 < x2->v2) return -1;
2828         
2829         return 0;
2830 }
2831
2832 static struct edgesort *make_mesh_edge_lookup(DerivedMesh *dm, int *totedgesort)
2833 {
2834         MFace *mf, *mface;
2835         MTFace *tface=NULL;
2836         struct edgesort *edsort, *ed;
2837         unsigned int *mcol=NULL;