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