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