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