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