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