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