Merge remote-tracking branch 'origin/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_modifier_types.h"
34 #include "DNA_object_fluidsim.h"
35 #include "DNA_object_types.h"
36
37 #include "BLI_math_geom.h"
38 #include "BLI_string.h"
39
40 #include "BKE_cdderivedmesh.h"
41 #include "BKE_main.h"
42 #include "BKE_material.h"
43 #include "BKE_mesh.h"
44 #include "BKE_modifier.h"
45 #include "BKE_object.h"
46
47 #include "WM_api.h"
48 #include "WM_types.h"
49
50 #include "ED_mesh.h"
51
52 #include "bmesh.h"
53 #include "bmesh_tools.h"
54 }
55
56 using Alembic::Abc::FloatArraySample;
57 using Alembic::Abc::ICompoundProperty;
58 using Alembic::Abc::Int32ArraySample;
59 using Alembic::Abc::Int32ArraySamplePtr;
60 using Alembic::Abc::P3fArraySamplePtr;
61 using Alembic::Abc::V2fArraySample;
62 using Alembic::Abc::V3fArraySample;
63 using Alembic::Abc::C4fArraySample;
64
65 using Alembic::AbcGeom::IFaceSet;
66 using Alembic::AbcGeom::IFaceSetSchema;
67 using Alembic::AbcGeom::IObject;
68 using Alembic::AbcGeom::IPolyMesh;
69 using Alembic::AbcGeom::IPolyMeshSchema;
70 using Alembic::AbcGeom::ISampleSelector;
71 using Alembic::AbcGeom::ISubD;
72 using Alembic::AbcGeom::ISubDSchema;
73 using Alembic::AbcGeom::IV2fGeomParam;
74
75 using Alembic::AbcGeom::OArrayProperty;
76 using Alembic::AbcGeom::OBoolProperty;
77 using Alembic::AbcGeom::OC3fArrayProperty;
78 using Alembic::AbcGeom::OC3fGeomParam;
79 using Alembic::AbcGeom::OC4fGeomParam;
80 using Alembic::AbcGeom::OCompoundProperty;
81 using Alembic::AbcGeom::OFaceSet;
82 using Alembic::AbcGeom::OFaceSetSchema;
83 using Alembic::AbcGeom::OFloatGeomParam;
84 using Alembic::AbcGeom::OInt32GeomParam;
85 using Alembic::AbcGeom::ON3fArrayProperty;
86 using Alembic::AbcGeom::ON3fGeomParam;
87 using Alembic::AbcGeom::OPolyMesh;
88 using Alembic::AbcGeom::OPolyMeshSchema;
89 using Alembic::AbcGeom::OSubD;
90 using Alembic::AbcGeom::OSubDSchema;
91 using Alembic::AbcGeom::OV2fGeomParam;
92 using Alembic::AbcGeom::OV3fGeomParam;
93
94 using Alembic::AbcGeom::kFacevaryingScope;
95 using Alembic::AbcGeom::kVaryingScope;
96 using Alembic::AbcGeom::kVertexScope;
97 using Alembic::AbcGeom::kWrapExisting;
98 using Alembic::AbcGeom::UInt32ArraySample;
99 using Alembic::AbcGeom::N3fArraySamplePtr;
100 using Alembic::AbcGeom::IN3fGeomParam;
101
102 /* ************************************************************************** */
103
104 /* NOTE: Alembic's polygon winding order is clockwise, to match with Renderman. */
105
106 static void get_vertices(DerivedMesh *dm, std::vector<Imath::V3f> &points)
107 {
108         points.clear();
109         points.resize(dm->getNumVerts(dm));
110
111         MVert *verts = dm->getVertArray(dm);
112
113         for (int i = 0, e = dm->getNumVerts(dm); i < e; ++i) {
114                 copy_yup_from_zup(points[i].getValue(), verts[i].co);
115         }
116 }
117
118 static void get_topology(DerivedMesh *dm,
119                          std::vector<int32_t> &poly_verts,
120                          std::vector<int32_t> &loop_counts,
121                          bool &smooth_normal)
122 {
123         const int num_poly = dm->getNumPolys(dm);
124         const int num_loops = dm->getNumLoops(dm);
125         MLoop *mloop = dm->getLoopArray(dm);
126         MPoly *mpoly = dm->getPolyArray(dm);
127
128         poly_verts.clear();
129         loop_counts.clear();
130         poly_verts.reserve(num_loops);
131         loop_counts.reserve(num_poly);
132
133         /* NOTE: data needs to be written in the reverse order. */
134         for (int i = 0; i < num_poly; ++i) {
135                 MPoly &poly = mpoly[i];
136                 loop_counts.push_back(poly.totloop);
137
138                 smooth_normal |= ((poly.flag & ME_SMOOTH) != 0);
139
140                 MLoop *loop = mloop + poly.loopstart + (poly.totloop - 1);
141
142                 for (int j = 0; j < poly.totloop; ++j, --loop) {
143                         poly_verts.push_back(loop->v);
144                 }
145         }
146 }
147
148 static void get_creases(DerivedMesh *dm,
149                         std::vector<int32_t> &indices,
150                         std::vector<int32_t> &lengths,
151                         std::vector<float> &sharpnesses)
152 {
153         const float factor = 1.0f / 255.0f;
154
155         indices.clear();
156         lengths.clear();
157         sharpnesses.clear();
158
159         MEdge *edge = dm->getEdgeArray(dm);
160
161         for (int i = 0, e = dm->getNumEdges(dm); i < e; ++i) {
162                 const float sharpness = static_cast<float>(edge[i].crease) * factor;
163
164                 if (sharpness != 0.0f) {
165                         indices.push_back(edge[i].v1);
166                         indices.push_back(edge[i].v2);
167                         sharpnesses.push_back(sharpness);
168                 }
169         }
170
171         lengths.resize(sharpnesses.size(), 2);
172 }
173
174 static void get_vertex_normals(DerivedMesh *dm, std::vector<Imath::V3f> &normals)
175 {
176         normals.clear();
177         normals.resize(dm->getNumVerts(dm));
178
179         MVert *verts = dm->getVertArray(dm);
180         float no[3];
181
182         for (int i = 0, e = dm->getNumVerts(dm); i < e; ++i) {
183                 normal_short_to_float_v3(no, verts[i].no);
184                 copy_yup_from_zup(normals[i].getValue(), no);
185         }
186 }
187
188 static void get_loop_normals(DerivedMesh *dm, std::vector<Imath::V3f> &normals)
189 {
190         MPoly *mpoly = dm->getPolyArray(dm);
191         MPoly *mp = mpoly;
192
193         MLoop *mloop = dm->getLoopArray(dm);
194         MLoop *ml = mloop;
195
196         MVert *verts = dm->getVertArray(dm);
197
198         const float (*lnors)[3] = static_cast<float(*)[3]>(dm->getLoopDataArray(dm, CD_NORMAL));
199
200         normals.clear();
201         normals.resize(dm->getNumLoops(dm));
202
203         unsigned loop_index = 0;
204
205         /* NOTE: data needs to be written in the reverse order. */
206
207         if (lnors) {
208                 for (int i = 0, e = dm->getNumPolys(dm); i < e; ++i, ++mp) {
209                         ml = mloop + mp->loopstart + (mp->totloop - 1);
210
211                         for (int j = 0; j < mp->totloop; --ml, ++j, ++loop_index) {
212                                 const int index = ml->v;
213                                 copy_yup_from_zup(normals[loop_index].getValue(), lnors[index]);
214                         }
215                 }
216         }
217         else {
218                 float no[3];
219
220                 for (int i = 0, e = dm->getNumPolys(dm); i < e; ++i, ++mp) {
221                         ml = mloop + mp->loopstart + (mp->totloop - 1);
222
223                         /* Flat shaded, use common normal for all verts. */
224                         if ((mp->flag & ME_SMOOTH) == 0) {
225                                 BKE_mesh_calc_poly_normal(mp, ml - (mp->totloop - 1), verts, no);
226
227                                 for (int j = 0; j < mp->totloop; --ml, ++j, ++loop_index) {
228                                         copy_yup_from_zup(normals[loop_index].getValue(), no);
229                                 }
230                         }
231                         else {
232                                 /* Smooth shaded, use individual vert normals. */
233                                 for (int j = 0; j < mp->totloop; --ml, ++j, ++loop_index) {
234                                         normal_short_to_float_v3(no, verts[ml->v].no);
235                                         copy_yup_from_zup(normals[loop_index].getValue(), no);
236                                 }
237                         }
238                 }
239         }
240 }
241
242 /* *************** Modifiers *************** */
243
244 /* check if the mesh is a subsurf, ignoring disabled modifiers and
245  * displace if it's after subsurf. */
246 static ModifierData *get_subsurf_modifier(Scene *scene, Object *ob)
247 {
248         ModifierData *md = static_cast<ModifierData *>(ob->modifiers.last);
249
250         for (; md; md = md->prev) {
251                 if (!modifier_isEnabled(scene, md, eModifierMode_Render)) {
252                         continue;
253                 }
254
255                 if (md->type == eModifierType_Subsurf) {
256                         SubsurfModifierData *smd = reinterpret_cast<SubsurfModifierData*>(md);
257
258                         if (smd->subdivType == ME_CC_SUBSURF) {
259                                 return md;
260                         }
261                 }
262
263                 /* mesh is not a subsurf. break */
264                 if ((md->type != eModifierType_Displace) && (md->type != eModifierType_ParticleSystem)) {
265                         return NULL;
266                 }
267         }
268
269         return NULL;
270 }
271
272 static ModifierData *get_liquid_sim_modifier(Scene *scene, Object *ob)
273 {
274         ModifierData *md = modifiers_findByType(ob, eModifierType_Fluidsim);
275
276         if (md && (modifier_isEnabled(scene, md, eModifierMode_Render))) {
277                 FluidsimModifierData *fsmd = reinterpret_cast<FluidsimModifierData *>(md);
278
279                 if (fsmd->fss && fsmd->fss->type == OB_FLUIDSIM_DOMAIN) {
280                         return md;
281                 }
282         }
283
284         return NULL;
285 }
286
287 /* ************************************************************************** */
288
289 AbcMeshWriter::AbcMeshWriter(EvaluationContext *eval_ctx,
290                              Scene *scene,
291                              Object *ob,
292                              AbcTransformWriter *parent,
293                              uint32_t time_sampling,
294                              ExportSettings &settings)
295     : AbcObjectWriter(eval_ctx, scene, 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_scene, m_object);
308                 m_is_subd = (m_subsurf_mod != NULL);
309         }
310
311         m_is_liquid = (get_liquid_sim_modifier(m_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         DerivedMesh *dm = getFinalMesh();
373
374         try {
375                 if (m_settings.use_subdiv_schema && m_subdiv_schema.valid()) {
376                         writeSubD(dm);
377                 }
378                 else {
379                         writeMesh(dm);
380                 }
381
382                 freeMesh(dm);
383         }
384         catch (...) {
385                 freeMesh(dm);
386                 throw;
387         }
388 }
389
390 void AbcMeshWriter::writeMesh(DerivedMesh *dm)
391 {
392         std::vector<Imath::V3f> points, normals;
393         std::vector<int32_t> poly_verts, loop_counts;
394
395         bool smooth_normal = false;
396
397         get_vertices(dm, points);
398         get_topology(dm, poly_verts, loop_counts, smooth_normal);
399
400         if (m_first_frame && m_settings.export_face_sets) {
401                 writeFaceSets(dm, m_mesh_schema);
402         }
403
404         m_mesh_sample = OPolyMeshSchema::Sample(V3fArraySample(points),
405                                                 Int32ArraySample(poly_verts),
406                                                 Int32ArraySample(loop_counts));
407
408         UVSample sample;
409         if (m_first_frame && m_settings.export_uvs) {
410                 const char *name = get_uv_sample(sample, m_custom_data_config, &dm->loopData);
411
412                 if (!sample.indices.empty() && !sample.uvs.empty()) {
413                         OV2fGeomParam::Sample uv_sample;
414                         uv_sample.setVals(V2fArraySample(sample.uvs));
415                         uv_sample.setIndices(UInt32ArraySample(sample.indices));
416                         uv_sample.setScope(kFacevaryingScope);
417
418                         m_mesh_schema.setUVSourceName(name);
419                         m_mesh_sample.setUVs(uv_sample);
420                 }
421
422                 write_custom_data(m_mesh_schema.getArbGeomParams(), m_custom_data_config, &dm->loopData, CD_MLOOPUV);
423         }
424
425         if (m_settings.export_normals) {
426                 if (smooth_normal) {
427                         get_loop_normals(dm, normals);
428                 }
429                 else {
430                         get_vertex_normals(dm, normals);
431                 }
432
433                 ON3fGeomParam::Sample normals_sample;
434                 if (!normals.empty()) {
435                         normals_sample.setScope((smooth_normal) ? kFacevaryingScope : kVertexScope);
436                         normals_sample.setVals(V3fArraySample(normals));
437                 }
438
439                 m_mesh_sample.setNormals(normals_sample);
440         }
441
442         if (m_is_liquid) {
443                 std::vector<Imath::V3f> velocities;
444                 getVelocities(dm, velocities);
445
446                 m_mesh_sample.setVelocities(V3fArraySample(velocities));
447         }
448
449         m_mesh_sample.setSelfBounds(bounds());
450
451         m_mesh_schema.set(m_mesh_sample);
452
453         writeArbGeoParams(dm);
454 }
455
456 void AbcMeshWriter::writeSubD(DerivedMesh *dm)
457 {
458         std::vector<float> crease_sharpness;
459         std::vector<Imath::V3f> points;
460         std::vector<int32_t> poly_verts, loop_counts;
461         std::vector<int32_t> crease_indices, crease_lengths;
462
463         bool smooth_normal = false;
464
465         get_vertices(dm, points);
466         get_topology(dm, poly_verts, loop_counts, smooth_normal);
467         get_creases(dm, crease_indices, crease_lengths, crease_sharpness);
468
469         if (m_first_frame && m_settings.export_face_sets) {
470                 writeFaceSets(dm, m_subdiv_schema);
471         }
472
473         m_subdiv_sample = OSubDSchema::Sample(V3fArraySample(points),
474                                               Int32ArraySample(poly_verts),
475                                               Int32ArraySample(loop_counts));
476
477         UVSample sample;
478         if (m_first_frame && m_settings.export_uvs) {
479                 const char *name = get_uv_sample(sample, m_custom_data_config, &dm->loopData);
480
481                 if (!sample.indices.empty() && !sample.uvs.empty()) {
482                         OV2fGeomParam::Sample uv_sample;
483                         uv_sample.setVals(V2fArraySample(sample.uvs));
484                         uv_sample.setIndices(UInt32ArraySample(sample.indices));
485                         uv_sample.setScope(kFacevaryingScope);
486
487                         m_subdiv_schema.setUVSourceName(name);
488                         m_subdiv_sample.setUVs(uv_sample);
489                 }
490
491                 write_custom_data(m_subdiv_schema.getArbGeomParams(), m_custom_data_config, &dm->loopData, CD_MLOOPUV);
492         }
493
494         if (!crease_indices.empty()) {
495                 m_subdiv_sample.setCreaseIndices(Int32ArraySample(crease_indices));
496                 m_subdiv_sample.setCreaseLengths(Int32ArraySample(crease_lengths));
497                 m_subdiv_sample.setCreaseSharpnesses(FloatArraySample(crease_sharpness));
498         }
499
500         m_subdiv_sample.setSelfBounds(bounds());
501         m_subdiv_schema.set(m_subdiv_sample);
502
503         writeArbGeoParams(dm);
504 }
505
506 template <typename Schema>
507 void AbcMeshWriter::writeFaceSets(DerivedMesh *dm, Schema &schema)
508 {
509         std::map< std::string, std::vector<int32_t> > geo_groups;
510         getGeoGroups(dm, geo_groups);
511
512         std::map< std::string, std::vector<int32_t>  >::iterator it;
513         for (it = geo_groups.begin(); it != geo_groups.end(); ++it) {
514                 OFaceSet face_set = schema.createFaceSet(it->first);
515                 OFaceSetSchema::Sample samp;
516                 samp.setFaces(Int32ArraySample(it->second));
517                 face_set.getSchema().set(samp);
518         }
519 }
520
521 DerivedMesh *AbcMeshWriter::getFinalMesh()
522 {
523         /* We don't want subdivided mesh data */
524         if (m_subsurf_mod) {
525                 m_subsurf_mod->mode |= eModifierMode_DisableTemporary;
526         }
527
528         DerivedMesh *dm = mesh_create_derived_render(m_eval_ctx, m_scene, m_object, CD_MASK_MESH);
529
530         if (m_subsurf_mod) {
531                 m_subsurf_mod->mode &= ~eModifierMode_DisableTemporary;
532         }
533
534         if (m_settings.triangulate) {
535                 const bool tag_only = false;
536                 const int quad_method = m_settings.quad_method;
537                 const int ngon_method = m_settings.ngon_method;
538
539                 BMesh *bm = DM_to_bmesh(dm, true);
540
541                 BM_mesh_triangulate(bm, quad_method, ngon_method, tag_only, NULL, NULL, NULL);
542
543                 DerivedMesh *result = CDDM_from_bmesh(bm, false);
544                 BM_mesh_free(bm);
545
546                 freeMesh(dm);
547
548                 dm = result;
549         }
550
551         m_custom_data_config.pack_uvs = m_settings.pack_uv;
552         m_custom_data_config.mpoly = dm->getPolyArray(dm);
553         m_custom_data_config.mloop = dm->getLoopArray(dm);
554         m_custom_data_config.totpoly = dm->getNumPolys(dm);
555         m_custom_data_config.totloop = dm->getNumLoops(dm);
556         m_custom_data_config.totvert = dm->getNumVerts(dm);
557
558         return dm;
559 }
560
561 void AbcMeshWriter::freeMesh(DerivedMesh *dm)
562 {
563         dm->release(dm);
564 }
565
566 void AbcMeshWriter::writeArbGeoParams(DerivedMesh *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->loopData, CD_MLOOPCOL);
576                 }
577                 else {
578                         write_custom_data(m_mesh_schema.getArbGeomParams(), m_custom_data_config, &dm->loopData, CD_MLOOPCOL);
579                 }
580         }
581 }
582
583 void AbcMeshWriter::getVelocities(DerivedMesh *dm, std::vector<Imath::V3f> &vels)
584 {
585         const int totverts = dm->getNumVerts(dm);
586
587         vels.clear();
588         vels.resize(totverts);
589
590         ModifierData *md = get_liquid_sim_modifier(m_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         DerivedMesh *dm,
609         std::map<std::string, std::vector<int32_t> > &geo_groups)
610 {
611         const int num_poly = dm->getNumPolys(dm);
612         MPoly *polygons = dm->getPolyArray(dm);
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 = dm->getNumTessFaces(dm); 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(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(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(DerivedMesh *dm)
877 {
878         MPoly *mpolys = dm->getPolyArray(dm);
879
880         for (int i = 0, e = dm->getNumPolys(dm); 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(DerivedMesh *dm)
892 {
893         MPoly *mpolys = dm->getPolyArray(dm);
894
895         for (int i = 0, e = dm->getNumPolys(dm); 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         DerivedMesh *dm = static_cast<DerivedMesh *>(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 = dm->getLoopDataLayout(dm);
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 = dm->getNumLoops(dm);
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(DerivedMesh *dm)
990 {
991         CDStreamConfig config;
992
993         config.user_data = dm;
994         config.mvert = dm->getVertArray(dm);
995         config.mloop = dm->getLoopArray(dm);
996         config.mpoly = dm->getPolyArray(dm);
997         config.totloop = dm->getNumLoops(dm);
998         config.totpoly = dm->getNumPolys(dm);
999         config.loopdata = dm->getLoopDataLayout(dm);
1000         config.add_customdata_cb = add_customdata_cb;
1001
1002         return config;
1003 }
1004
1005 /* ************************************************************************** */
1006
1007 AbcMeshReader::AbcMeshReader(const IObject &object, ImportSettings &settings)
1008     : AbcObjectReader(object, settings)
1009 {
1010         m_settings->read_flag |= MOD_MESHSEQ_READ_ALL;
1011
1012         IPolyMesh ipoly_mesh(m_iobject, kWrapExisting);
1013         m_schema = ipoly_mesh.getSchema();
1014
1015         get_min_max_time(m_iobject, m_schema, m_min_time, m_max_time);
1016 }
1017
1018 bool AbcMeshReader::valid() const
1019 {
1020         return m_schema.valid();
1021 }
1022
1023 void AbcMeshReader::readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel)
1024 {
1025         Mesh *mesh = BKE_mesh_add(bmain, m_data_name.c_str());
1026
1027         m_object = BKE_object_add_only_object(bmain, OB_MESH, m_object_name.c_str());
1028         m_object->data = mesh;
1029
1030         DerivedMesh *dm = CDDM_from_mesh(mesh);
1031         DerivedMesh *ndm = this->read_derivedmesh(dm, sample_sel, MOD_MESHSEQ_READ_ALL, NULL);
1032
1033         if (ndm != dm) {
1034                 dm->release(dm);
1035         }
1036
1037         DM_to_mesh(ndm, mesh, m_object, CD_MASK_MESH, true);
1038
1039         if (m_settings->validate_meshes) {
1040                 BKE_mesh_validate(mesh, false, false);
1041         }
1042
1043         readFaceSetsSample(bmain, mesh, 0, sample_sel);
1044
1045         if (has_animations(m_schema, m_settings)) {
1046                 addCacheModifier();
1047         }
1048 }
1049
1050 bool AbcMeshReader::accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
1051                                         const Object *const ob,
1052                                         const char **err_str) const
1053 {
1054         if (!Alembic::AbcGeom::IPolyMesh::matches(alembic_header)) {
1055                 *err_str = "Object type mismatch, Alembic object path pointed to PolyMesh when importing, but not any more.";
1056                 return false;
1057         }
1058
1059         if (ob->type != OB_MESH) {
1060                 *err_str = "Object type mismatch, Alembic object path points to PolyMesh.";
1061                 return false;
1062         }
1063
1064         return true;
1065 }
1066
1067 DerivedMesh *AbcMeshReader::read_derivedmesh(DerivedMesh *dm,
1068                                              const ISampleSelector &sample_sel,
1069                                              int read_flag,
1070                                              const char **err_str)
1071 {
1072         const IPolyMeshSchema::Sample sample = m_schema.getValue(sample_sel);
1073
1074         const P3fArraySamplePtr &positions = sample.getPositions();
1075         const Alembic::Abc::Int32ArraySamplePtr &face_indices = sample.getFaceIndices();
1076         const Alembic::Abc::Int32ArraySamplePtr &face_counts = sample.getFaceCounts();
1077
1078         DerivedMesh *new_dm = NULL;
1079
1080         /* Only read point data when streaming meshes, unless we need to create new ones. */
1081         ImportSettings settings;
1082         settings.read_flag |= read_flag;
1083
1084         bool topology_changed =  positions->size() != dm->getNumVerts(dm) ||
1085                                  face_counts->size() != dm->getNumPolys(dm) ||
1086                                  face_indices->size() != dm->getNumLoops(dm);
1087         if (topology_changed) {
1088                 new_dm = CDDM_from_template(dm,
1089                                             positions->size(),
1090                                             0,
1091                                             0,
1092                                             face_indices->size(),
1093                                             face_counts->size());
1094
1095                 settings.read_flag |= MOD_MESHSEQ_READ_ALL;
1096         }
1097         else {
1098                 /* If the face count changed (e.g. by triangulation), only read points.
1099                  * This prevents crash from T49813.
1100                  * TODO(kevin): perhaps find a better way to do this? */
1101                 if (face_counts->size() != dm->getNumPolys(dm) ||
1102                     face_indices->size() != dm->getNumLoops(dm))
1103                 {
1104                         settings.read_flag = MOD_MESHSEQ_READ_VERT;
1105
1106                         if (err_str) {
1107                                 *err_str = "Topology has changed, perhaps by triangulating the"
1108                                            " mesh. Only vertices will be read!";
1109                         }
1110                 }
1111         }
1112
1113         CDStreamConfig config = get_config(new_dm ? new_dm : dm);
1114         config.time = sample_sel.getRequestedTime();
1115
1116         bool do_normals = false;
1117         read_mesh_sample(m_iobject.getFullName(),
1118                          &settings, m_schema, sample_sel, config, do_normals);
1119
1120         if (new_dm) {
1121                 /* Check if we had ME_SMOOTH flag set to restore it. */
1122                 if (!do_normals && check_smooth_poly_flag(dm)) {
1123                         set_smooth_poly_flag(new_dm);
1124                 }
1125
1126                 CDDM_calc_normals(new_dm);
1127                 CDDM_calc_edges(new_dm);
1128
1129                 /* Here we assume that the number of materials doesn't change, i.e. that
1130                  * the material slots that were created when the object was loaded from
1131                  * Alembic are still valid now. */
1132                 size_t num_polys = new_dm->getNumPolys(new_dm);
1133                 if (num_polys > 0) {
1134                         MPoly *dmpolies = new_dm->getPolyArray(new_dm);
1135                         std::map<std::string, int> mat_map;
1136                         assign_facesets_to_mpoly(sample_sel, 0, dmpolies, num_polys, mat_map);
1137                 }
1138
1139                 return new_dm;
1140         }
1141
1142         if (do_normals) {
1143                 CDDM_calc_normals(dm);
1144         }
1145
1146         return dm;
1147 }
1148
1149 void AbcMeshReader::assign_facesets_to_mpoly(
1150         const ISampleSelector &sample_sel,
1151         size_t poly_start,
1152         MPoly *mpoly, int totpoly,
1153         std::map<std::string, int> & r_mat_map)
1154 {
1155         std::vector<std::string> face_sets;
1156         m_schema.getFaceSetNames(face_sets);
1157
1158         if (face_sets.empty()) {
1159                 return;
1160         }
1161
1162         int current_mat = 0;
1163
1164         for (int i = 0; i < face_sets.size(); ++i) {
1165                 const std::string &grp_name = face_sets[i];
1166
1167                 if (r_mat_map.find(grp_name) == r_mat_map.end()) {
1168                         r_mat_map[grp_name] = 1 + current_mat++;
1169                 }
1170
1171                 const int assigned_mat = r_mat_map[grp_name];
1172
1173                 const IFaceSet faceset = m_schema.getFaceSet(grp_name);
1174
1175                 if (!faceset.valid()) {
1176                         std::cerr << " Face set " << grp_name << " invalid for " << m_object_name << "\n";
1177                         continue;
1178                 }
1179
1180                 const IFaceSetSchema face_schem = faceset.getSchema();
1181                 const IFaceSetSchema::Sample face_sample = face_schem.getValue(sample_sel);
1182                 const Int32ArraySamplePtr group_faces = face_sample.getFaces();
1183                 const size_t num_group_faces = group_faces->size();
1184
1185                 for (size_t l = 0; l < num_group_faces; l++) {
1186                         size_t pos = (*group_faces)[l] + poly_start;
1187
1188                         if (pos >= totpoly) {
1189                                 std::cerr << "Faceset overflow on " << faceset.getName() << '\n';
1190                                 break;
1191                         }
1192
1193                         MPoly &poly = mpoly[pos];
1194                         poly.mat_nr = assigned_mat - 1;
1195                 }
1196         }
1197
1198 }
1199
1200 void AbcMeshReader::readFaceSetsSample(Main *bmain, Mesh *mesh, size_t poly_start,
1201                                        const ISampleSelector &sample_sel)
1202 {
1203         std::map<std::string, int> mat_map;
1204         assign_facesets_to_mpoly(sample_sel,
1205                                  poly_start, mesh->mpoly, mesh->totpoly,
1206                                  mat_map);
1207         utils::assign_materials(bmain, m_object, mat_map);
1208 }
1209
1210 /* ************************************************************************** */
1211
1212 ABC_INLINE MEdge *find_edge(MEdge *edges, int totedge, int v1, int v2)
1213 {
1214         for (int i = 0, e = totedge; i < e; ++i) {
1215                 MEdge &edge = edges[i];
1216
1217                 if (edge.v1 == v1 && edge.v2 == v2) {
1218                         return &edge;
1219                 }
1220         }
1221
1222         return NULL;
1223 }
1224
1225 static void read_subd_sample(const std::string & iobject_full_name,
1226                              ImportSettings *settings,
1227                              const ISubDSchema &schema,
1228                              const ISampleSelector &selector,
1229                              CDStreamConfig &config)
1230 {
1231         const ISubDSchema::Sample sample = schema.getValue(selector);
1232
1233         AbcMeshData abc_mesh_data;
1234         abc_mesh_data.face_counts = sample.getFaceCounts();
1235         abc_mesh_data.face_indices = sample.getFaceIndices();
1236         abc_mesh_data.vertex_normals = N3fArraySamplePtr();
1237         abc_mesh_data.face_normals = N3fArraySamplePtr();
1238         abc_mesh_data.positions = sample.getPositions();
1239
1240         get_weight_and_index(config, schema.getTimeSampling(), schema.getNumSamples());
1241
1242         if (config.weight != 0.0f) {
1243                 Alembic::AbcGeom::ISubDSchema::Sample ceil_sample;
1244                 schema.get(ceil_sample, Alembic::Abc::ISampleSelector(config.ceil_index));
1245                 abc_mesh_data.ceil_positions = ceil_sample.getPositions();
1246         }
1247
1248         if ((settings->read_flag & MOD_MESHSEQ_READ_UV) != 0) {
1249                 read_uvs_params(config, abc_mesh_data, schema.getUVsParam(), selector);
1250         }
1251
1252         if ((settings->read_flag & MOD_MESHSEQ_READ_VERT) != 0) {
1253                 read_mverts(config, abc_mesh_data);
1254         }
1255
1256         if ((settings->read_flag & MOD_MESHSEQ_READ_POLY) != 0) {
1257                 read_mpolys(config, abc_mesh_data);
1258         }
1259
1260         if ((settings->read_flag & (MOD_MESHSEQ_READ_UV | MOD_MESHSEQ_READ_COLOR)) != 0) {
1261                 read_custom_data(iobject_full_name,
1262                                  schema.getArbGeomParams(), config, selector);
1263         }
1264 }
1265
1266 /* ************************************************************************** */
1267
1268 AbcSubDReader::AbcSubDReader(const IObject &object, ImportSettings &settings)
1269     : AbcObjectReader(object, settings)
1270 {
1271         m_settings->read_flag |= MOD_MESHSEQ_READ_ALL;
1272
1273         ISubD isubd_mesh(m_iobject, kWrapExisting);
1274         m_schema = isubd_mesh.getSchema();
1275
1276         get_min_max_time(m_iobject, m_schema, m_min_time, m_max_time);
1277 }
1278
1279 bool AbcSubDReader::valid() const
1280 {
1281         return m_schema.valid();
1282 }
1283
1284 bool AbcSubDReader::accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
1285                                         const Object *const ob,
1286                                         const char **err_str) const
1287 {
1288         if (!Alembic::AbcGeom::ISubD::matches(alembic_header)) {
1289                 *err_str = "Object type mismatch, Alembic object path pointed to SubD when importing, but not any more.";
1290                 return false;
1291         }
1292
1293         if (ob->type != OB_MESH) {
1294                 *err_str = "Object type mismatch, Alembic object path points to SubD.";
1295                 return false;
1296         }
1297
1298         return true;
1299 }
1300
1301 void AbcSubDReader::readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel)
1302 {
1303         Mesh *mesh = BKE_mesh_add(bmain, m_data_name.c_str());
1304
1305         m_object = BKE_object_add_only_object(bmain, OB_MESH, m_object_name.c_str());
1306         m_object->data = mesh;
1307
1308         DerivedMesh *dm = CDDM_from_mesh(mesh);
1309         DerivedMesh *ndm = this->read_derivedmesh(dm, sample_sel, MOD_MESHSEQ_READ_ALL, NULL);
1310
1311         if (ndm != dm) {
1312                 dm->release(dm);
1313         }
1314
1315         DM_to_mesh(ndm, mesh, m_object, CD_MASK_MESH, true);
1316
1317         const ISubDSchema::Sample sample = m_schema.getValue(sample_sel);
1318         Int32ArraySamplePtr indices = sample.getCreaseIndices();
1319         Alembic::Abc::FloatArraySamplePtr sharpnesses = sample.getCreaseSharpnesses();
1320
1321         MEdge *edges = mesh->medge;
1322
1323         if (indices && sharpnesses) {
1324                 for (int i = 0, s = 0, e = indices->size(); i < e; i += 2, ++s) {
1325                         MEdge *edge = find_edge(edges, mesh->totedge, (*indices)[i], (*indices)[i + 1]);
1326
1327                         if (edge) {
1328                                 edge->crease = FTOCHAR((*sharpnesses)[s]);
1329                         }
1330                 }
1331
1332                 mesh->cd_flag |= ME_CDFLAG_EDGE_CREASE;
1333         }
1334
1335         BKE_mesh_calc_normals(mesh);
1336         BKE_mesh_calc_edges(mesh, false, false);
1337
1338         if (m_settings->validate_meshes) {
1339                 BKE_mesh_validate(mesh, false, false);
1340         }
1341
1342         if (has_animations(m_schema, m_settings)) {
1343                 addCacheModifier();
1344         }
1345 }
1346
1347 DerivedMesh *AbcSubDReader::read_derivedmesh(DerivedMesh *dm,
1348                                              const ISampleSelector &sample_sel,
1349                                              int read_flag,
1350                                              const char **err_str)
1351 {
1352         const ISubDSchema::Sample sample = m_schema.getValue(sample_sel);
1353
1354         const P3fArraySamplePtr &positions = sample.getPositions();
1355         const Alembic::Abc::Int32ArraySamplePtr &face_indices = sample.getFaceIndices();
1356         const Alembic::Abc::Int32ArraySamplePtr &face_counts = sample.getFaceCounts();
1357
1358         DerivedMesh *new_dm = NULL;
1359
1360         ImportSettings settings;
1361         settings.read_flag |= read_flag;
1362
1363         if (dm->getNumVerts(dm) != positions->size()) {
1364                 new_dm = CDDM_from_template(dm,
1365                                             positions->size(),
1366                                             0,
1367                                             0,
1368                                             face_indices->size(),
1369                                             face_counts->size());
1370
1371                 settings.read_flag |= MOD_MESHSEQ_READ_ALL;
1372         }
1373         else {
1374                 /* If the face count changed (e.g. by triangulation), only read points.
1375                  * This prevents crash from T49813.
1376                  * TODO(kevin): perhaps find a better way to do this? */
1377                 if (face_counts->size() != dm->getNumPolys(dm) ||
1378                     face_indices->size() != dm->getNumLoops(dm))
1379                 {
1380                         settings.read_flag = MOD_MESHSEQ_READ_VERT;
1381
1382                         if (err_str) {
1383                                 *err_str = "Topology has changed, perhaps by triangulating the"
1384                                            " mesh. Only vertices will be read!";
1385                         }
1386                 }
1387         }
1388
1389         /* Only read point data when streaming meshes, unless we need to create new ones. */
1390         CDStreamConfig config = get_config(new_dm ? new_dm : dm);
1391         config.time = sample_sel.getRequestedTime();
1392         read_subd_sample(m_iobject.getFullName(),
1393                          &settings, m_schema, sample_sel, config);
1394
1395         if (new_dm) {
1396                 /* Check if we had ME_SMOOTH flag set to restore it. */
1397                 if (check_smooth_poly_flag(dm)) {
1398                         set_smooth_poly_flag(new_dm);
1399                 }
1400
1401                 CDDM_calc_normals(new_dm);
1402                 CDDM_calc_edges(new_dm);
1403
1404                 return new_dm;
1405         }
1406
1407         return dm;
1408 }