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