Merge branch 'master' into blender2.8
[blender.git] / source / blender / alembic / intern / abc_mesh.cc
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  * Contributor(s): Esteban Tovagliari, Cedric Paille, Kevin Dietrich
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 #include "abc_mesh.h"
24
25 #include <algorithm>
26
27 #include "abc_transform.h"
28 #include "abc_util.h"
29
30 extern "C" {
31 #include "DNA_material_types.h"
32 #include "DNA_mesh_types.h"
33 #include "DNA_meshdata_types.h"
34 #include "DNA_modifier_types.h"
35 #include "DNA_object_fluidsim_types.h"
36 #include "DNA_object_types.h"
37
38 #include "BLI_math_geom.h"
39 #include "BLI_string.h"
40
41 #include "BKE_main.h"
42 #include "BKE_material.h"
43 #include "BKE_mesh.h"
44 #include "BKE_mesh_runtime.h"
45 #include "BKE_modifier.h"
46 #include "BKE_object.h"
47
48 #include "WM_api.h"
49 #include "WM_types.h"
50
51 #include "ED_mesh.h"
52
53 #include "bmesh.h"
54 #include "bmesh_tools.h"
55
56 #include "DEG_depsgraph_query.h"
57 }
58
59 using Alembic::Abc::FloatArraySample;
60 using Alembic::Abc::ICompoundProperty;
61 using Alembic::Abc::Int32ArraySample;
62 using Alembic::Abc::Int32ArraySamplePtr;
63 using Alembic::Abc::P3fArraySamplePtr;
64 using Alembic::Abc::V2fArraySample;
65 using Alembic::Abc::V3fArraySample;
66 using Alembic::Abc::C4fArraySample;
67
68 using Alembic::AbcGeom::IFaceSet;
69 using Alembic::AbcGeom::IFaceSetSchema;
70 using Alembic::AbcGeom::IObject;
71 using Alembic::AbcGeom::IPolyMesh;
72 using Alembic::AbcGeom::IPolyMeshSchema;
73 using Alembic::AbcGeom::ISampleSelector;
74 using Alembic::AbcGeom::ISubD;
75 using Alembic::AbcGeom::ISubDSchema;
76 using Alembic::AbcGeom::IV2fGeomParam;
77
78 using Alembic::AbcGeom::OArrayProperty;
79 using Alembic::AbcGeom::OBoolProperty;
80 using Alembic::AbcGeom::OC3fArrayProperty;
81 using Alembic::AbcGeom::OC3fGeomParam;
82 using Alembic::AbcGeom::OC4fGeomParam;
83 using Alembic::AbcGeom::OCompoundProperty;
84 using Alembic::AbcGeom::OFaceSet;
85 using Alembic::AbcGeom::OFaceSetSchema;
86 using Alembic::AbcGeom::OFloatGeomParam;
87 using Alembic::AbcGeom::OInt32GeomParam;
88 using Alembic::AbcGeom::ON3fArrayProperty;
89 using Alembic::AbcGeom::ON3fGeomParam;
90 using Alembic::AbcGeom::OPolyMesh;
91 using Alembic::AbcGeom::OPolyMeshSchema;
92 using Alembic::AbcGeom::OSubD;
93 using Alembic::AbcGeom::OSubDSchema;
94 using Alembic::AbcGeom::OV2fGeomParam;
95 using Alembic::AbcGeom::OV3fGeomParam;
96
97 using Alembic::AbcGeom::kFacevaryingScope;
98 using Alembic::AbcGeom::kVaryingScope;
99 using Alembic::AbcGeom::kVertexScope;
100 using Alembic::AbcGeom::kWrapExisting;
101 using Alembic::AbcGeom::UInt32ArraySample;
102 using Alembic::AbcGeom::N3fArraySamplePtr;
103 using Alembic::AbcGeom::IN3fGeomParam;
104
105 /* ************************************************************************** */
106
107 /* NOTE: Alembic's polygon winding order is clockwise, to match with Renderman. */
108
109 static void get_vertices(struct Mesh *mesh, std::vector<Imath::V3f> &points)
110 {
111         points.clear();
112         points.resize(mesh->totvert);
113
114         MVert *verts = mesh->mvert;
115
116         for (int i = 0, e = mesh->totvert; i < e; ++i) {
117                 copy_yup_from_zup(points[i].getValue(), verts[i].co);
118         }
119 }
120
121 static void get_topology(struct Mesh *mesh,
122                          std::vector<int32_t> &poly_verts,
123                          std::vector<int32_t> &loop_counts,
124                          bool &smooth_normal)
125 {
126         const int num_poly = mesh->totpoly;
127         const int num_loops = mesh->totloop;
128         MLoop *mloop = mesh->mloop;
129         MPoly *mpoly = mesh->mpoly;
130
131         poly_verts.clear();
132         loop_counts.clear();
133         poly_verts.reserve(num_loops);
134         loop_counts.reserve(num_poly);
135
136         /* NOTE: data needs to be written in the reverse order. */
137         for (int i = 0; i < num_poly; ++i) {
138                 MPoly &poly = mpoly[i];
139                 loop_counts.push_back(poly.totloop);
140
141                 smooth_normal |= ((poly.flag & ME_SMOOTH) != 0);
142
143                 MLoop *loop = mloop + poly.loopstart + (poly.totloop - 1);
144
145                 for (int j = 0; j < poly.totloop; ++j, --loop) {
146                         poly_verts.push_back(loop->v);
147                 }
148         }
149 }
150
151 static void get_creases(struct Mesh *mesh,
152                         std::vector<int32_t> &indices,
153                         std::vector<int32_t> &lengths,
154                         std::vector<float> &sharpnesses)
155 {
156         const float factor = 1.0f / 255.0f;
157
158         indices.clear();
159         lengths.clear();
160         sharpnesses.clear();
161
162         MEdge *edge = mesh->medge;
163
164         for (int i = 0, e = mesh->totedge; i < e; ++i) {
165                 const float sharpness = static_cast<float>(edge[i].crease) * factor;
166
167                 if (sharpness != 0.0f) {
168                         indices.push_back(edge[i].v1);
169                         indices.push_back(edge[i].v2);
170                         sharpnesses.push_back(sharpness);
171                 }
172         }
173
174         lengths.resize(sharpnesses.size(), 2);
175 }
176
177 static void get_vertex_normals(struct Mesh *mesh, std::vector<Imath::V3f> &normals)
178 {
179         normals.clear();
180         normals.resize(mesh->totvert);
181
182         MVert *verts = mesh->mvert;
183         float no[3];
184
185         for (int i = 0, e = mesh->totvert; i < e; ++i) {
186                 normal_short_to_float_v3(no, verts[i].no);
187                 copy_yup_from_zup(normals[i].getValue(), no);
188         }
189 }
190
191 static void get_loop_normals(struct Mesh *mesh, std::vector<Imath::V3f> &normals)
192 {
193         MPoly *mp = mesh->mpoly;
194
195         MLoop *mloop = mesh->mloop;
196         MLoop *ml = mloop;
197
198         MVert *verts = mesh->mvert;
199
200         const float (*lnors)[3] = static_cast<float(*)[3]>(CustomData_get_layer(&mesh->ldata, CD_NORMAL));
201
202         normals.clear();
203         normals.resize(mesh->totloop);
204
205         unsigned loop_index = 0;
206
207         /* NOTE: data needs to be written in the reverse order. */
208
209         if (lnors) {
210                 for (int i = 0, e = mesh->totpoly; i < e; ++i, ++mp) {
211                         ml = mloop + mp->loopstart + (mp->totloop - 1);
212
213                         for (int j = 0; j < mp->totloop; --ml, ++j, ++loop_index) {
214                                 const int index = ml->v;
215                                 copy_yup_from_zup(normals[loop_index].getValue(), lnors[index]);
216                         }
217                 }
218         }
219         else {
220                 float no[3];
221
222                 for (int i = 0, e = mesh->totpoly; i < e; ++i, ++mp) {
223                         ml = mloop + mp->loopstart + (mp->totloop - 1);
224
225                         /* Flat shaded, use common normal for all verts. */
226                         if ((mp->flag & ME_SMOOTH) == 0) {
227                                 BKE_mesh_calc_poly_normal(mp, ml - (mp->totloop - 1), verts, no);
228
229                                 for (int j = 0; j < mp->totloop; --ml, ++j, ++loop_index) {
230                                         copy_yup_from_zup(normals[loop_index].getValue(), no);
231                                 }
232                         }
233                         else {
234                                 /* Smooth shaded, use individual vert normals. */
235                                 for (int j = 0; j < mp->totloop; --ml, ++j, ++loop_index) {
236                                         normal_short_to_float_v3(no, verts[ml->v].no);
237                                         copy_yup_from_zup(normals[loop_index].getValue(), no);
238                                 }
239                         }
240                 }
241         }
242 }
243
244 /* *************** Modifiers *************** */
245
246 /* check if the mesh is a subsurf, ignoring disabled modifiers and
247  * displace if it's after subsurf. */
248 static ModifierData *get_subsurf_modifier(Scene *scene, Object *ob)
249 {
250         ModifierData *md = static_cast<ModifierData *>(ob->modifiers.last);
251
252         for (; md; md = md->prev) {
253                 if (!modifier_isEnabled(scene, md, eModifierMode_Render)) {
254                         continue;
255                 }
256
257                 if (md->type == eModifierType_Subsurf) {
258                         SubsurfModifierData *smd = reinterpret_cast<SubsurfModifierData*>(md);
259
260                         if (smd->subdivType == ME_CC_SUBSURF) {
261                                 return md;
262                         }
263                 }
264
265                 /* mesh is not a subsurf. break */
266                 if ((md->type != eModifierType_Displace) && (md->type != eModifierType_ParticleSystem)) {
267                         return NULL;
268                 }
269         }
270
271         return NULL;
272 }
273
274 static ModifierData *get_liquid_sim_modifier(Scene *scene, Object *ob)
275 {
276         ModifierData *md = modifiers_findByType(ob, eModifierType_Fluidsim);
277
278         if (md && (modifier_isEnabled(scene, md, eModifierMode_Render))) {
279                 FluidsimModifierData *fsmd = reinterpret_cast<FluidsimModifierData *>(md);
280
281                 if (fsmd->fss && fsmd->fss->type == OB_FLUIDSIM_DOMAIN) {
282                         return md;
283                 }
284         }
285
286         return NULL;
287 }
288
289 /* ************************************************************************** */
290
291 AbcMeshWriter::AbcMeshWriter(Object *ob,
292                              AbcTransformWriter *parent,
293                              uint32_t time_sampling,
294                              ExportSettings &settings)
295     : AbcObjectWriter(ob, time_sampling, settings, parent)
296 {
297         m_is_animated = isAnimated();
298         m_subsurf_mod = NULL;
299         m_is_subd = false;
300
301         /* If the object is static, use the default static time sampling. */
302         if (!m_is_animated) {
303                 time_sampling = 0;
304         }
305
306         if (!m_settings.apply_subdiv) {
307                 m_subsurf_mod = get_subsurf_modifier(m_settings.scene, m_object);
308                 m_is_subd = (m_subsurf_mod != NULL);
309         }
310
311         m_is_liquid = (get_liquid_sim_modifier(m_settings.scene, m_object) != NULL);
312
313         while (parent->alembicXform().getChildHeader(m_name)) {
314                 m_name.append("_");
315         }
316
317         if (m_settings.use_subdiv_schema && m_is_subd) {
318                 OSubD subd(parent->alembicXform(), m_name, m_time_sampling);
319                 m_subdiv_schema = subd.getSchema();
320         }
321         else {
322                 OPolyMesh mesh(parent->alembicXform(), m_name, m_time_sampling);
323                 m_mesh_schema = mesh.getSchema();
324
325                 OCompoundProperty typeContainer = m_mesh_schema.getUserProperties();
326                 OBoolProperty type(typeContainer, "meshtype");
327                 type.set(m_is_subd);
328         }
329 }
330
331 AbcMeshWriter::~AbcMeshWriter()
332 {
333         if (m_subsurf_mod) {
334                 m_subsurf_mod->mode &= ~eModifierMode_DisableTemporary;
335         }
336 }
337
338 bool AbcMeshWriter::isAnimated() const
339 {
340         /* Check if object has shape keys. */
341         Mesh *me = static_cast<Mesh *>(m_object->data);
342
343         if (me->key) {
344                 return true;
345         }
346
347         /* Test modifiers. */
348         ModifierData *md = static_cast<ModifierData *>(m_object->modifiers.first);
349
350         while (md) {
351                 if (md->type != eModifierType_Subsurf) {
352                         return true;
353                 }
354
355                 md = md->next;
356         }
357
358         return me->adt != NULL;
359 }
360
361 void AbcMeshWriter::setIsAnimated(bool is_animated)
362 {
363         m_is_animated = is_animated;
364 }
365
366 void AbcMeshWriter::do_write()
367 {
368         /* We have already stored a sample for this object. */
369         if (!m_first_frame && !m_is_animated)
370                 return;
371
372         bool needsfree;
373         struct Mesh *mesh = getFinalMesh(needsfree);
374
375         try {
376                 if (m_settings.use_subdiv_schema && m_subdiv_schema.valid()) {
377                         writeSubD(mesh);
378                 }
379                 else {
380                         writeMesh(mesh);
381                 }
382
383                 if (needsfree) BKE_id_free(NULL, mesh);
384         }
385         catch (...) {
386                 if (needsfree) BKE_id_free(NULL, mesh);
387                 throw;
388         }
389 }
390
391 void AbcMeshWriter::writeMesh(struct Mesh *mesh)
392 {
393         std::vector<Imath::V3f> points, normals;
394         std::vector<int32_t> poly_verts, loop_counts;
395
396         bool smooth_normal = false;
397
398         get_vertices(mesh, points);
399         get_topology(mesh, poly_verts, loop_counts, smooth_normal);
400
401         if (m_first_frame && m_settings.export_face_sets) {
402                 writeFaceSets(mesh, m_mesh_schema);
403         }
404
405         m_mesh_sample = OPolyMeshSchema::Sample(V3fArraySample(points),
406                                                 Int32ArraySample(poly_verts),
407                                                 Int32ArraySample(loop_counts));
408
409         UVSample sample;
410         if (m_first_frame && m_settings.export_uvs) {
411                 const char *name = get_uv_sample(sample, m_custom_data_config, &mesh->ldata);
412
413                 if (!sample.indices.empty() && !sample.uvs.empty()) {
414                         OV2fGeomParam::Sample uv_sample;
415                         uv_sample.setVals(V2fArraySample(sample.uvs));
416                         uv_sample.setIndices(UInt32ArraySample(sample.indices));
417                         uv_sample.setScope(kFacevaryingScope);
418
419                         m_mesh_schema.setUVSourceName(name);
420                         m_mesh_sample.setUVs(uv_sample);
421                 }
422
423                 write_custom_data(m_mesh_schema.getArbGeomParams(), m_custom_data_config, &mesh->ldata, CD_MLOOPUV);
424         }
425
426         if (m_settings.export_normals) {
427                 if (smooth_normal) {
428                         get_loop_normals(mesh, normals);
429                 }
430                 else {
431                         get_vertex_normals(mesh, normals);
432                 }
433
434                 ON3fGeomParam::Sample normals_sample;
435                 if (!normals.empty()) {
436                         normals_sample.setScope((smooth_normal) ? kFacevaryingScope : kVertexScope);
437                         normals_sample.setVals(V3fArraySample(normals));
438                 }
439
440                 m_mesh_sample.setNormals(normals_sample);
441         }
442
443         if (m_is_liquid) {
444                 std::vector<Imath::V3f> velocities;
445                 getVelocities(mesh, velocities);
446
447                 m_mesh_sample.setVelocities(V3fArraySample(velocities));
448         }
449
450         m_mesh_sample.setSelfBounds(bounds());
451
452         m_mesh_schema.set(m_mesh_sample);
453
454         writeArbGeoParams(mesh);
455 }
456
457 void AbcMeshWriter::writeSubD(struct Mesh *mesh)
458 {
459         std::vector<float> crease_sharpness;
460         std::vector<Imath::V3f> points;
461         std::vector<int32_t> poly_verts, loop_counts;
462         std::vector<int32_t> crease_indices, crease_lengths;
463
464         bool smooth_normal = false;
465
466         get_vertices(mesh, points);
467         get_topology(mesh, poly_verts, loop_counts, smooth_normal);
468         get_creases(mesh, crease_indices, crease_lengths, crease_sharpness);
469
470         if (m_first_frame && m_settings.export_face_sets) {
471                 writeFaceSets(mesh, m_subdiv_schema);
472         }
473
474         m_subdiv_sample = OSubDSchema::Sample(V3fArraySample(points),
475                                               Int32ArraySample(poly_verts),
476                                               Int32ArraySample(loop_counts));
477
478         UVSample sample;
479         if (m_first_frame && m_settings.export_uvs) {
480                 const char *name = get_uv_sample(sample, m_custom_data_config, &mesh->ldata);
481
482                 if (!sample.indices.empty() && !sample.uvs.empty()) {
483                         OV2fGeomParam::Sample uv_sample;
484                         uv_sample.setVals(V2fArraySample(sample.uvs));
485                         uv_sample.setIndices(UInt32ArraySample(sample.indices));
486                         uv_sample.setScope(kFacevaryingScope);
487
488                         m_subdiv_schema.setUVSourceName(name);
489                         m_subdiv_sample.setUVs(uv_sample);
490                 }
491
492                 write_custom_data(m_subdiv_schema.getArbGeomParams(), m_custom_data_config, &mesh->ldata, CD_MLOOPUV);
493         }
494
495         if (!crease_indices.empty()) {
496                 m_subdiv_sample.setCreaseIndices(Int32ArraySample(crease_indices));
497                 m_subdiv_sample.setCreaseLengths(Int32ArraySample(crease_lengths));
498                 m_subdiv_sample.setCreaseSharpnesses(FloatArraySample(crease_sharpness));
499         }
500
501         m_subdiv_sample.setSelfBounds(bounds());
502         m_subdiv_schema.set(m_subdiv_sample);
503
504         writeArbGeoParams(mesh);
505 }
506
507 template <typename Schema>
508 void AbcMeshWriter::writeFaceSets(struct Mesh *dm, Schema &schema)
509 {
510         std::map< std::string, std::vector<int32_t> > geo_groups;
511         getGeoGroups(dm, geo_groups);
512
513         std::map< std::string, std::vector<int32_t>  >::iterator it;
514         for (it = geo_groups.begin(); it != geo_groups.end(); ++it) {
515                 OFaceSet face_set = schema.createFaceSet(it->first);
516                 OFaceSetSchema::Sample samp;
517                 samp.setFaces(Int32ArraySample(it->second));
518                 face_set.getSchema().set(samp);
519         }
520 }
521
522 Mesh *AbcMeshWriter::getFinalMesh(bool &r_needsfree)
523 {
524         /* We don't want subdivided mesh data */
525         if (m_subsurf_mod) {
526                 m_subsurf_mod->mode |= eModifierMode_DisableTemporary;
527         }
528
529         Scene *scene = DEG_get_evaluated_scene(m_settings.depsgraph);
530         Object *ob_eval = DEG_get_evaluated_object(m_settings.depsgraph, m_object);
531         struct Mesh *mesh = mesh_get_eval_final(m_settings.depsgraph, scene, ob_eval, CD_MASK_MESH);
532         r_needsfree = false;
533
534         if (m_subsurf_mod) {
535                 m_subsurf_mod->mode &= ~eModifierMode_DisableTemporary;
536         }
537
538         if (m_settings.triangulate) {
539                 const bool tag_only = false;
540                 const int quad_method = m_settings.quad_method;
541                 const int ngon_method = m_settings.ngon_method;
542
543                 struct BMeshCreateParams bmcp = {false};
544                 struct BMeshFromMeshParams bmfmp = {true, false, false, 0};
545                 BMesh *bm = BKE_mesh_to_bmesh_ex(mesh, &bmcp, &bmfmp);
546
547                 BM_mesh_triangulate(bm, quad_method, ngon_method, tag_only, NULL, NULL, NULL);
548
549                 Mesh *result = BKE_mesh_from_bmesh_for_eval_nomain(bm, 0);
550                 BM_mesh_free(bm);
551
552                 mesh = result;
553                 r_needsfree = true;
554         }
555
556         m_custom_data_config.pack_uvs = m_settings.pack_uv;
557         m_custom_data_config.mpoly = mesh->mpoly;
558         m_custom_data_config.mloop = mesh->mloop;
559         m_custom_data_config.totpoly = mesh->totpoly;
560         m_custom_data_config.totloop = mesh->totloop;
561         m_custom_data_config.totvert = mesh->totvert;
562
563         return mesh;
564 }
565
566 void AbcMeshWriter::writeArbGeoParams(struct Mesh *dm)
567 {
568         if (m_is_liquid) {
569                 /* We don't need anything more for liquid meshes. */
570                 return;
571         }
572
573         if (m_first_frame && m_settings.export_vcols) {
574                 if (m_subdiv_schema.valid()) {
575                         write_custom_data(m_subdiv_schema.getArbGeomParams(), m_custom_data_config, &dm->ldata, CD_MLOOPCOL);
576                 }
577                 else {
578                         write_custom_data(m_mesh_schema.getArbGeomParams(), m_custom_data_config, &dm->ldata, CD_MLOOPCOL);
579                 }
580         }
581 }
582
583 void AbcMeshWriter::getVelocities(struct Mesh *mesh, std::vector<Imath::V3f> &vels)
584 {
585         const int totverts = mesh->totvert;
586
587         vels.clear();
588         vels.resize(totverts);
589
590         ModifierData *md = get_liquid_sim_modifier(m_settings.scene, m_object);
591         FluidsimModifierData *fmd = reinterpret_cast<FluidsimModifierData *>(md);
592         FluidsimSettings *fss = fmd->fss;
593
594         if (fss->meshVelocities) {
595                 float *mesh_vels = reinterpret_cast<float *>(fss->meshVelocities);
596
597                 for (int i = 0; i < totverts; ++i) {
598                         copy_yup_from_zup(vels[i].getValue(), mesh_vels);
599                         mesh_vels += 3;
600                 }
601         }
602         else {
603                 std::fill(vels.begin(), vels.end(), Imath::V3f(0.0f));
604         }
605 }
606
607 void AbcMeshWriter::getGeoGroups(
608         struct Mesh *mesh,
609         std::map<std::string, std::vector<int32_t> > &geo_groups)
610 {
611         const int num_poly = mesh->totpoly;
612         MPoly *polygons = mesh->mpoly;
613
614         for (int i = 0; i < num_poly; ++i) {
615                 MPoly &current_poly = polygons[i];
616                 short mnr = current_poly.mat_nr;
617
618                 Material *mat = give_current_material(m_object, mnr + 1);
619
620                 if (!mat) {
621                         continue;
622                 }
623
624                 std::string name = get_id_name(&mat->id);
625
626                 if (geo_groups.find(name) == geo_groups.end()) {
627                         std::vector<int32_t> faceArray;
628                         geo_groups[name] = faceArray;
629                 }
630
631                 geo_groups[name].push_back(i);
632         }
633
634         if (geo_groups.size() == 0) {
635                 Material *mat = give_current_material(m_object, 1);
636
637                 std::string name = (mat) ? get_id_name(&mat->id) : "default";
638
639                 std::vector<int32_t> faceArray;
640
641                 for (int i = 0, e = mesh->totface; i < e; ++i) {
642                         faceArray.push_back(i);
643                 }
644
645                 geo_groups[name] = faceArray;
646         }
647 }
648
649 /* ************************************************************************** */
650
651 /* Some helpers for mesh generation */
652 namespace utils {
653
654 static void build_mat_map(const Main *bmain, std::map<std::string, Material *> &mat_map)
655 {
656         Material *material = static_cast<Material *>(bmain->mat.first);
657
658         for (; material; material = static_cast<Material *>(material->id.next)) {
659                 mat_map[material->id.name + 2] = material;
660         }
661 }
662
663 static void assign_materials(Main *bmain, Object *ob, const std::map<std::string, int> &mat_index_map)
664 {
665         bool can_assign = true;
666         std::map<std::string, int>::const_iterator it = mat_index_map.begin();
667
668         int matcount = 0;
669         for (; it != mat_index_map.end(); ++it, ++matcount) {
670                 if (!BKE_object_material_slot_add(bmain, ob)) {
671                         can_assign = false;
672                         break;
673                 }
674         }
675
676         /* TODO(kevin): use global map? */
677         std::map<std::string, Material *> mat_map;
678         build_mat_map(bmain, mat_map);
679
680         std::map<std::string, Material *>::iterator mat_iter;
681
682         if (can_assign) {
683                 it = mat_index_map.begin();
684
685                 for (; it != mat_index_map.end(); ++it) {
686                         std::string mat_name = it->first;
687                         mat_iter = mat_map.find(mat_name.c_str());
688
689                         Material *assigned_mat;
690
691                         if (mat_iter == mat_map.end()) {
692                                 assigned_mat = BKE_material_add(bmain, mat_name.c_str());
693                                 mat_map[mat_name] = assigned_mat;
694                         }
695                         else {
696                                 assigned_mat = mat_iter->second;
697                         }
698
699                         assign_material(bmain, ob, assigned_mat, it->second, BKE_MAT_ASSIGN_OBDATA);
700                 }
701         }
702 }
703
704 }  /* namespace utils */
705
706 /* ************************************************************************** */
707
708 using Alembic::AbcGeom::UInt32ArraySamplePtr;
709 using Alembic::AbcGeom::V2fArraySamplePtr;
710
711 struct AbcMeshData {
712         Int32ArraySamplePtr face_indices;
713         Int32ArraySamplePtr face_counts;
714
715         P3fArraySamplePtr positions;
716         P3fArraySamplePtr ceil_positions;
717
718         N3fArraySamplePtr vertex_normals;
719         N3fArraySamplePtr face_normals;
720
721         V2fArraySamplePtr uvs;
722         UInt32ArraySamplePtr uvs_indices;
723 };
724
725 static void read_mverts_interp(MVert *mverts, const P3fArraySamplePtr &positions, const P3fArraySamplePtr &ceil_positions, const float weight)
726 {
727         float tmp[3];
728         for (int i = 0; i < positions->size(); ++i) {
729                 MVert &mvert = mverts[i];
730                 const Imath::V3f &floor_pos = (*positions)[i];
731                 const Imath::V3f &ceil_pos = (*ceil_positions)[i];
732
733                 interp_v3_v3v3(tmp, floor_pos.getValue(), ceil_pos.getValue(), weight);
734                 copy_zup_from_yup(mvert.co, tmp);
735
736                 mvert.bweight = 0;
737         }
738 }
739
740 static void read_mverts(CDStreamConfig &config, const AbcMeshData &mesh_data)
741 {
742         MVert *mverts = config.mvert;
743         const P3fArraySamplePtr &positions = mesh_data.positions;
744         const N3fArraySamplePtr &normals = mesh_data.vertex_normals;
745
746         if (   config.weight != 0.0f
747             && mesh_data.ceil_positions != NULL
748             && mesh_data.ceil_positions->size() == positions->size())
749         {
750                 read_mverts_interp(mverts, positions, mesh_data.ceil_positions, config.weight);
751                 return;
752         }
753
754         read_mverts(mverts, positions, normals);
755 }
756
757 void read_mverts(MVert *mverts, const P3fArraySamplePtr &positions, const N3fArraySamplePtr &normals)
758 {
759         for (int i = 0; i < positions->size(); ++i) {
760                 MVert &mvert = mverts[i];
761                 Imath::V3f pos_in = (*positions)[i];
762
763                 copy_zup_from_yup(mvert.co, pos_in.getValue());
764
765                 mvert.bweight = 0;
766
767                 if (normals) {
768                         Imath::V3f nor_in = (*normals)[i];
769
770                         short no[3];
771                         normal_float_to_short_v3(no, nor_in.getValue());
772
773                         copy_zup_from_yup(mvert.no, no);
774                 }
775         }
776 }
777
778 static void read_mpolys(CDStreamConfig &config, const AbcMeshData &mesh_data)
779 {
780         MPoly *mpolys = config.mpoly;
781         MLoop *mloops = config.mloop;
782         MLoopUV *mloopuvs = config.mloopuv;
783
784         const Int32ArraySamplePtr &face_indices = mesh_data.face_indices;
785         const Int32ArraySamplePtr &face_counts = mesh_data.face_counts;
786         const V2fArraySamplePtr &uvs = mesh_data.uvs;
787         const UInt32ArraySamplePtr &uvs_indices = mesh_data.uvs_indices;
788         const N3fArraySamplePtr &normals = mesh_data.face_normals;
789
790         const bool do_uvs = (mloopuvs && uvs && uvs_indices) && (uvs_indices->size() == face_indices->size());
791         unsigned int loop_index = 0;
792         unsigned int rev_loop_index = 0;
793         unsigned int uv_index = 0;
794
795         for (int i = 0; i < face_counts->size(); ++i) {
796                 const int face_size = (*face_counts)[i];
797
798                 MPoly &poly = mpolys[i];
799                 poly.loopstart = loop_index;
800                 poly.totloop = face_size;
801
802                 if (normals != NULL) {
803                         poly.flag |= ME_SMOOTH;
804                 }
805
806                 /* NOTE: Alembic data is stored in the reverse order. */
807                 rev_loop_index = loop_index + (face_size - 1);
808
809                 for (int f = 0; f < face_size; ++f, ++loop_index, --rev_loop_index) {
810                         MLoop &loop = mloops[rev_loop_index];
811                         loop.v = (*face_indices)[loop_index];
812
813                         if (do_uvs) {
814                                 MLoopUV &loopuv = mloopuvs[rev_loop_index];
815
816                                 uv_index = (*uvs_indices)[loop_index];
817                                 loopuv.uv[0] = (*uvs)[uv_index][0];
818                                 loopuv.uv[1] = (*uvs)[uv_index][1];
819                         }
820                 }
821         }
822 }
823
824 ABC_INLINE void read_uvs_params(CDStreamConfig &config,
825                                 AbcMeshData &abc_data,
826                                 const IV2fGeomParam &uv,
827                                 const ISampleSelector &selector)
828 {
829         if (!uv.valid()) {
830                 return;
831         }
832
833         IV2fGeomParam::Sample uvsamp;
834         uv.getIndexed(uvsamp, selector);
835
836         abc_data.uvs = uvsamp.getVals();
837         abc_data.uvs_indices = uvsamp.getIndices();
838
839         if (abc_data.uvs_indices->size() == config.totloop) {
840                 std::string name = Alembic::Abc::GetSourceName(uv.getMetaData());
841
842                 /* According to the convention, primary UVs should have had their name
843                  * set using Alembic::Abc::SetSourceName, but you can't expect everyone
844                  * to follow it! :) */
845                 if (name.empty()) {
846                         name = uv.getName();
847                 }
848
849                 void *cd_ptr = config.add_customdata_cb(config.user_data, name.c_str(), CD_MLOOPUV);
850                 config.mloopuv = static_cast<MLoopUV *>(cd_ptr);
851         }
852 }
853
854 /* TODO(kevin): normals from Alembic files are not read in anymore, this is due
855  * to the fact that there are many issues that are not so easy to solve, mainly
856  * regarding the way normals are handled in Blender (MPoly.flag vs loop normals).
857  */
858 ABC_INLINE void read_normals_params(AbcMeshData &abc_data,
859                                     const IN3fGeomParam &normals,
860                                     const ISampleSelector &selector)
861 {
862         if (!normals.valid()) {
863                 return;
864         }
865
866         IN3fGeomParam::Sample normsamp = normals.getExpandedValue(selector);
867
868         if (normals.getScope() == kFacevaryingScope) {
869                 abc_data.face_normals = normsamp.getVals();
870         }
871         else if ((normals.getScope() == kVertexScope) || (normals.getScope() == kVaryingScope)) {
872                 abc_data.vertex_normals = N3fArraySamplePtr();
873         }
874 }
875
876 static bool check_smooth_poly_flag(Mesh *mesh)
877 {
878         MPoly *mpolys = mesh->mpoly;
879
880         for (int i = 0, e = mesh->totpoly; i < e; ++i) {
881                 MPoly &poly = mpolys[i];
882
883                 if ((poly.flag & ME_SMOOTH) != 0) {
884                         return true;
885                 }
886         }
887
888         return false;
889 }
890
891 static void set_smooth_poly_flag(Mesh *mesh)
892 {
893         MPoly *mpolys = mesh->mpoly;
894
895         for (int i = 0, e = mesh->totpoly; i < e; ++i) {
896                 MPoly &poly = mpolys[i];
897                 poly.flag |= ME_SMOOTH;
898         }
899 }
900
901 static void *add_customdata_cb(void *user_data, const char *name, int data_type)
902 {
903         Mesh *mesh = static_cast<Mesh *>(user_data);
904         CustomDataType cd_data_type = static_cast<CustomDataType>(data_type);
905         void *cd_ptr;
906         CustomData *loopdata;
907         int numloops;
908
909         /* unsupported custom data type -- don't do anything. */
910         if (!ELEM(cd_data_type, CD_MLOOPUV, CD_MLOOPCOL)) {
911                 return NULL;
912         }
913
914         loopdata = &mesh->ldata;
915         cd_ptr = CustomData_get_layer_named(loopdata, cd_data_type, name);
916         if (cd_ptr != NULL) {
917                 /* layer already exists, so just return it. */
918                 return cd_ptr;
919         }
920
921         /* create a new layer, taking care to construct the hopefully-soon-to-be-removed
922          * CD_MTEXPOLY layer too, with the same name. */
923         numloops = mesh->totloop;
924         cd_ptr = CustomData_add_layer_named(loopdata, cd_data_type, CD_DEFAULT,
925                                             NULL, numloops, name);
926         return cd_ptr;
927 }
928
929 static void get_weight_and_index(CDStreamConfig &config,
930                                  Alembic::AbcCoreAbstract::TimeSamplingPtr time_sampling,
931                                  size_t samples_number)
932 {
933         Alembic::AbcGeom::index_t i0, i1;
934
935         config.weight = get_weight_and_index(config.time,
936                                              time_sampling,
937                                              samples_number,
938                                              i0,
939                                              i1);
940
941         config.index = i0;
942         config.ceil_index = i1;
943 }
944
945 static void read_mesh_sample(const std::string & iobject_full_name,
946                              ImportSettings *settings,
947                              const IPolyMeshSchema &schema,
948                              const ISampleSelector &selector,
949                              CDStreamConfig &config,
950                              bool &do_normals)
951 {
952         const IPolyMeshSchema::Sample sample = schema.getValue(selector);
953
954         AbcMeshData abc_mesh_data;
955         abc_mesh_data.face_counts = sample.getFaceCounts();
956         abc_mesh_data.face_indices = sample.getFaceIndices();
957         abc_mesh_data.positions = sample.getPositions();
958
959         read_normals_params(abc_mesh_data, schema.getNormalsParam(), selector);
960
961         do_normals = (abc_mesh_data.face_normals != NULL);
962
963         get_weight_and_index(config, schema.getTimeSampling(), schema.getNumSamples());
964
965         if (config.weight != 0.0f) {
966                 Alembic::AbcGeom::IPolyMeshSchema::Sample ceil_sample;
967                 schema.get(ceil_sample, Alembic::Abc::ISampleSelector(config.ceil_index));
968                 abc_mesh_data.ceil_positions = ceil_sample.getPositions();
969         }
970
971         if ((settings->read_flag & MOD_MESHSEQ_READ_UV) != 0) {
972                 read_uvs_params(config, abc_mesh_data, schema.getUVsParam(), selector);
973         }
974
975         if ((settings->read_flag & MOD_MESHSEQ_READ_VERT) != 0) {
976                 read_mverts(config, abc_mesh_data);
977         }
978
979         if ((settings->read_flag & MOD_MESHSEQ_READ_POLY) != 0) {
980                 read_mpolys(config, abc_mesh_data);
981         }
982
983         if ((settings->read_flag & (MOD_MESHSEQ_READ_UV | MOD_MESHSEQ_READ_COLOR)) != 0) {
984                 read_custom_data(iobject_full_name,
985                                  schema.getArbGeomParams(), config, selector);
986         }
987 }
988
989 CDStreamConfig get_config(Mesh *mesh)
990 {
991         CDStreamConfig config;
992
993         BLI_assert(mesh->mvert);
994
995         config.user_data = mesh;
996         config.mvert = mesh->mvert;
997         config.mloop = mesh->mloop;
998         config.mpoly = mesh->mpoly;
999         config.totloop = mesh->totloop;
1000         config.totpoly = mesh->totpoly;
1001         config.loopdata = &mesh->ldata;
1002         config.add_customdata_cb = add_customdata_cb;
1003
1004         return config;
1005 }
1006
1007 /* ************************************************************************** */
1008
1009 AbcMeshReader::AbcMeshReader(const IObject &object, ImportSettings &settings)
1010     : AbcObjectReader(object, settings)
1011 {
1012         m_settings->read_flag |= MOD_MESHSEQ_READ_ALL;
1013
1014         IPolyMesh ipoly_mesh(m_iobject, kWrapExisting);
1015         m_schema = ipoly_mesh.getSchema();
1016
1017         get_min_max_time(m_iobject, m_schema, m_min_time, m_max_time);
1018 }
1019
1020 bool AbcMeshReader::valid() const
1021 {
1022         return m_schema.valid();
1023 }
1024
1025 void AbcMeshReader::readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel)
1026 {
1027         Mesh *mesh = BKE_mesh_add(bmain, m_data_name.c_str());
1028
1029         m_object = BKE_object_add_only_object(bmain, OB_MESH, m_object_name.c_str());
1030         m_object->data = mesh;
1031
1032         Mesh *read_mesh = this->read_mesh(mesh, sample_sel, MOD_MESHSEQ_READ_ALL, NULL);
1033         BKE_mesh_nomain_to_mesh(read_mesh, mesh, m_object, CD_MASK_MESH, true);
1034
1035         if (m_settings->validate_meshes) {
1036                 BKE_mesh_validate(mesh, false, false);
1037         }
1038
1039         readFaceSetsSample(bmain, mesh, 0, sample_sel);
1040
1041         if (has_animations(m_schema, m_settings)) {
1042                 addCacheModifier();
1043         }
1044 }
1045
1046 bool AbcMeshReader::accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
1047                                         const Object *const ob,
1048                                         const char **err_str) const
1049 {
1050         if (!Alembic::AbcGeom::IPolyMesh::matches(alembic_header)) {
1051                 *err_str = "Object type mismatch, Alembic object path pointed to PolyMesh when importing, but not any more.";
1052                 return false;
1053         }
1054
1055         if (ob->type != OB_MESH) {
1056                 *err_str = "Object type mismatch, Alembic object path points to PolyMesh.";
1057                 return false;
1058         }
1059
1060         return true;
1061 }
1062
1063 Mesh *AbcMeshReader::read_mesh(Mesh *existing_mesh,
1064                                const ISampleSelector &sample_sel,
1065                                int read_flag,
1066                                const char **err_str)
1067 {
1068         IPolyMeshSchema::Sample sample;
1069         try {
1070                 sample = m_schema.getValue(sample_sel);
1071         }
1072         catch(Alembic::Util::Exception &ex) {
1073                 *err_str = "Error reading mesh sample; more detail on the console";
1074                 printf("Alembic: error reading mesh sample for '%s/%s' at time %f: %s\n",
1075                            m_iobject.getFullName().c_str(),
1076                            m_schema.getName().c_str(),
1077                            sample_sel.getRequestedTime(),
1078                            ex.what());
1079                 return existing_mesh;
1080         }
1081
1082         const P3fArraySamplePtr &positions = sample.getPositions();
1083         const Alembic::Abc::Int32ArraySamplePtr &face_indices = sample.getFaceIndices();
1084         const Alembic::Abc::Int32ArraySamplePtr &face_counts = sample.getFaceCounts();
1085
1086         Mesh *new_mesh = NULL;
1087
1088         /* Only read point data when streaming meshes, unless we need to create new ones. */
1089         ImportSettings settings;
1090         settings.read_flag |= read_flag;
1091
1092         bool topology_changed =  positions->size() != existing_mesh->totvert ||
1093                                  face_counts->size() != existing_mesh->totpoly ||
1094                                  face_indices->size() != existing_mesh->totloop;
1095         if (topology_changed) {
1096                 new_mesh = BKE_mesh_new_nomain_from_template(existing_mesh,
1097                                                              positions->size(),
1098                                                              0,
1099                                                              0,
1100                                                              face_indices->size(),
1101                                                              face_counts->size());
1102
1103                 settings.read_flag |= MOD_MESHSEQ_READ_ALL;
1104         }
1105         else {
1106                 /* If the face count changed (e.g. by triangulation), only read points.
1107                  * This prevents crash from T49813.
1108                  * TODO(kevin): perhaps find a better way to do this? */
1109                 if (face_counts->size() != existing_mesh->totpoly ||
1110                     face_indices->size() != existing_mesh->totloop)
1111                 {
1112                         settings.read_flag = MOD_MESHSEQ_READ_VERT;
1113
1114                         if (err_str) {
1115                                 *err_str = "Topology has changed, perhaps by triangulating the"
1116                                            " mesh. Only vertices will be read!";
1117                         }
1118                 }
1119         }
1120
1121         CDStreamConfig config = get_config(new_mesh ? new_mesh : existing_mesh);
1122         config.time = sample_sel.getRequestedTime();
1123
1124         bool do_normals = false;
1125         read_mesh_sample(m_iobject.getFullName(),
1126                          &settings, m_schema, sample_sel, config, do_normals);
1127
1128         if (new_mesh) {
1129                 /* Check if we had ME_SMOOTH flag set to restore it. */
1130                 if (!do_normals && check_smooth_poly_flag(existing_mesh)) {
1131                         set_smooth_poly_flag(new_mesh);
1132                 }
1133
1134                 BKE_mesh_calc_normals(new_mesh);
1135                 BKE_mesh_calc_edges(new_mesh, false, false);
1136
1137                 /* Here we assume that the number of materials doesn't change, i.e. that
1138                  * the material slots that were created when the object was loaded from
1139                  * Alembic are still valid now. */
1140                 size_t num_polys = new_mesh->totpoly;
1141                 if (num_polys > 0) {
1142                         std::map<std::string, int> mat_map;
1143                         assign_facesets_to_mpoly(sample_sel, 0, new_mesh->mpoly, num_polys, mat_map);
1144                 }
1145
1146                 return new_mesh;
1147         }
1148
1149         if (do_normals) {
1150                 BKE_mesh_calc_normals(existing_mesh);
1151         }
1152
1153         return existing_mesh;
1154 }
1155
1156 void AbcMeshReader::assign_facesets_to_mpoly(
1157         const ISampleSelector &sample_sel,
1158         size_t poly_start,
1159         MPoly *mpoly, int totpoly,
1160         std::map<std::string, int> & r_mat_map)
1161 {
1162         std::vector<std::string> face_sets;
1163         m_schema.getFaceSetNames(face_sets);
1164
1165         if (face_sets.empty()) {
1166                 return;
1167         }
1168
1169         int current_mat = 0;
1170
1171         for (int i = 0; i < face_sets.size(); ++i) {
1172                 const std::string &grp_name = face_sets[i];
1173
1174                 if (r_mat_map.find(grp_name) == r_mat_map.end()) {
1175                         r_mat_map[grp_name] = 1 + current_mat++;
1176                 }
1177
1178                 const int assigned_mat = r_mat_map[grp_name];
1179
1180                 const IFaceSet faceset = m_schema.getFaceSet(grp_name);
1181
1182                 if (!faceset.valid()) {
1183                         std::cerr << " Face set " << grp_name << " invalid for " << m_object_name << "\n";
1184                         continue;
1185                 }
1186
1187                 const IFaceSetSchema face_schem = faceset.getSchema();
1188                 const IFaceSetSchema::Sample face_sample = face_schem.getValue(sample_sel);
1189                 const Int32ArraySamplePtr group_faces = face_sample.getFaces();
1190                 const size_t num_group_faces = group_faces->size();
1191
1192                 for (size_t l = 0; l < num_group_faces; l++) {
1193                         size_t pos = (*group_faces)[l] + poly_start;
1194
1195                         if (pos >= totpoly) {
1196                                 std::cerr << "Faceset overflow on " << faceset.getName() << '\n';
1197                                 break;
1198                         }
1199
1200                         MPoly &poly = mpoly[pos];
1201                         poly.mat_nr = assigned_mat - 1;
1202                 }
1203         }
1204
1205 }
1206
1207 void AbcMeshReader::readFaceSetsSample(Main *bmain, Mesh *mesh, size_t poly_start,
1208                                        const ISampleSelector &sample_sel)
1209 {
1210         std::map<std::string, int> mat_map;
1211         assign_facesets_to_mpoly(sample_sel,
1212                                  poly_start, mesh->mpoly, mesh->totpoly,
1213                                  mat_map);
1214         utils::assign_materials(bmain, m_object, mat_map);
1215 }
1216
1217 /* ************************************************************************** */
1218
1219 ABC_INLINE MEdge *find_edge(MEdge *edges, int totedge, int v1, int v2)
1220 {
1221         for (int i = 0, e = totedge; i < e; ++i) {
1222                 MEdge &edge = edges[i];
1223
1224                 if (edge.v1 == v1 && edge.v2 == v2) {
1225                         return &edge;
1226                 }
1227         }
1228
1229         return NULL;
1230 }
1231
1232 static void read_subd_sample(const std::string & iobject_full_name,
1233                              ImportSettings *settings,
1234                              const ISubDSchema &schema,
1235                              const ISampleSelector &selector,
1236                              CDStreamConfig &config)
1237 {
1238         const ISubDSchema::Sample sample = schema.getValue(selector);
1239
1240         AbcMeshData abc_mesh_data;
1241         abc_mesh_data.face_counts = sample.getFaceCounts();
1242         abc_mesh_data.face_indices = sample.getFaceIndices();
1243         abc_mesh_data.vertex_normals = N3fArraySamplePtr();
1244         abc_mesh_data.face_normals = N3fArraySamplePtr();
1245         abc_mesh_data.positions = sample.getPositions();
1246
1247         get_weight_and_index(config, schema.getTimeSampling(), schema.getNumSamples());
1248
1249         if (config.weight != 0.0f) {
1250                 Alembic::AbcGeom::ISubDSchema::Sample ceil_sample;
1251                 schema.get(ceil_sample, Alembic::Abc::ISampleSelector(config.ceil_index));
1252                 abc_mesh_data.ceil_positions = ceil_sample.getPositions();
1253         }
1254
1255         if ((settings->read_flag & MOD_MESHSEQ_READ_UV) != 0) {
1256                 read_uvs_params(config, abc_mesh_data, schema.getUVsParam(), selector);
1257         }
1258
1259         if ((settings->read_flag & MOD_MESHSEQ_READ_VERT) != 0) {
1260                 read_mverts(config, abc_mesh_data);
1261         }
1262
1263         if ((settings->read_flag & MOD_MESHSEQ_READ_POLY) != 0) {
1264                 read_mpolys(config, abc_mesh_data);
1265         }
1266
1267         if ((settings->read_flag & (MOD_MESHSEQ_READ_UV | MOD_MESHSEQ_READ_COLOR)) != 0) {
1268                 read_custom_data(iobject_full_name,
1269                                  schema.getArbGeomParams(), config, selector);
1270         }
1271 }
1272
1273 /* ************************************************************************** */
1274
1275 AbcSubDReader::AbcSubDReader(const IObject &object, ImportSettings &settings)
1276     : AbcObjectReader(object, settings)
1277 {
1278         m_settings->read_flag |= MOD_MESHSEQ_READ_ALL;
1279
1280         ISubD isubd_mesh(m_iobject, kWrapExisting);
1281         m_schema = isubd_mesh.getSchema();
1282
1283         get_min_max_time(m_iobject, m_schema, m_min_time, m_max_time);
1284 }
1285
1286 bool AbcSubDReader::valid() const
1287 {
1288         return m_schema.valid();
1289 }
1290
1291 bool AbcSubDReader::accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
1292                                         const Object *const ob,
1293                                         const char **err_str) const
1294 {
1295         if (!Alembic::AbcGeom::ISubD::matches(alembic_header)) {
1296                 *err_str = "Object type mismatch, Alembic object path pointed to SubD when importing, but not any more.";
1297                 return false;
1298         }
1299
1300         if (ob->type != OB_MESH) {
1301                 *err_str = "Object type mismatch, Alembic object path points to SubD.";
1302                 return false;
1303         }
1304
1305         return true;
1306 }
1307
1308 void AbcSubDReader::readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel)
1309 {
1310         Mesh *mesh = BKE_mesh_add(bmain, m_data_name.c_str());
1311
1312         m_object = BKE_object_add_only_object(bmain, OB_MESH, m_object_name.c_str());
1313         m_object->data = mesh;
1314
1315         Mesh *read_mesh = this->read_mesh(mesh, sample_sel, MOD_MESHSEQ_READ_ALL, NULL);
1316         BKE_mesh_nomain_to_mesh(read_mesh, mesh, m_object, CD_MASK_MESH, true);
1317
1318         ISubDSchema::Sample sample;
1319         try {
1320                 sample = m_schema.getValue(sample_sel);
1321         }
1322         catch(Alembic::Util::Exception &ex) {
1323                 printf("Alembic: error reading mesh sample for '%s/%s' at time %f: %s\n",
1324                            m_iobject.getFullName().c_str(),
1325                            m_schema.getName().c_str(),
1326                            sample_sel.getRequestedTime(),
1327                            ex.what());
1328                 return;
1329         }
1330
1331         Int32ArraySamplePtr indices = sample.getCreaseIndices();
1332         Alembic::Abc::FloatArraySamplePtr sharpnesses = sample.getCreaseSharpnesses();
1333
1334         MEdge *edges = mesh->medge;
1335
1336         if (indices && sharpnesses) {
1337                 for (int i = 0, s = 0, e = indices->size(); i < e; i += 2, ++s) {
1338                         MEdge *edge = find_edge(edges, mesh->totedge, (*indices)[i], (*indices)[i + 1]);
1339
1340                         if (edge) {
1341                                 edge->crease = unit_float_to_uchar_clamp((*sharpnesses)[s]);
1342                         }
1343                 }
1344
1345                 mesh->cd_flag |= ME_CDFLAG_EDGE_CREASE;
1346         }
1347
1348         BKE_mesh_calc_normals(mesh);
1349         BKE_mesh_calc_edges(mesh, false, false);
1350
1351         if (m_settings->validate_meshes) {
1352                 BKE_mesh_validate(mesh, false, false);
1353         }
1354
1355         if (has_animations(m_schema, m_settings)) {
1356                 addCacheModifier();
1357         }
1358 }
1359
1360 Mesh *AbcSubDReader::read_mesh(Mesh *existing_mesh,
1361                                const ISampleSelector &sample_sel,
1362                                int read_flag,
1363                                const char **err_str)
1364 {
1365         ISubDSchema::Sample sample;
1366         try {
1367                 sample = m_schema.getValue(sample_sel);
1368         }
1369         catch(Alembic::Util::Exception &ex) {
1370                 *err_str = "Error reading mesh sample; more detail on the console";
1371                 printf("Alembic: error reading mesh sample for '%s/%s' at time %f: %s\n",
1372                            m_iobject.getFullName().c_str(),
1373                            m_schema.getName().c_str(),
1374                            sample_sel.getRequestedTime(),
1375                            ex.what());
1376                 return existing_mesh;
1377         }
1378
1379         const P3fArraySamplePtr &positions = sample.getPositions();
1380         const Alembic::Abc::Int32ArraySamplePtr &face_indices = sample.getFaceIndices();
1381         const Alembic::Abc::Int32ArraySamplePtr &face_counts = sample.getFaceCounts();
1382
1383         Mesh *new_mesh = NULL;
1384
1385         ImportSettings settings;
1386         settings.read_flag |= read_flag;
1387
1388         if (existing_mesh->totvert != positions->size()) {
1389                 new_mesh = BKE_mesh_new_nomain_from_template(existing_mesh,
1390                                                            positions->size(),
1391                                                            0,
1392                                                            0,
1393                                                            face_indices->size(),
1394                                                            face_counts->size());
1395
1396                 settings.read_flag |= MOD_MESHSEQ_READ_ALL;
1397         }
1398         else {
1399                 /* If the face count changed (e.g. by triangulation), only read points.
1400                  * This prevents crash from T49813.
1401                  * TODO(kevin): perhaps find a better way to do this? */
1402                 if (face_counts->size() != existing_mesh->totpoly ||
1403                     face_indices->size() != existing_mesh->totpoly)
1404                 {
1405                         settings.read_flag = MOD_MESHSEQ_READ_VERT;
1406
1407                         if (err_str) {
1408                                 *err_str = "Topology has changed, perhaps by triangulating the"
1409                                            " mesh. Only vertices will be read!";
1410                         }
1411                 }
1412         }
1413
1414         /* Only read point data when streaming meshes, unless we need to create new ones. */
1415         CDStreamConfig config = get_config(new_mesh ? new_mesh : existing_mesh);
1416         config.time = sample_sel.getRequestedTime();
1417         read_subd_sample(m_iobject.getFullName(),
1418                          &settings, m_schema, sample_sel, config);
1419
1420         if (new_mesh) {
1421                 /* Check if we had ME_SMOOTH flag set to restore it. */
1422                 if (check_smooth_poly_flag(existing_mesh)) {
1423                         set_smooth_poly_flag(new_mesh);
1424                 }
1425
1426                 BKE_mesh_calc_normals(new_mesh);
1427                 BKE_mesh_calc_edges(new_mesh, false, false);
1428
1429                 return new_mesh;
1430         }
1431
1432         return existing_mesh;
1433 }