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