Alembic import: port DerivedMesh → Mesh
[blender.git] / source / blender / alembic / intern / abc_curves.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  * The Original Code is Copyright (C) 2016 Kévin Dietrich.
19  * All rights reserved.
20  *
21  * ***** END GPL LICENSE BLOCK *****
22  *
23  */
24
25 #include "abc_curves.h"
26
27 #include <cstdio>
28
29 #include "abc_transform.h"
30 #include "abc_util.h"
31
32 extern "C" {
33 #include "MEM_guardedalloc.h"
34
35 #include "DNA_curve_types.h"
36 #include "DNA_object_types.h"
37
38 #include "BLI_listbase.h"
39
40 #include "BKE_curve.h"
41 #include "BKE_mesh.h"
42 #include "BKE_object.h"
43
44 #include "ED_curve.h"
45 }
46
47 using Alembic::Abc::IInt32ArrayProperty;
48 using Alembic::Abc::Int32ArraySamplePtr;
49 using Alembic::Abc::FloatArraySamplePtr;
50 using Alembic::Abc::P3fArraySamplePtr;
51 using Alembic::Abc::UcharArraySamplePtr;
52 using Alembic::Abc::PropertyHeader;
53
54 using Alembic::AbcGeom::ICompoundProperty;
55 using Alembic::AbcGeom::ICurves;
56 using Alembic::AbcGeom::ICurvesSchema;
57 using Alembic::AbcGeom::IFloatGeomParam;
58 using Alembic::AbcGeom::IInt16Property;
59 using Alembic::AbcGeom::ISampleSelector;
60 using Alembic::AbcGeom::kWrapExisting;
61 using Alembic::AbcGeom::CurvePeriodicity;
62
63 using Alembic::AbcGeom::OCompoundProperty;
64 using Alembic::AbcGeom::OCurves;
65 using Alembic::AbcGeom::OCurvesSchema;
66 using Alembic::AbcGeom::OInt16Property;
67 using Alembic::AbcGeom::ON3fGeomParam;
68 using Alembic::AbcGeom::OV2fGeomParam;
69
70 #define ABC_CURVE_RESOLUTION_U_PROPNAME "blender:resolution"
71
72 /* ************************************************************************** */
73
74 AbcCurveWriter::AbcCurveWriter(Depsgraph *depsgraph,
75                                Scene *scene,
76                                Object *ob,
77                                AbcTransformWriter *parent,
78                                uint32_t time_sampling,
79                                ExportSettings &settings)
80     : AbcObjectWriter(depsgraph, scene, ob, time_sampling, settings, parent)
81 {
82         OCurves curves(parent->alembicXform(), m_name, m_time_sampling);
83         m_schema = curves.getSchema();
84
85         Curve *cu = static_cast<Curve *>(m_object->data);
86         OCompoundProperty user_props = m_schema.getUserProperties();
87         OInt16Property user_prop_resolu(user_props, ABC_CURVE_RESOLUTION_U_PROPNAME);
88         user_prop_resolu.set(cu->resolu);
89 }
90
91 void AbcCurveWriter::do_write()
92 {
93         Curve *curve = static_cast<Curve *>(m_object->data);
94
95         std::vector<Imath::V3f> verts;
96         std::vector<int32_t> vert_counts;
97         std::vector<float> widths;
98         std::vector<float> weights;
99         std::vector<float> knots;
100         std::vector<uint8_t> orders;
101         Imath::V3f temp_vert;
102
103         Alembic::AbcGeom::BasisType curve_basis;
104         Alembic::AbcGeom::CurveType curve_type;
105         Alembic::AbcGeom::CurvePeriodicity periodicity;
106
107         Nurb *nurbs = static_cast<Nurb *>(curve->nurb.first);
108         for (; nurbs; nurbs = nurbs->next) {
109                 if (nurbs->bp) {
110                         curve_basis = Alembic::AbcGeom::kNoBasis;
111                         curve_type = Alembic::AbcGeom::kVariableOrder;
112
113                         const int totpoint = nurbs->pntsu * nurbs->pntsv;
114
115                         const BPoint *point = nurbs->bp;
116
117                         for (int i = 0; i < totpoint; ++i, ++point) {
118                                 copy_yup_from_zup(temp_vert.getValue(), point->vec);
119                                 verts.push_back(temp_vert);
120                                 weights.push_back(point->vec[3]);
121                                 widths.push_back(point->radius);
122                         }
123                 }
124                 else if (nurbs->bezt) {
125                         curve_basis = Alembic::AbcGeom::kBezierBasis;
126                         curve_type = Alembic::AbcGeom::kCubic;
127
128                         const int totpoint = nurbs->pntsu;
129
130                         const BezTriple *bezier = nurbs->bezt;
131
132                         /* TODO(kevin): store info about handles, Alembic doesn't have this. */
133                         for (int i = 0; i < totpoint; ++i, ++bezier) {
134                                 copy_yup_from_zup(temp_vert.getValue(), bezier->vec[1]);
135                                 verts.push_back(temp_vert);
136                                 widths.push_back(bezier->radius);
137                         }
138                 }
139
140                 if ((nurbs->flagu & CU_NURB_ENDPOINT) != 0) {
141                         periodicity = Alembic::AbcGeom::kNonPeriodic;
142                 }
143                 else if ((nurbs->flagu & CU_NURB_CYCLIC) != 0) {
144                         periodicity = Alembic::AbcGeom::kPeriodic;
145
146                         /* Duplicate the start points to indicate that the curve is actually
147                          * cyclic since other software need those.
148                          */
149
150                         for (int i = 0; i < nurbs->orderu; ++i) {
151                                 verts.push_back(verts[i]);
152                         }
153                 }
154
155                 if (nurbs->knotsu != NULL) {
156                         const size_t num_knots = KNOTSU(nurbs);
157
158                         /* Add an extra knot at the beggining and end of the array since most apps
159                          * require/expect them. */
160                         knots.resize(num_knots + 2);
161
162                         for (int i = 0; i < num_knots; ++i) {
163                                 knots[i + 1] = nurbs->knotsu[i];
164                         }
165
166                         if ((nurbs->flagu & CU_NURB_CYCLIC) != 0) {
167                                 knots[0] = nurbs->knotsu[0];
168                                 knots[num_knots - 1] = nurbs->knotsu[num_knots - 1];
169                         }
170                         else {
171                                 knots[0] = (2.0f * nurbs->knotsu[0] - nurbs->knotsu[1]);
172                                 knots[num_knots - 1] = (2.0f * nurbs->knotsu[num_knots - 1] - nurbs->knotsu[num_knots - 2]);
173                         }
174                 }
175
176                 orders.push_back(nurbs->orderu);
177                 vert_counts.push_back(verts.size());
178         }
179
180         Alembic::AbcGeom::OFloatGeomParam::Sample width_sample;
181         width_sample.setVals(widths);
182
183         m_sample = OCurvesSchema::Sample(verts,
184                                          vert_counts,
185                                          curve_type,
186                                          periodicity,
187                                          width_sample,
188                                          OV2fGeomParam::Sample(),  /* UVs */
189                                          ON3fGeomParam::Sample(),  /* normals */
190                                          curve_basis,
191                                          weights,
192                                          orders,
193                                          knots);
194
195         m_sample.setSelfBounds(bounds());
196         m_schema.set(m_sample);
197 }
198
199 /* ************************************************************************** */
200
201 AbcCurveReader::AbcCurveReader(const Alembic::Abc::IObject &object, ImportSettings &settings)
202     : AbcObjectReader(object, settings)
203 {
204         ICurves abc_curves(object, kWrapExisting);
205         m_curves_schema = abc_curves.getSchema();
206
207         get_min_max_time(m_iobject, m_curves_schema, m_min_time, m_max_time);
208 }
209
210 bool AbcCurveReader::valid() const
211 {
212         return m_curves_schema.valid();
213 }
214
215 bool AbcCurveReader::accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
216                                          const Object *const ob,
217                                          const char **err_str) const
218 {
219         if (!Alembic::AbcGeom::ICurves::matches(alembic_header)) {
220                 *err_str = "Object type mismatch, Alembic object path pointed to Curves when importing, but not any more.";
221                 return false;
222         }
223
224         if (ob->type != OB_CURVE) {
225                 *err_str = "Object type mismatch, Alembic object path points to Curves.";
226                 return false;
227         }
228
229         return true;
230 }
231
232 void AbcCurveReader::readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel)
233 {
234         Curve *cu = BKE_curve_add(bmain, m_data_name.c_str(), OB_CURVE);
235
236         cu->flag |= CU_DEFORM_FILL | CU_3D;
237         cu->actvert = CU_ACT_NONE;
238         cu->resolu = 1;
239
240         ICompoundProperty user_props = m_curves_schema.getUserProperties();
241         if (user_props) {
242                 const PropertyHeader *header = user_props.getPropertyHeader(ABC_CURVE_RESOLUTION_U_PROPNAME);
243                 if (header != NULL && header->isScalar() && IInt16Property::matches(*header)) {
244                         IInt16Property resolu(user_props, header->getName());
245                         cu->resolu = resolu.getValue(sample_sel);
246                 }
247         }
248
249         m_object = BKE_object_add_only_object(bmain, OB_CURVE, m_object_name.c_str());
250         m_object->data = cu;
251
252         read_curve_sample(cu, m_curves_schema, sample_sel);
253
254         if (has_animations(m_curves_schema, m_settings)) {
255                 addCacheModifier();
256         }
257 }
258
259 /* ************************************************************************** */
260
261 void read_curve_sample(Curve *cu, const ICurvesSchema &schema, const ISampleSelector &sample_sel)
262 {
263         ICurvesSchema::Sample smp = schema.getValue(sample_sel);
264         const Int32ArraySamplePtr num_vertices = smp.getCurvesNumVertices();
265         const P3fArraySamplePtr positions = smp.getPositions();
266         const FloatArraySamplePtr weights = smp.getPositionWeights();
267         const FloatArraySamplePtr knots = smp.getKnots();
268         const CurvePeriodicity periodicity = smp.getWrap();
269         const UcharArraySamplePtr orders = smp.getOrders();
270
271         const IFloatGeomParam widths_param = schema.getWidthsParam();
272         FloatArraySamplePtr radiuses;
273
274         if (widths_param.valid()) {
275                 IFloatGeomParam::Sample wsample = widths_param.getExpandedValue(sample_sel);
276                 radiuses = wsample.getVals();
277         }
278
279         int knot_offset = 0;
280
281         size_t idx = 0;
282         for (size_t i = 0; i < num_vertices->size(); ++i) {
283                 const int num_verts = (*num_vertices)[i];
284
285                 Nurb *nu = static_cast<Nurb *>(MEM_callocN(sizeof(Nurb), "abc_getnurb"));
286                 nu->resolu = cu->resolu;
287                 nu->resolv = cu->resolv;
288                 nu->pntsu = num_verts;
289                 nu->pntsv = 1;
290                 nu->flag |= CU_SMOOTH;
291
292                 switch (smp.getType()) {
293                         case Alembic::AbcGeom::kCubic:
294                                 nu->orderu = 4;
295                                 break;
296                         case Alembic::AbcGeom::kVariableOrder:
297                                 if (orders && orders->size() > i) {
298                                         nu->orderu = static_cast<short>((*orders)[i]);
299                                         break;
300                                 }
301                                 ATTR_FALLTHROUGH;
302                         case Alembic::AbcGeom::kLinear:
303                         default:
304                                 nu->orderu = 2;
305                 }
306
307                 if (periodicity == Alembic::AbcGeom::kNonPeriodic) {
308                         nu->flagu |= CU_NURB_ENDPOINT;
309                 }
310                 else if (periodicity == Alembic::AbcGeom::kPeriodic) {
311                         nu->flagu |= CU_NURB_CYCLIC;
312
313                         /* Check the number of points which overlap, we don't have
314                          * overlapping points in Blender, but other software do use them to
315                          * indicate that a curve is actually cyclic. Usually the number of
316                          * overlapping points is equal to the order/degree of the curve.
317                          */
318
319                         const int start = idx;
320                         const int end = idx + num_verts;
321                         int overlap = 0;
322
323                         for (int j = start, k = end - nu->orderu; j < nu->orderu; ++j, ++k) {
324                                 const Imath::V3f &p1 = (*positions)[j];
325                                 const Imath::V3f &p2 = (*positions)[k];
326
327                                 if (p1 != p2) {
328                                         break;
329                                 }
330
331                                 ++overlap;
332                         }
333
334                         /* TODO: Special case, need to figure out how it coincides with knots. */
335                         if (overlap == 0 && num_verts > 2 && (*positions)[start] == (*positions)[end - 1]) {
336                                 overlap = 1;
337                         }
338
339                         /* There is no real cycles. */
340                         if (overlap == 0) {
341                                 nu->flagu &= ~CU_NURB_CYCLIC;
342                                 nu->flagu |= CU_NURB_ENDPOINT;
343                         }
344
345                         nu->pntsu -= overlap;
346                 }
347
348                 const bool do_weights = (weights != NULL) && (weights->size() > 1);
349                 float weight = 1.0f;
350
351                 const bool do_radius = (radiuses != NULL) && (radiuses->size() > 1);
352                 float radius = (radiuses && radiuses->size() == 1) ? (*radiuses)[0] : 1.0f;
353
354                 nu->type = CU_NURBS;
355
356                 nu->bp = static_cast<BPoint *>(MEM_callocN(sizeof(BPoint) * nu->pntsu, "abc_getnurb"));
357                 BPoint *bp = nu->bp;
358
359                 for (int j = 0; j < nu->pntsu; ++j, ++bp, ++idx) {
360                         const Imath::V3f &pos = (*positions)[idx];
361
362                         if (do_radius) {
363                                 radius = (*radiuses)[idx];
364                         }
365
366                         if (do_weights) {
367                                 weight = (*weights)[idx];
368                         }
369
370                         copy_zup_from_yup(bp->vec, pos.getValue());
371                         bp->vec[3] = weight;
372                         bp->f1 = SELECT;
373                         bp->radius = radius;
374                         bp->weight = 1.0f;
375                 }
376
377                 if (knots && knots->size() != 0) {
378                         nu->knotsu = static_cast<float *>(MEM_callocN(KNOTSU(nu) * sizeof(float), "abc_setsplineknotsu"));
379
380                         /* TODO: second check is temporary, for until the check for cycles is rock solid. */
381                         if (periodicity == Alembic::AbcGeom::kPeriodic && (KNOTSU(nu) == knots->size() - 2)) {
382                                 /* Skip first and last knots. */
383                                 for (size_t i = 1; i < knots->size() - 1; ++i) {
384                                         nu->knotsu[i - 1] = (*knots)[knot_offset + i];
385                                 }
386                         }
387                         else {
388                                 /* TODO: figure out how to use the knots array from other
389                                  * software in this case. */
390                                 BKE_nurb_knot_calc_u(nu);
391                         }
392
393                         knot_offset += knots->size();
394                 }
395                 else {
396                         BKE_nurb_knot_calc_u(nu);
397                 }
398
399                 BLI_addtail(BKE_curve_nurbs_get(cu), nu);
400         }
401 }
402
403 /* NOTE: Alembic only stores data about control points, but the Mesh
404  * passed from the cache modifier contains the displist, which has more data
405  * than the control points, so to avoid corrupting the displist we modify the
406  * object directly and create a new Mesh from that. Also we might need to
407  * create new or delete existing NURBS in the curve.
408  */
409 Mesh *AbcCurveReader::read_mesh(Mesh * /*existing_mesh*/,
410                                 const ISampleSelector &sample_sel,
411                                 int /*read_flag*/,
412                                 const char ** /*err_str*/)
413 {
414         const ICurvesSchema::Sample sample = m_curves_schema.getValue(sample_sel);
415
416         const P3fArraySamplePtr &positions = sample.getPositions();
417         const Int32ArraySamplePtr num_vertices = sample.getCurvesNumVertices();
418
419         int vertex_idx = 0;
420         int curve_idx = 0;
421         Curve *curve = static_cast<Curve *>(m_object->data);
422
423         const int curve_count = BLI_listbase_count(&curve->nurb);
424
425         if (curve_count != num_vertices->size()) {
426                 BKE_nurbList_free(&curve->nurb);
427                 read_curve_sample(curve, m_curves_schema, sample_sel);
428         }
429         else {
430                 Nurb *nurbs = static_cast<Nurb *>(curve->nurb.first);
431                 for (; nurbs; nurbs = nurbs->next, ++curve_idx) {
432                         const int totpoint = (*num_vertices)[curve_idx];
433
434                         if (nurbs->bp) {
435                                 BPoint *point = nurbs->bp;
436
437                                 for (int i = 0; i < totpoint; ++i, ++point, ++vertex_idx) {
438                                         const Imath::V3f &pos = (*positions)[vertex_idx];
439                                         copy_zup_from_yup(point->vec, pos.getValue());
440                                 }
441                         }
442                         else if (nurbs->bezt) {
443                                 BezTriple *bezier = nurbs->bezt;
444
445                                 for (int i = 0; i < totpoint; ++i, ++bezier, ++vertex_idx) {
446                                         const Imath::V3f &pos = (*positions)[vertex_idx];
447                                         copy_zup_from_yup(bezier->vec[1], pos.getValue());
448                                 }
449                         }
450                 }
451         }
452
453         return BKE_mesh_new_nomain_from_curve(m_object);
454 }