/[svn]/gigedit/trunk/src/gigedit/CombineInstrumentsDialog.cpp
ViewVC logotype

Contents of /gigedit/trunk/src/gigedit/CombineInstrumentsDialog.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2550 - (show annotations) (download)
Wed May 14 01:31:30 2014 UTC (9 years, 10 months ago) by schoenebeck
File size: 34673 byte(s)
* Fixed various bugs regarding new "combine instruments" tool.
* Show a warning if user tries to combine instruments in old
  .gig v2 format.
* Don't auto remove stereo dimension if user drags a mono
  sample reference on DimensionRegion's sample reference.
* Select "Instruments" tab on app start by default.

1 /*
2 Copyright (c) 2014 Christian Schoenebeck
3
4 This file is part of "gigedit" and released under the terms of the
5 GNU General Public License version 2.
6 */
7
8 #include "CombineInstrumentsDialog.h"
9
10 // enable this for debug messages being printed while combining the instruments
11 #define DEBUG_COMBINE_INSTRUMENTS 0
12
13 #include "global.h"
14
15 #include <set>
16 #include <iostream>
17 #include <assert.h>
18
19 #include <glibmm/ustring.h>
20 #include <gtkmm/stock.h>
21 #include <gtkmm/messagedialog.h>
22
23 Glib::ustring gig_to_utf8(const gig::String& gig_string);
24
25 typedef std::map<gig::Instrument*, gig::Region*> RegionGroup;
26 typedef std::map<DLS::range_t,RegionGroup> RegionGroups;
27
28 typedef std::vector<DLS::range_t> DimensionZones;
29 typedef std::map<gig::dimension_t,DimensionZones> Dimensions;
30
31 typedef std::map<gig::dimension_t,int> DimensionCase;
32
33 typedef std::map<gig::dimension_t, int> DimensionRegionUpperLimits;
34
35 ///////////////////////////////////////////////////////////////////////////
36 // private functions
37
38 #if DEBUG_COMBINE_INSTRUMENTS
39 static void printRanges(const RegionGroups& regions) {
40 std::cout << "{ ";
41 for (RegionGroups::const_iterator it = regions.begin(); it != regions.end(); ++it) {
42 if (it != regions.begin()) std::cout << ", ";
43 std::cout << (int)it->first.low << ".." << (int)it->first.high;
44 }
45 std::cout << " }" << std::flush;
46 }
47 #endif
48
49 /**
50 * If the two ranges overlap, then this function returns the smallest point
51 * within that overlapping zone. If the two ranges do not overlap, then this
52 * function will return -1 instead.
53 */
54 inline int smallestOverlapPoint(const DLS::range_t& r1, const DLS::range_t& r2) {
55 if (r1.overlaps(r2.low)) return r2.low;
56 if (r2.overlaps(r1.low)) return r1.low;
57 return -1;
58 }
59
60 /**
61 * Get the most smallest region point (not necessarily its region start point)
62 * of all regions of the given instruments, start searching at keyboard
63 * position @a iStart.
64 *
65 * @returns very first region point >= iStart, or -1 if no region could be
66 * found with a range member point >= iStart
67 */
68 static int findLowestRegionPoint(std::vector<gig::Instrument*>& instruments, int iStart) {
69 DLS::range_t searchRange = { iStart, 127 };
70 int result = -1;
71 for (uint i = 0; i < instruments.size(); ++i) {
72 gig::Instrument* instr = instruments[i];
73 for (gig::Region* rgn = instr->GetFirstRegion(); rgn; rgn = instr->GetNextRegion()) {
74 if (rgn->KeyRange.overlaps(searchRange)) {
75 int lowest = smallestOverlapPoint(rgn->KeyRange, searchRange);
76 if (result == -1 || lowest < result) result = lowest;
77 }
78 }
79 }
80 return result;
81 }
82
83 /**
84 * Get the most smallest region end of all regions of the given instruments,
85 * start searching at keyboard position @a iStart.
86 *
87 * @returns very first region end >= iStart, or -1 if no region could be found
88 * with a range end >= iStart
89 */
90 static int findFirstRegionEnd(std::vector<gig::Instrument*>& instruments, int iStart) {
91 DLS::range_t searchRange = { iStart, 127 };
92 int result = -1;
93 for (uint i = 0; i < instruments.size(); ++i) {
94 gig::Instrument* instr = instruments[i];
95 for (gig::Region* rgn = instr->GetFirstRegion(); rgn; rgn = instr->GetNextRegion()) {
96 if (rgn->KeyRange.overlaps(searchRange)) {
97 if (result == -1 || rgn->KeyRange.high < result)
98 result = rgn->KeyRange.high;
99 }
100 }
101 }
102 return result;
103 }
104
105 /**
106 * Returns a list of all regions of the given @a instrument where the respective
107 * region's key range overlaps the given @a range.
108 */
109 static std::vector<gig::Region*> getAllRegionsWhichOverlapRange(gig::Instrument* instrument, DLS::range_t range) {
110 //std::cout << "All regions which overlap { " << (int)range.low << ".." << (int)range.high << " } : " << std::flush;
111 std::vector<gig::Region*> v;
112 for (gig::Region* rgn = instrument->GetFirstRegion(); rgn; rgn = instrument->GetNextRegion()) {
113 if (rgn->KeyRange.overlaps(range)) {
114 v.push_back(rgn);
115 //std::cout << (int)rgn->KeyRange.low << ".." << (int)rgn->KeyRange.high << ", " << std::flush;
116 }
117 }
118 //std::cout << " END." << std::endl;
119 return v;
120 }
121
122 /**
123 * Returns all regions of the given @a instruments where the respective region's
124 * key range overlaps the given @a range. The regions returned are ordered (in a
125 * map) by their instrument pointer.
126 */
127 static RegionGroup getAllRegionsWhichOverlapRange(std::vector<gig::Instrument*>& instruments, DLS::range_t range) {
128 RegionGroup group;
129 for (uint i = 0; i < instruments.size(); ++i) {
130 gig::Instrument* instr = instruments[i];
131 std::vector<gig::Region*> v = getAllRegionsWhichOverlapRange(instr, range);
132 if (v.empty()) continue;
133 if (v.size() > 1) {
134 std::cerr << "WARNING: More than one region found!" << std::endl;
135 }
136 group[instr] = v[0];
137 }
138 return group;
139 }
140
141 /** @brief Identify required regions.
142 *
143 * Takes a list of @a instruments as argument (which are planned to be combined
144 * as layers in one single new instrument) and fulfills the following tasks:
145 *
146 * - 1. Identification of total amount of regions required to create a new
147 * instrument to become a layered version of the given instruments.
148 * - 2. Precise key range of each of those identified required regions to be
149 * created in that new instrument.
150 * - 3. Grouping the original source regions of the given original instruments
151 * to the respective target key range (new region) of the instrument to be
152 * created.
153 *
154 * @param instruments - list of instruments that are planned to be combined
155 * @returns structured result of the tasks described above
156 */
157 static RegionGroups groupByRegionIntersections(std::vector<gig::Instrument*>& instruments) {
158 RegionGroups groups;
159
160 // find all region intersections of all instruments
161 std::vector<DLS::range_t> intersections;
162 for (int iStart = 0; iStart <= 127; ) {
163 iStart = findLowestRegionPoint(instruments, iStart);
164 if (iStart < 0) break;
165 const int iEnd = findFirstRegionEnd(instruments, iStart);
166 DLS::range_t range = { iStart, iEnd };
167 intersections.push_back(range);
168 iStart = iEnd + 1;
169 }
170
171 // now sort all regions to those found intersections
172 for (uint i = 0; i < intersections.size(); ++i) {
173 const DLS::range_t& range = intersections[i];
174 RegionGroup group = getAllRegionsWhichOverlapRange(instruments, range);
175 if (!group.empty())
176 groups[range] = group;
177 else
178 std::cerr << "WARNING: empty region group!" << std::endl;
179 }
180
181 return groups;
182 }
183
184 /** @brief Identify required dimensions.
185 *
186 * Takes a planned new region (@a regionGroup) as argument and identifies which
187 * precise dimensions would have to be created for that new region, along with
188 * the amount of dimension zones and their precise individual zone sizes.
189 *
190 * @param regionGroup - planned new region for a new instrument
191 * @returns set of dimensions that shall be created for the given planned region
192 */
193 static Dimensions getDimensionsForRegionGroup(RegionGroup& regionGroup) {
194 std::map<gig::dimension_t, std::set<int> > dimUpperLimits;
195
196 // collect all dimension region zones' upper limits
197 for (RegionGroup::iterator it = regionGroup.begin();
198 it != regionGroup.end(); ++it)
199 {
200 gig::Region* rgn = it->second;
201 int previousBits = 0;
202 for (uint d = 0; d < rgn->Dimensions; ++d) {
203 const gig::dimension_def_t& def = rgn->pDimensionDefinitions[d];
204 for (uint z = 0; z < def.zones; ++z) {
205 int dr = z << previousBits;
206 gig::DimensionRegion* dimRgn = rgn->pDimensionRegions[dr];
207 // Store the individual dimension zone sizes (or actually their
208 // upper limits here) for each dimension.
209 // HACK: Note that the velocity dimension is specially handled
210 // here. Instead of taking over custom velocity split sizes
211 // here, only a bogus number (zone index number) is stored for
212 // each velocity zone, that way only the maxiumum amount of
213 // velocity splits of all regions is stored here, and when their
214 // individual DimensionRegions are finally copied (later), the
215 // individual velocity split size are copied by that.
216 dimUpperLimits[def.dimension].insert(
217 (def.dimension == gig::dimension_velocity) ?
218 z : (def.split_type == gig::split_type_bit) ?
219 ((z+1) * 128/def.zones - 1) : dimRgn->DimensionUpperLimits[dr]
220 );
221 }
222 previousBits += def.bits;
223 }
224 }
225
226 // convert upper limit set to range vector
227 Dimensions dims;
228 for (std::map<gig::dimension_t, std::set<int> >::const_iterator it = dimUpperLimits.begin();
229 it != dimUpperLimits.end(); ++it)
230 {
231 gig::dimension_t type = it->first;
232 int iLow = 0;
233 for (std::set<int>::const_iterator itNums = it->second.begin();
234 itNums != it->second.end(); ++itNums)
235 {
236 const int iUpperLimit = *itNums;
237 DLS::range_t range = { iLow, iUpperLimit };
238 dims[type].push_back(range);
239 iLow = iUpperLimit + 1;
240 }
241 }
242
243 return dims;
244 }
245
246 inline int getDimensionIndex(gig::dimension_t type, gig::Region* rgn) {
247 for (uint i = 0; i < rgn->Dimensions; ++i)
248 if (rgn->pDimensionDefinitions[i].dimension == type)
249 return i;
250 return -1;
251 }
252
253 static void fillDimValues(uint* values/*[8]*/, DimensionCase dimCase, gig::Region* rgn, bool bShouldHaveAllDimensionsPassed) {
254 #if DEBUG_COMBINE_INSTRUMENTS
255 printf("dimvalues = { ");
256 fflush(stdout);
257 #endif
258 for (DimensionCase::iterator it = dimCase.begin(); it != dimCase.end(); ++it) {
259 gig::dimension_t type = it->first;
260 int iDimIndex = getDimensionIndex(type, rgn);
261 if (bShouldHaveAllDimensionsPassed) assert(iDimIndex >= 0);
262 else if (iDimIndex < 0) continue;
263 values[iDimIndex] = it->second;
264 #if DEBUG_COMBINE_INSTRUMENTS
265 printf("%x=%d, ", type, it->second);
266 #endif
267 }
268 #if DEBUG_COMBINE_INSTRUMENTS
269 printf("\n");
270 #endif
271 }
272
273 static DimensionRegionUpperLimits getDimensionRegionUpperLimits(gig::DimensionRegion* dimRgn) {
274 DimensionRegionUpperLimits limits;
275 gig::Region* rgn = dimRgn->GetParent();
276 for (uint d = 0; d < rgn->Dimensions; ++d) {
277 const gig::dimension_def_t& def = rgn->pDimensionDefinitions[d];
278 limits[def.dimension] = dimRgn->DimensionUpperLimits[d];
279 }
280 return limits;
281 }
282
283 static void restoreDimensionRegionUpperLimits(gig::DimensionRegion* dimRgn, const DimensionRegionUpperLimits& limits) {
284 gig::Region* rgn = dimRgn->GetParent();
285 for (DimensionRegionUpperLimits::const_iterator it = limits.begin();
286 it != limits.end(); ++it)
287 {
288 int index = getDimensionIndex(it->first, rgn);
289 assert(index >= 0);
290 dimRgn->DimensionUpperLimits[index] = it->second;
291 }
292 }
293
294 /**
295 * Returns the sum of all bits of all dimensions defined before the given
296 * dimensions (@a type). This allows to access cases of that particular
297 * dimension directly.
298 *
299 * @param type - dimension that shall be used
300 * @param rgn - parent region of that dimension
301 */
302 inline int baseBits(gig::dimension_t type, gig::Region* rgn) {
303 int previousBits = 0;
304 for (uint i = 0; i < rgn->Dimensions; ++i) {
305 if (rgn->pDimensionDefinitions[i].dimension == type) break;
306 previousBits += rgn->pDimensionDefinitions[i].bits;
307 }
308 return previousBits;
309 }
310
311 inline int dimensionRegionIndex(gig::DimensionRegion* dimRgn) {
312 gig::Region* rgn = dimRgn->GetParent();
313 int sz = sizeof(rgn->pDimensionRegions) / sizeof(gig::DimensionRegion*);
314 for (int i = 0; i < sz; ++i)
315 if (rgn->pDimensionRegions[i] == dimRgn)
316 return i;
317 return -1;
318 }
319
320 /** @brief Get exact zone ranges of given dimension.
321 *
322 * This function is useful for the velocity type dimension. In contrast to other
323 * dimension types, this dimension can have different zone ranges (that is
324 * different individual start and end points of its dimension zones) depending
325 * on which zones of other dimensions (on that gig::Region) are currently
326 * selected.
327 *
328 * @param type - dimension where the zone ranges should be retrieved for
329 * (usually the velocity dimension in this context)
330 * @param dimRgn - reflects the exact cases (zone selections) of all other
331 * dimensions than the given one in question
332 * @returns individual ranges for each zone of the questioned dimension type,
333 * it returns an empty result on errors instead
334 */
335 static DimensionZones preciseDimensionZonesFor(gig::dimension_t type, gig::DimensionRegion* dimRgn) {
336 DimensionZones zones;
337 gig::Region* rgn = dimRgn->GetParent();
338 int iDimension = getDimensionIndex(type, rgn);
339 if (iDimension < 0) return zones;
340 const gig::dimension_def_t& def = rgn->pDimensionDefinitions[iDimension];
341 int iDimRgn = dimensionRegionIndex(dimRgn);
342 int iBaseBits = baseBits(type, rgn);
343 int mask = ~(((1 << def.bits) - 1) << iBaseBits);
344
345 #if DEBUG_COMBINE_INSTRUMENTS
346 printf("velo zones { ");
347 fflush(stdout);
348 #endif
349 int iLow = 0;
350 for (int z = 0; z < def.zones; ++z) {
351 gig::DimensionRegion* dimRgn2 =
352 rgn->pDimensionRegions[ (iDimRgn & mask) | ( z << iBaseBits) ];
353 int iHigh = dimRgn2->DimensionUpperLimits[iDimension];
354 DLS::range_t range = { iLow, iHigh};
355 #if DEBUG_COMBINE_INSTRUMENTS
356 printf("%d..%d, ", iLow, iHigh);
357 fflush(stdout);
358 #endif
359 zones.push_back(range);
360 iLow = iHigh + 1;
361 }
362 #if DEBUG_COMBINE_INSTRUMENTS
363 printf("}\n");
364 #endif
365 return zones;
366 }
367
368 struct CopyAssignSchedEntry {
369 gig::DimensionRegion* src;
370 gig::DimensionRegion* dst;
371 int velocityZone;
372 int totalSrcVelocityZones;
373 };
374 typedef std::vector<CopyAssignSchedEntry> CopyAssignSchedule;
375
376 /** @brief Copy all DimensionRegions from source Region to target Region.
377 *
378 * Copies the entire articulation informations (including sample reference of
379 * course) from all individual DimensionRegions of source Region @a inRgn to
380 * target Region @a outRgn. There are no dimension regions created during this
381 * task. It is expected that the required dimensions (thus the required
382 * dimension regions) were already created before calling this function.
383 *
384 * To be precise, it does the task above only for the layer selected by
385 * @a iSrcLayer and @a iDstLayer. All dimensions regions of other layers that
386 * may exist, will not be copied by one single call of this function. So if
387 * there is a layer dimension, this function needs to be called several times.
388 *
389 * @param outRgn - where the dimension regions shall be copied to
390 * @param inRgn - all dimension regions that shall be copied from
391 * @param dims - precise dimension definitions of target region
392 * @param iDstLayer - layer index of destination region where the dimension
393 * regions shall be copied to
394 * @param iSrcLayer - layer index of the source region where the dimension
395 * regions shall be copied from
396 * @param dimCase - just for internal purpose (function recursion), don't pass
397 * anything here, this function will call itself recursively
398 * will fill this container with concrete dimension values for
399 * selecting the precise dimension regions during its task
400 * @param schedule - just for internal purpose (function recursion), don't pass
401 anything here: list of all DimensionRegion copy operations
402 * which is filled during the nested loops / recursions of
403 * this function call, they will be peformed after all
404 * function recursions have been completed
405 */
406 static void copyDimensionRegions(gig::Region* outRgn, gig::Region* inRgn, Dimensions dims, int iDstLayer, int iSrcLayer, DimensionCase dimCase = DimensionCase(), CopyAssignSchedule* schedule = NULL) {
407 const bool isHighestLevelOfRecursion = !schedule;
408
409 if (isHighestLevelOfRecursion)
410 schedule = new CopyAssignSchedule;
411
412 if (dims.empty()) { // reached deepest level of function recursion ...
413 CopyAssignSchedEntry e;
414
415 // resolve the respective source & destination DimensionRegion ...
416 uint srcDimValues[8] = {};
417 uint dstDimValues[8] = {};
418 DimensionCase srcDimCase = dimCase;
419 DimensionCase dstDimCase = dimCase;
420 srcDimCase[gig::dimension_layer] = iSrcLayer;
421 dstDimCase[gig::dimension_layer] = iDstLayer;
422
423 #if DEBUG_COMBINE_INSTRUMENTS
424 printf("-------------------------------\n");
425 #endif
426
427 // first select source & target dimension region with an arbitrary
428 // velocity split zone, to get access to the precise individual velocity
429 // split zone sizes (if there is actually a velocity dimension at all,
430 // otherwise we already select the desired source & target dimension
431 // region here)
432 #if DEBUG_COMBINE_INSTRUMENTS
433 printf("src "); fflush(stdout);
434 #endif
435 fillDimValues(srcDimValues, srcDimCase, inRgn, false);
436 #if DEBUG_COMBINE_INSTRUMENTS
437 printf("dst "); fflush(stdout);
438 #endif
439 fillDimValues(dstDimValues, dstDimCase, outRgn, true);
440 gig::DimensionRegion* srcDimRgn = inRgn->GetDimensionRegionByValue(srcDimValues);
441 gig::DimensionRegion* dstDimRgn = outRgn->GetDimensionRegionByValue(dstDimValues);
442 #if DEBUG_COMBINE_INSTRUMENTS
443 printf("iDstLayer=%d iSrcLayer=%d\n", iDstLayer, iSrcLayer);
444 printf("srcDimRgn=%lx dstDimRgn=%lx\n", (uint64_t)srcDimRgn, (uint64_t)dstDimRgn);
445 printf("srcSample='%s' dstSample='%s'\n",
446 (!srcDimRgn->pSample ? "NULL" : srcDimRgn->pSample->pInfo->Name.c_str()),
447 (!dstDimRgn->pSample ? "NULL" : dstDimRgn->pSample->pInfo->Name.c_str())
448 );
449 #endif
450
451 assert(srcDimRgn->GetParent() == inRgn);
452 assert(dstDimRgn->GetParent() == outRgn);
453
454 // now that we have access to the precise velocity split zone upper
455 // limits, we can select the actual source & destination dimension
456 // regions we need to copy (assuming that source or target region has
457 // a velocity dimension)
458 if (outRgn->GetDimensionDefinition(gig::dimension_velocity)) {
459 // re-select target dimension region (with correct velocity zone)
460 DimensionZones dstZones = preciseDimensionZonesFor(gig::dimension_velocity, dstDimRgn);
461 assert(dstZones.size() > 1);
462 int iZoneIndex = dstDimCase[gig::dimension_velocity];
463 e.velocityZone = iZoneIndex;
464 #if DEBUG_COMBINE_INSTRUMENTS
465 printf("dst velocity zone: %d/%d\n", iZoneIndex, (int)dstZones.size());
466 #endif
467 assert(uint(iZoneIndex) < dstZones.size());
468 dstDimCase[gig::dimension_velocity] = dstZones[iZoneIndex].low; // arbitrary value between low and high
469 #if DEBUG_COMBINE_INSTRUMENTS
470 printf("dst velocity value = %d\n", dstDimCase[gig::dimension_velocity]);
471 printf("dst refilled "); fflush(stdout);
472 #endif
473 fillDimValues(dstDimValues, dstDimCase, outRgn, true);
474 dstDimRgn = outRgn->GetDimensionRegionByValue(dstDimValues);
475 #if DEBUG_COMBINE_INSTRUMENTS
476 printf("reselected dstDimRgn=%lx\n", (uint64_t)dstDimRgn);
477 printf("dstSample='%s'\n",
478 (!dstDimRgn->pSample ? "NULL" : dstDimRgn->pSample->pInfo->Name.c_str())
479 );
480 #endif
481
482 // re-select source dimension region with correct velocity zone
483 // (if it has a velocity dimension that is)
484 if (inRgn->GetDimensionDefinition(gig::dimension_velocity)) {
485 DimensionZones srcZones = preciseDimensionZonesFor(gig::dimension_velocity, srcDimRgn);
486 e.totalSrcVelocityZones = srcZones.size();
487 assert(srcZones.size() > 1);
488 if (uint(iZoneIndex) >= srcZones.size())
489 iZoneIndex = srcZones.size() - 1;
490 srcDimCase[gig::dimension_velocity] = srcZones[iZoneIndex].low; // same zone as used above for target dimension region (no matter what the precise zone ranges are)
491 #if DEBUG_COMBINE_INSTRUMENTS
492 printf("src refilled "); fflush(stdout);
493 #endif
494 fillDimValues(srcDimValues, srcDimCase, inRgn, false);
495 srcDimRgn = inRgn->GetDimensionRegionByValue(srcDimValues);
496 #if DEBUG_COMBINE_INSTRUMENTS
497 printf("reselected srcDimRgn=%lx\n", (uint64_t)srcDimRgn);
498 printf("srcSample='%s'\n",
499 (!srcDimRgn->pSample ? "NULL" : srcDimRgn->pSample->pInfo->Name.c_str())
500 );
501 #endif
502 }
503 }
504
505 // Schedule copy opertion of source -> target DimensionRegion for the
506 // time after all nested loops have been traversed. We have to postpone
507 // the actual copy operations this way, because otherwise it would
508 // overwrite informations inside the destination DimensionRegion object
509 // that we need to read in the code block above.
510 e.src = srcDimRgn;
511 e.dst = dstDimRgn;
512 schedule->push_back(e);
513
514 return; // returning from deepest level of function recursion
515 }
516
517 // Copying n dimensions requires n nested loops. That's why this function
518 // is calling itself recursively to provide the required amount of nested
519 // loops. With each call it pops from argument 'dims' and pushes to
520 // argument 'dimCase'.
521
522 Dimensions::iterator itDimension = dims.begin();
523 gig::dimension_t type = itDimension->first;
524 DimensionZones zones = itDimension->second;
525 dims.erase(itDimension);
526
527 int iZone = 0;
528 for (DimensionZones::iterator itZone = zones.begin();
529 itZone != zones.end(); ++itZone, ++iZone)
530 {
531 DLS::range_t zoneRange = *itZone;
532 gig::dimension_def_t* def = outRgn->GetDimensionDefinition(type);
533 dimCase[type] = (def->split_type == gig::split_type_bit) ? iZone : zoneRange.low;
534
535 // recurse until 'dims' is exhausted (and dimCase filled up with concrete value)
536 copyDimensionRegions(outRgn, inRgn, dims, iDstLayer, iSrcLayer, dimCase, schedule);
537 }
538
539 // if current function call is the (very first) entry point ...
540 if (isHighestLevelOfRecursion) {
541 // ... then perform all scheduled DimensionRegion copy operations
542 for (uint i = 0; i < schedule->size(); ++i) {
543 CopyAssignSchedEntry& e = (*schedule)[i];
544
545 // backup the target DimensionRegion's current dimension zones upper
546 // limits (because the target DimensionRegion's upper limits are
547 // already defined correctly since calling AddDimension(), and the
548 // CopyAssign() call next, will overwrite those upper limits
549 // unfortunately
550 DimensionRegionUpperLimits dstUpperLimits = getDimensionRegionUpperLimits(e.dst);
551 DimensionRegionUpperLimits srcUpperLimits = getDimensionRegionUpperLimits(e.src);
552
553 // now actually copy over the current DimensionRegion
554 const gig::Region* const origRgn = e.dst->GetParent(); // just for sanity check below
555 e.dst->CopyAssign(e.src);
556 assert(origRgn == e.dst->GetParent()); // if gigedit is crashing here, then you must update libgig (to at least SVN r2547, v3.3.0.svn10)
557
558 // restore all original dimension zone upper limits except of the
559 // velocity dimension, because the velocity dimension zone sizes are
560 // allowed to differ for individual DimensionRegions in gig v3
561 // format
562 if (srcUpperLimits.count(gig::dimension_velocity)) {
563 assert(dstUpperLimits.count(gig::dimension_velocity));
564 dstUpperLimits[gig::dimension_velocity] =
565 (e.velocityZone >= e.totalSrcVelocityZones)
566 ? 127 : srcUpperLimits[gig::dimension_velocity];
567 }
568 restoreDimensionRegionUpperLimits(e.dst, dstUpperLimits);
569 }
570 delete schedule;
571 }
572 }
573
574 /** @brief Combine given list of instruments to one instrument.
575 *
576 * Takes a list of @a instruments as argument and combines them to one single
577 * new @a output instrument. For this task, it will create a 'layer' dimension
578 * in the new instrument and copies the source instruments to those layers.
579 *
580 * @param instruments - (input) list of instruments that shall be combined,
581 * they will only be read, so they will be left untouched
582 * @param gig - (input/output) .gig file where the new combined instrument shall
583 * be created
584 * @param output - (output) on success this pointer will be set to the new
585 * instrument being created
586 * @throw RIFF::Exception on any kinds of errors
587 */
588 static void combineInstruments(std::vector<gig::Instrument*>& instruments, gig::File* gig, gig::Instrument*& output) {
589 output = NULL;
590
591 // divide the individual regions to (probably even smaller) groups of
592 // regions, coping with the fact that the source regions of the instruments
593 // might have quite different range sizes and start and end points
594 RegionGroups groups = groupByRegionIntersections(instruments);
595 #if DEBUG_COMBINE_INSTRUMENTS
596 std::cout << std::endl << "New regions: " << std::flush;
597 printRanges(groups);
598 std::cout << std::endl;
599 #endif
600
601 if (groups.empty())
602 throw gig::Exception(_("No regions found to create a new instrument with."));
603
604 // create a new output instrument
605 gig::Instrument* outInstr = gig->AddInstrument();
606 outInstr->pInfo->Name = _("NEW COMBINATION");
607
608 // Distinguishing in the following code block between 'horizontal' and
609 // 'vertical' regions. The 'horizontal' ones are meant to be the key ranges
610 // in the output instrument, while the 'vertical' regions are meant to be
611 // the set of source regions that shall be layered to that 'horizontal'
612 // region / key range. It is important to know, that the key ranges defined
613 // in the 'horizontal' and 'vertical' regions might differ.
614
615 // merge the instruments to the new output instrument
616 for (RegionGroups::iterator itGroup = groups.begin();
617 itGroup != groups.end(); ++itGroup) // iterate over 'horizontal' / target regions ...
618 {
619 gig::Region* outRgn = outInstr->AddRegion();
620 outRgn->SetKeyRange(itGroup->first.low, itGroup->first.high);
621
622 // detect the total amount of layers required to build up this combi
623 // for current key range
624 int iTotalLayers = 0;
625 for (RegionGroup::iterator itRgn = itGroup->second.begin();
626 itRgn != itGroup->second.end(); ++itRgn)
627 {
628 gig::Region* inRgn = itRgn->second;
629 iTotalLayers += inRgn->Layers;
630 }
631
632 // create all required dimensions for this output region
633 // (except the layer dimension, which we create as next step)
634 Dimensions dims = getDimensionsForRegionGroup(itGroup->second);
635 for (Dimensions::iterator itDim = dims.begin();
636 itDim != dims.end(); ++itDim)
637 {
638 if (itDim->first == gig::dimension_layer) continue;
639
640 gig::dimension_def_t def;
641 def.dimension = itDim->first; // dimension type
642 def.zones = itDim->second.size();
643 def.bits = zoneCountToBits(def.zones);
644 #if DEBUG_COMBINE_INSTRUMENTS
645 std::cout << "Adding new regular dimension type=" << std::hex << (int)def.dimension << std::dec << ", zones=" << (int)def.zones << ", bits=" << (int)def.bits << " ... " << std::flush;
646 #endif
647 outRgn->AddDimension(&def);
648 #if DEBUG_COMBINE_INSTRUMENTS
649 std::cout << "OK" << std::endl << std::flush;
650 #endif
651 }
652
653 // create the layer dimension (if necessary for current key range)
654 if (iTotalLayers > 1) {
655 gig::dimension_def_t def;
656 def.dimension = gig::dimension_layer; // dimension type
657 def.zones = iTotalLayers;
658 def.bits = zoneCountToBits(def.zones);
659 #if DEBUG_COMBINE_INSTRUMENTS
660 std::cout << "Adding new (layer) dimension type=" << std::hex << (int)def.dimension << std::dec << ", zones=" << (int)def.zones << ", bits=" << (int)def.bits << " ... " << std::flush;
661 #endif
662 outRgn->AddDimension(&def);
663 #if DEBUG_COMBINE_INSTRUMENTS
664 std::cout << "OK" << std::endl << std::flush;
665 #endif
666 }
667
668 // now copy the source dimension regions to the target dimension regions
669 int iDstLayer = 0;
670 for (RegionGroup::iterator itRgn = itGroup->second.begin();
671 itRgn != itGroup->second.end(); ++itRgn) // iterate over 'vertical' / source regions ...
672 {
673 gig::Region* inRgn = itRgn->second;
674 for (uint iSrcLayer = 0; iSrcLayer < inRgn->Layers; ++iSrcLayer, ++iDstLayer) {
675 copyDimensionRegions(outRgn, inRgn, dims, iDstLayer, iSrcLayer);
676 }
677 }
678 }
679
680 // success
681 output = outInstr;
682 }
683
684 ///////////////////////////////////////////////////////////////////////////
685 // class 'CombineInstrumentsDialog'
686
687 CombineInstrumentsDialog::CombineInstrumentsDialog(Gtk::Window& parent, gig::File* gig)
688 : Gtk::Dialog(_("Combine Instruments"), parent, true),
689 m_gig(gig), m_fileWasChanged(false), m_newCombinedInstrument(NULL),
690 m_cancelButton(Gtk::Stock::CANCEL), m_OKButton(Gtk::Stock::OK),
691 m_descriptionLabel()
692 {
693 get_vbox()->pack_start(m_descriptionLabel, Gtk::PACK_SHRINK);
694 get_vbox()->pack_start(m_treeView);
695 get_vbox()->pack_start(m_buttonBox, Gtk::PACK_SHRINK);
696
697 #if GTKMM_MAJOR_VERSION >= 3
698 description.set_line_wrap();
699 #endif
700 m_descriptionLabel.set_text(_(
701 "Select at least two instruments below that shall be combined "
702 "as layers (using a \"Layer\" dimension) to a new instrument. The "
703 "original instruments remain untouched.")
704 );
705
706 m_refTreeModel = Gtk::ListStore::create(m_columns);
707 m_treeView.set_model(m_refTreeModel);
708 m_treeView.set_tooltip_text(_(
709 "Use SHIFT + left click or CTRL + left click to select the instruments "
710 "you want to combine."
711 ));
712 m_treeView.append_column("Instrument", m_columns.m_col_name);
713 m_treeView.set_headers_visible(false);
714 m_treeView.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
715 m_treeView.get_selection()->signal_changed().connect(
716 sigc::mem_fun(*this, &CombineInstrumentsDialog::onSelectionChanged)
717 );
718 m_treeView.show();
719
720 for (int i = 0; true; ++i) {
721 gig::Instrument* instr = gig->GetInstrument(i);
722 if (!instr) break;
723
724 #if DEBUG_COMBINE_INSTRUMENTS
725 {
726 std::cout << "Instrument (" << i << ") '" << instr->pInfo->Name << "' Regions: " << std::flush;
727 for (gig::Region* rgn = instr->GetFirstRegion(); rgn; rgn = instr->GetNextRegion()) {
728 std::cout << rgn->KeyRange.low << ".." << rgn->KeyRange.high << ", " << std::flush;
729 }
730 std::cout << std::endl;
731 }
732 std::cout << std::endl;
733 #endif
734
735 Glib::ustring name(gig_to_utf8(instr->pInfo->Name));
736 Gtk::TreeModel::iterator iter = m_refTreeModel->append();
737 Gtk::TreeModel::Row row = *iter;
738 row[m_columns.m_col_name] = name;
739 row[m_columns.m_col_instr] = instr;
740 }
741
742 m_buttonBox.set_layout(Gtk::BUTTONBOX_END);
743 m_buttonBox.set_border_width(5);
744 m_buttonBox.pack_start(m_cancelButton, Gtk::PACK_SHRINK);
745 m_buttonBox.pack_start(m_OKButton, Gtk::PACK_SHRINK);
746 m_buttonBox.show();
747
748 m_cancelButton.show();
749 m_OKButton.set_sensitive(false);
750 m_OKButton.show();
751
752 m_cancelButton.signal_clicked().connect(
753 sigc::mem_fun(*this, &CombineInstrumentsDialog::hide)
754 );
755
756 m_OKButton.signal_clicked().connect(
757 sigc::mem_fun(*this, &CombineInstrumentsDialog::combineSelectedInstruments)
758 );
759
760 show_all_children();
761
762 // show a warning to user if he uses a .gig in v2 format
763 if (gig->pVersion->major < 3) {
764 Glib::ustring txt = _(
765 "You are currently using a .gig file in old v2 format. The current "
766 "combine algorithm will most probably fail trying to combine "
767 "instruments in this old format. So better save the file in new v3 "
768 "format before trying to combine your instruments."
769 );
770 Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_WARNING);
771 msg.run();
772 }
773 }
774
775 void CombineInstrumentsDialog::combineSelectedInstruments() {
776 std::vector<gig::Instrument*> instruments;
777 std::vector<Gtk::TreeModel::Path> v = m_treeView.get_selection()->get_selected_rows();
778 for (uint i = 0; i < v.size(); ++i) {
779 Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(v[i]);
780 Gtk::TreeModel::Row row = *it;
781 Glib::ustring name = row[m_columns.m_col_name];
782 gig::Instrument* instrument = row[m_columns.m_col_instr];
783 #if DEBUG_COMBINE_INSTRUMENTS
784 printf("Selection '%s' 0x%lx\n\n", name.c_str(), int64_t((void*)instrument));
785 #endif
786 instruments.push_back(instrument);
787 }
788
789 try {
790 combineInstruments(instruments, m_gig, m_newCombinedInstrument);
791 } catch (RIFF::Exception e) {;
792 Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);
793 msg.run();
794 return;
795 }
796
797 // no error occurred
798 m_fileWasChanged = true;
799 hide();
800 }
801
802 void CombineInstrumentsDialog::onSelectionChanged() {
803 std::vector<Gtk::TreeModel::Path> v = m_treeView.get_selection()->get_selected_rows();
804 m_OKButton.set_sensitive(v.size() >= 2);
805 }
806
807 bool CombineInstrumentsDialog::fileWasChanged() const {
808 return m_fileWasChanged;
809 }
810
811 gig::Instrument* CombineInstrumentsDialog::newCombinedInstrument() const {
812 return m_newCombinedInstrument;
813 }

  ViewVC Help
Powered by ViewVC