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