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