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