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