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