/[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 3151 - (show annotations) (download)
Fri May 5 18:44:59 2017 UTC (6 years, 11 months ago) by schoenebeck
File size: 43000 byte(s)
* WIP: Added initial draft implementation of macro editor
  (accessible for copied clipboard content via Alt+x).
* Bumped version (1.0.0.svn35).

1 /*
2 Copyright (c) 2014-2017 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 #include "compat.h"
15
16 #include <set>
17 #include <iostream>
18 #include <assert.h>
19 #include <stdarg.h>
20 #include <string.h>
21
22 #include <glibmm/ustring.h>
23 #include <gtkmm/messagedialog.h>
24 #include <gtkmm/label.h>
25
26 Glib::ustring dimTypeAsString(gig::dimension_t d);
27
28 typedef std::vector< std::pair<gig::Instrument*, gig::Region*> > OrderedRegionGroup;
29 typedef std::map<gig::Instrument*, gig::Region*> RegionGroup;
30 typedef std::map<DLS::range_t,RegionGroup> RegionGroups;
31
32 typedef std::vector<DLS::range_t> DimensionZones;
33 typedef std::map<gig::dimension_t,DimensionZones> Dimensions;
34
35 typedef std::map<gig::dimension_t, int> DimensionRegionUpperLimits;
36
37 typedef std::set<Glib::ustring> Warnings;
38
39 ///////////////////////////////////////////////////////////////////////////
40 // private static data
41
42 static Warnings g_warnings;
43
44 ///////////////////////////////////////////////////////////////////////////
45 // private functions
46
47 #if DEBUG_COMBINE_INSTRUMENTS
48 static void printRanges(const RegionGroups& regions) {
49 std::cout << "{ ";
50 for (RegionGroups::const_iterator it = regions.begin(); it != regions.end(); ++it) {
51 if (it != regions.begin()) std::cout << ", ";
52 std::cout << (int)it->first.low << ".." << (int)it->first.high;
53 }
54 std::cout << " }" << std::flush;
55 }
56 #endif
57
58 /**
59 * Store a warning message that shall be stored and displayed to the user as a
60 * list of warnings after the overall operation has finished. Duplicate warning
61 * messages are automatically eliminated.
62 */
63 inline void addWarning(const char* fmt, ...) {
64 va_list arg;
65 va_start(arg, fmt);
66 const int SZ = 255 + strlen(fmt);
67 char* buf = new char[SZ];
68 vsnprintf(buf, SZ, fmt, arg);
69 Glib::ustring s = buf;
70 delete [] buf;
71 va_end(arg);
72 std::cerr << _("WARNING:") << " " << s << std::endl << std::flush;
73 g_warnings.insert(s);
74 }
75
76 /**
77 * If the two ranges overlap, then this function returns the smallest point
78 * within that overlapping zone. If the two ranges do not overlap, then this
79 * function will return -1 instead.
80 */
81 inline int smallestOverlapPoint(const DLS::range_t& r1, const DLS::range_t& r2) {
82 if (r1.overlaps(r2.low)) return r2.low;
83 if (r2.overlaps(r1.low)) return r1.low;
84 return -1;
85 }
86
87 /**
88 * Get the most smallest region point (not necessarily its region start point)
89 * of all regions of the given instruments, start searching at keyboard
90 * position @a iStart.
91 *
92 * @returns very first region point >= iStart, or -1 if no region could be
93 * found with a range member point >= iStart
94 */
95 static int findLowestRegionPoint(std::vector<gig::Instrument*>& instruments, int iStart) {
96 DLS::range_t searchRange = { uint16_t(iStart), 127 };
97 int result = -1;
98 for (uint i = 0; i < instruments.size(); ++i) {
99 gig::Instrument* instr = instruments[i];
100 for (gig::Region* rgn = instr->GetFirstRegion(); rgn; rgn = instr->GetNextRegion()) {
101 if (rgn->KeyRange.overlaps(searchRange)) {
102 int lowest = smallestOverlapPoint(rgn->KeyRange, searchRange);
103 if (result == -1 || lowest < result) result = lowest;
104 }
105 }
106 }
107 return result;
108 }
109
110 /**
111 * Get the most smallest region end of all regions of the given instruments,
112 * start searching at keyboard position @a iStart.
113 *
114 * @returns very first region end >= iStart, or -1 if no region could be found
115 * with a range end >= iStart
116 */
117 static int findFirstRegionEnd(std::vector<gig::Instrument*>& instruments, int iStart) {
118 DLS::range_t searchRange = { uint16_t(iStart), 127 };
119 int result = -1;
120 for (uint i = 0; i < instruments.size(); ++i) {
121 gig::Instrument* instr = instruments[i];
122 for (gig::Region* rgn = instr->GetFirstRegion(); rgn; rgn = instr->GetNextRegion()) {
123 if (rgn->KeyRange.overlaps(searchRange)) {
124 if (result == -1 || rgn->KeyRange.high < result)
125 result = rgn->KeyRange.high;
126 }
127 }
128 }
129 return result;
130 }
131
132 /**
133 * Returns a list of all regions of the given @a instrument where the respective
134 * region's key range overlaps the given @a range.
135 */
136 static std::vector<gig::Region*> getAllRegionsWhichOverlapRange(gig::Instrument* instrument, DLS::range_t range) {
137 //std::cout << "All regions which overlap { " << (int)range.low << ".." << (int)range.high << " } : " << std::flush;
138 std::vector<gig::Region*> v;
139 for (gig::Region* rgn = instrument->GetFirstRegion(); rgn; rgn = instrument->GetNextRegion()) {
140 if (rgn->KeyRange.overlaps(range)) {
141 v.push_back(rgn);
142 //std::cout << (int)rgn->KeyRange.low << ".." << (int)rgn->KeyRange.high << ", " << std::flush;
143 }
144 }
145 //std::cout << " END." << std::endl;
146 return v;
147 }
148
149 /**
150 * Returns all regions of the given @a instruments where the respective region's
151 * key range overlaps the given @a range. The regions returned are ordered (in a
152 * map) by their instrument pointer.
153 */
154 static RegionGroup getAllRegionsWhichOverlapRange(std::vector<gig::Instrument*>& instruments, DLS::range_t range) {
155 RegionGroup group;
156 for (uint i = 0; i < instruments.size(); ++i) {
157 gig::Instrument* instr = instruments[i];
158 std::vector<gig::Region*> v = getAllRegionsWhichOverlapRange(instr, range);
159 if (v.empty()) continue;
160 if (v.size() > 1) {
161 addWarning("More than one region found!");
162 }
163 group[instr] = v[0];
164 }
165 return group;
166 }
167
168 /** @brief Identify required regions.
169 *
170 * Takes a list of @a instruments as argument (which are planned to be combined
171 * as separate dimension zones of a certain dimension into one single new
172 * instrument) and fulfills the following tasks:
173 *
174 * - 1. Identification of total amount of regions required to create a new
175 * instrument to become a combined version of the given instruments.
176 * - 2. Precise key range of each of those identified required regions to be
177 * created in that new instrument.
178 * - 3. Grouping the original source regions of the given original instruments
179 * to the respective target key range (new region) of the instrument to be
180 * created.
181 *
182 * @param instruments - list of instruments that are planned to be combined
183 * @returns structured result of the tasks described above
184 */
185 static RegionGroups groupByRegionIntersections(std::vector<gig::Instrument*>& instruments) {
186 RegionGroups groups;
187
188 // find all region intersections of all instruments
189 std::vector<DLS::range_t> intersections;
190 for (int iStart = 0; iStart <= 127; ) {
191 iStart = findLowestRegionPoint(instruments, iStart);
192 if (iStart < 0) break;
193 const int iEnd = findFirstRegionEnd(instruments, iStart);
194 DLS::range_t range = { uint16_t(iStart), uint16_t(iEnd) };
195 intersections.push_back(range);
196 iStart = iEnd + 1;
197 }
198
199 // now sort all regions to those found intersections
200 for (uint i = 0; i < intersections.size(); ++i) {
201 const DLS::range_t& range = intersections[i];
202 RegionGroup group = getAllRegionsWhichOverlapRange(instruments, range);
203 if (!group.empty())
204 groups[range] = group;
205 else
206 addWarning("Empty region group!");
207 }
208
209 return groups;
210 }
211
212 /** @brief Identify required dimensions.
213 *
214 * Takes a planned new region (@a regionGroup) as argument and identifies which
215 * precise dimensions would have to be created for that new region, along with
216 * the amount of dimension zones and their precise individual zone sizes.
217 *
218 * @param regionGroup - planned new region for a new instrument
219 * @returns set of dimensions that shall be created for the given planned region
220 */
221 static Dimensions getDimensionsForRegionGroup(RegionGroup& regionGroup) {
222 std::map<gig::dimension_t, std::set<int> > dimUpperLimits;
223
224 // collect all dimension region zones' upper limits
225 for (RegionGroup::iterator it = regionGroup.begin();
226 it != regionGroup.end(); ++it)
227 {
228 gig::Region* rgn = it->second;
229 int previousBits = 0;
230 for (uint d = 0; d < rgn->Dimensions; ++d) {
231 const gig::dimension_def_t& def = rgn->pDimensionDefinitions[d];
232 for (uint z = 0; z < def.zones; ++z) {
233 int dr = z << previousBits;
234 gig::DimensionRegion* dimRgn = rgn->pDimensionRegions[dr];
235 // Store the individual dimension zone sizes (or actually their
236 // upper limits here) for each dimension.
237 // HACK: Note that the velocity dimension is specially handled
238 // here. Instead of taking over custom velocity split sizes
239 // here, only a bogus number (zone index number) is stored for
240 // each velocity zone, that way only the maxiumum amount of
241 // velocity splits of all regions is stored here, and when their
242 // individual DimensionRegions are finally copied (later), the
243 // individual velocity split size are copied by that.
244 dimUpperLimits[def.dimension].insert(
245 (def.dimension == gig::dimension_velocity) ?
246 z : (def.split_type == gig::split_type_bit) ?
247 ((z+1) * 128/def.zones - 1) : dimRgn->DimensionUpperLimits[dr]
248 );
249 }
250 previousBits += def.bits;
251 }
252 }
253
254 // convert upper limit set to range vector
255 Dimensions dims;
256 for (std::map<gig::dimension_t, std::set<int> >::const_iterator it = dimUpperLimits.begin();
257 it != dimUpperLimits.end(); ++it)
258 {
259 gig::dimension_t type = it->first;
260 int iLow = 0;
261 for (std::set<int>::const_iterator itNums = it->second.begin();
262 itNums != it->second.end(); ++itNums)
263 {
264 const int iUpperLimit = *itNums;
265 DLS::range_t range = { uint16_t(iLow), uint16_t(iUpperLimit) };
266 dims[type].push_back(range);
267 iLow = iUpperLimit + 1;
268 }
269 }
270
271 return dims;
272 }
273
274 static void fillDimValues(uint* values/*[8]*/, DimensionCase dimCase, gig::Region* rgn, bool bShouldHaveAllDimensionsPassed) {
275 #if DEBUG_COMBINE_INSTRUMENTS
276 printf("dimvalues = { ");
277 fflush(stdout);
278 #endif
279 for (DimensionCase::iterator it = dimCase.begin(); it != dimCase.end(); ++it) {
280 gig::dimension_t type = it->first;
281 int iDimIndex = getDimensionIndex(type, rgn);
282 if (bShouldHaveAllDimensionsPassed) assert(iDimIndex >= 0);
283 else if (iDimIndex < 0) continue;
284 values[iDimIndex] = it->second;
285 #if DEBUG_COMBINE_INSTRUMENTS
286 printf("%x=%d, ", type, it->second);
287 #endif
288 }
289 #if DEBUG_COMBINE_INSTRUMENTS
290 printf("}\n");
291 #endif
292 }
293
294 static DimensionRegionUpperLimits getDimensionRegionUpperLimits(gig::DimensionRegion* dimRgn) {
295 DimensionRegionUpperLimits limits;
296 gig::Region* rgn = dimRgn->GetParent();
297 for (uint d = 0; d < rgn->Dimensions; ++d) {
298 const gig::dimension_def_t& def = rgn->pDimensionDefinitions[d];
299 limits[def.dimension] = dimRgn->DimensionUpperLimits[d];
300 }
301 return limits;
302 }
303
304 static void restoreDimensionRegionUpperLimits(gig::DimensionRegion* dimRgn, const DimensionRegionUpperLimits& limits) {
305 gig::Region* rgn = dimRgn->GetParent();
306 for (DimensionRegionUpperLimits::const_iterator it = limits.begin();
307 it != limits.end(); ++it)
308 {
309 int index = getDimensionIndex(it->first, rgn);
310 assert(index >= 0);
311 dimRgn->DimensionUpperLimits[index] = it->second;
312 }
313 }
314
315 inline int dimensionRegionIndex(gig::DimensionRegion* dimRgn) {
316 gig::Region* rgn = dimRgn->GetParent();
317 int sz = sizeof(rgn->pDimensionRegions) / sizeof(gig::DimensionRegion*);
318 for (int i = 0; i < sz; ++i)
319 if (rgn->pDimensionRegions[i] == dimRgn)
320 return i;
321 return -1;
322 }
323
324 /** @brief Get exact zone ranges of given dimension.
325 *
326 * This function is useful for the velocity type dimension. In contrast to other
327 * dimension types, this dimension can have different zone ranges (that is
328 * different individual start and end points of its dimension zones) depending
329 * on which zones of other dimensions (on that gig::Region) are currently
330 * selected.
331 *
332 * @param type - dimension where the zone ranges should be retrieved for
333 * (usually the velocity dimension in this context)
334 * @param dimRgn - reflects the exact cases (zone selections) of all other
335 * dimensions than the given one in question
336 * @returns individual ranges for each zone of the questioned dimension type,
337 * it returns an empty result on errors instead
338 */
339 static DimensionZones preciseDimensionZonesFor(gig::dimension_t type, gig::DimensionRegion* dimRgn) {
340 DimensionZones zones;
341 gig::Region* rgn = dimRgn->GetParent();
342 int iDimension = getDimensionIndex(type, rgn);
343 if (iDimension < 0) return zones;
344 const gig::dimension_def_t& def = rgn->pDimensionDefinitions[iDimension];
345 int iDimRgn = dimensionRegionIndex(dimRgn);
346 int iBaseBits = baseBits(type, rgn);
347 assert(iBaseBits >= 0);
348 int mask = ~(((1 << def.bits) - 1) << iBaseBits);
349
350 #if DEBUG_COMBINE_INSTRUMENTS
351 printf("velo zones { ");
352 fflush(stdout);
353 #endif
354 int iLow = 0;
355 for (int z = 0; z < def.zones; ++z) {
356 gig::DimensionRegion* dimRgn2 =
357 rgn->pDimensionRegions[ (iDimRgn & mask) | ( z << iBaseBits) ];
358 int iHigh = dimRgn2->DimensionUpperLimits[iDimension];
359 DLS::range_t range = { uint16_t(iLow), uint16_t(iHigh) };
360 #if DEBUG_COMBINE_INSTRUMENTS
361 printf("%d..%d, ", iLow, iHigh);
362 fflush(stdout);
363 #endif
364 zones.push_back(range);
365 iLow = iHigh + 1;
366 }
367 #if DEBUG_COMBINE_INSTRUMENTS
368 printf("}\n");
369 #endif
370 return zones;
371 }
372
373 struct CopyAssignSchedEntry {
374 gig::DimensionRegion* src;
375 gig::DimensionRegion* dst;
376 int velocityZone;
377 int totalSrcVelocityZones;
378 };
379 typedef std::vector<CopyAssignSchedEntry> CopyAssignSchedule;
380
381 /** @brief Schedule copying DimensionRegions from source Region to target Region.
382 *
383 * Schedules copying the entire articulation informations (including sample
384 * reference) from all individual DimensionRegions of source Region @a inRgn to
385 * target Region @a outRgn. It is expected that the required dimensions (thus
386 * the required dimension regions) were already created before calling this
387 * function.
388 *
389 * To be precise, it does the task above only for the dimension zones defined by
390 * the three arguments @a mainDim, @a iSrcMainBit, @a iDstMainBit, which reflect
391 * a selection which dimension zones shall be copied. All other dimension zones
392 * will not be scheduled to be copied by a single call of this function. So this
393 * function needs to be called several time in case all dimension regions shall
394 * be copied of the entire region (@a inRgn, @a outRgn).
395 *
396 * @param outRgn - where the dimension regions shall be copied to
397 * @param inRgn - all dimension regions that shall be copied from
398 * @param dims - precise dimension definitions of target region
399 * @param mainDim - this dimension type, in combination with @a iSrcMainBit and
400 * @a iDstMainBit defines a selection which dimension region
401 * zones shall be copied by this call of this function
402 * @param iDstMainBit - destination bit of @a mainDim
403 * @param iSrcMainBit - source bit of @a mainDim
404 * @param schedule - list of all DimensionRegion copy operations which is filled
405 * during the nested loops / recursions of this function call
406 * @param dimCase - just for internal purpose (function recursion), don't pass
407 * anything here, this function will call itself recursively
408 * will fill this container with concrete dimension values for
409 * selecting the precise dimension regions during its task
410 */
411 static void scheduleCopyDimensionRegions(gig::Region* outRgn, gig::Region* inRgn,
412 Dimensions dims, gig::dimension_t mainDim,
413 int iDstMainBit, int iSrcMainBit,
414 CopyAssignSchedule* schedule,
415 DimensionCase dimCase = DimensionCase())
416 {
417 if (dims.empty()) { // reached deepest level of function recursion ...
418 CopyAssignSchedEntry e;
419
420 // resolve the respective source & destination DimensionRegion ...
421 uint srcDimValues[8] = {};
422 uint dstDimValues[8] = {};
423 DimensionCase srcDimCase = dimCase;
424 DimensionCase dstDimCase = dimCase;
425 srcDimCase[mainDim] = iSrcMainBit;
426 dstDimCase[mainDim] = iDstMainBit;
427
428 #if DEBUG_COMBINE_INSTRUMENTS
429 printf("-------------------------------\n");
430 printf("iDstMainBit=%d iSrcMainBit=%d\n", iDstMainBit, iSrcMainBit);
431 #endif
432
433 // first select source & target dimension region with an arbitrary
434 // velocity split zone, to get access to the precise individual velocity
435 // split zone sizes (if there is actually a velocity dimension at all,
436 // otherwise we already select the desired source & target dimension
437 // region here)
438 #if DEBUG_COMBINE_INSTRUMENTS
439 printf("src "); fflush(stdout);
440 #endif
441 fillDimValues(srcDimValues, srcDimCase, inRgn, false);
442 #if DEBUG_COMBINE_INSTRUMENTS
443 printf("dst "); fflush(stdout);
444 #endif
445 fillDimValues(dstDimValues, dstDimCase, outRgn, false);
446 gig::DimensionRegion* srcDimRgn = inRgn->GetDimensionRegionByValue(srcDimValues);
447 gig::DimensionRegion* dstDimRgn = outRgn->GetDimensionRegionByValue(dstDimValues);
448 #if DEBUG_COMBINE_INSTRUMENTS
449 printf("iDstMainBit=%d iSrcMainBit=%d\n", iDstMainBit, iSrcMainBit);
450 printf("srcDimRgn=%lx dstDimRgn=%lx\n", (uint64_t)srcDimRgn, (uint64_t)dstDimRgn);
451 printf("srcSample='%s' dstSample='%s'\n",
452 (!srcDimRgn->pSample ? "NULL" : srcDimRgn->pSample->pInfo->Name.c_str()),
453 (!dstDimRgn->pSample ? "NULL" : dstDimRgn->pSample->pInfo->Name.c_str())
454 );
455 #endif
456
457 assert(srcDimRgn->GetParent() == inRgn);
458 assert(dstDimRgn->GetParent() == outRgn);
459
460 // now that we have access to the precise velocity split zone upper
461 // limits, we can select the actual source & destination dimension
462 // regions we need to copy (assuming that source or target region has
463 // a velocity dimension)
464 if (outRgn->GetDimensionDefinition(gig::dimension_velocity)) {
465 // re-select target dimension region (with correct velocity zone)
466 DimensionZones dstZones = preciseDimensionZonesFor(gig::dimension_velocity, dstDimRgn);
467 assert(dstZones.size() > 1);
468 const int iDstZoneIndex =
469 (mainDim == gig::dimension_velocity)
470 ? iDstMainBit : dstDimCase[gig::dimension_velocity]; // (mainDim == gig::dimension_velocity) exception case probably unnecessary here
471 e.velocityZone = iDstZoneIndex;
472 #if DEBUG_COMBINE_INSTRUMENTS
473 printf("dst velocity zone: %d/%d\n", iDstZoneIndex, (int)dstZones.size());
474 #endif
475 assert(uint(iDstZoneIndex) < dstZones.size());
476 dstDimCase[gig::dimension_velocity] = dstZones[iDstZoneIndex].low; // arbitrary value between low and high
477 #if DEBUG_COMBINE_INSTRUMENTS
478 printf("dst velocity value = %d\n", dstDimCase[gig::dimension_velocity]);
479 printf("dst refilled "); fflush(stdout);
480 #endif
481 fillDimValues(dstDimValues, dstDimCase, outRgn, false);
482 dstDimRgn = outRgn->GetDimensionRegionByValue(dstDimValues);
483 #if DEBUG_COMBINE_INSTRUMENTS
484 printf("reselected dstDimRgn=%lx\n", (uint64_t)dstDimRgn);
485 printf("dstSample='%s'%s\n",
486 (!dstDimRgn->pSample ? "NULL" : dstDimRgn->pSample->pInfo->Name.c_str()),
487 (dstDimRgn->pSample ? " <--- ERROR ERROR ERROR !!!!!!!!! " : "")
488 );
489 #endif
490
491 // re-select source dimension region with correct velocity zone
492 // (if it has a velocity dimension that is)
493 if (inRgn->GetDimensionDefinition(gig::dimension_velocity)) {
494 DimensionZones srcZones = preciseDimensionZonesFor(gig::dimension_velocity, srcDimRgn);
495 e.totalSrcVelocityZones = srcZones.size();
496 assert(srcZones.size() > 0);
497 if (srcZones.size() <= 1) {
498 addWarning("Input region has a velocity dimension with only ONE zone!");
499 }
500 int iSrcZoneIndex =
501 (mainDim == gig::dimension_velocity)
502 ? iSrcMainBit : iDstZoneIndex;
503 if (uint(iSrcZoneIndex) >= srcZones.size())
504 iSrcZoneIndex = srcZones.size() - 1;
505 srcDimCase[gig::dimension_velocity] = srcZones[iSrcZoneIndex].low; // same zone as used above for target dimension region (no matter what the precise zone ranges are)
506 #if DEBUG_COMBINE_INSTRUMENTS
507 printf("src refilled "); fflush(stdout);
508 #endif
509 fillDimValues(srcDimValues, srcDimCase, inRgn, false);
510 srcDimRgn = inRgn->GetDimensionRegionByValue(srcDimValues);
511 #if DEBUG_COMBINE_INSTRUMENTS
512 printf("reselected srcDimRgn=%lx\n", (uint64_t)srcDimRgn);
513 printf("srcSample='%s'\n",
514 (!srcDimRgn->pSample ? "NULL" : srcDimRgn->pSample->pInfo->Name.c_str())
515 );
516 #endif
517 }
518 }
519
520 // Schedule copy operation of source -> target DimensionRegion for the
521 // time after all nested loops have been traversed. We have to postpone
522 // the actual copy operations this way, because otherwise it would
523 // overwrite informations inside the destination DimensionRegion object
524 // that we need to read in the code block above.
525 e.src = srcDimRgn;
526 e.dst = dstDimRgn;
527 schedule->push_back(e);
528
529 return; // returning from deepest level of function recursion
530 }
531
532 // Copying n dimensions requires n nested loops. That's why this function
533 // is calling itself recursively to provide the required amount of nested
534 // loops. With each call it pops from argument 'dims' and pushes to
535 // argument 'dimCase'.
536
537 Dimensions::iterator itDimension = dims.begin();
538 gig::dimension_t type = itDimension->first;
539 DimensionZones zones = itDimension->second;
540 dims.erase(itDimension);
541
542 int iZone = 0;
543 for (DimensionZones::iterator itZone = zones.begin();
544 itZone != zones.end(); ++itZone, ++iZone)
545 {
546 DLS::range_t zoneRange = *itZone;
547 gig::dimension_def_t* def = outRgn->GetDimensionDefinition(type);
548 dimCase[type] = (def->split_type == gig::split_type_bit) ? iZone : zoneRange.low;
549
550 // recurse until 'dims' is exhausted (and dimCase filled up with concrete value)
551 scheduleCopyDimensionRegions(outRgn, inRgn, dims, mainDim, iDstMainBit, iSrcMainBit, schedule, dimCase);
552 }
553 }
554
555 static OrderedRegionGroup sortRegionGroup(const RegionGroup& group, const std::vector<gig::Instrument*>& instruments) {
556 OrderedRegionGroup result;
557 for (std::vector<gig::Instrument*>::const_iterator it = instruments.begin();
558 it != instruments.end(); ++it)
559 {
560 RegionGroup::const_iterator itRgn = group.find(*it);
561 if (itRgn == group.end()) continue;
562 result.push_back(
563 std::pair<gig::Instrument*, gig::Region*>(
564 itRgn->first, itRgn->second
565 )
566 );
567 }
568 return result;
569 }
570
571 /** @brief Combine given list of instruments to one instrument.
572 *
573 * Takes a list of @a instruments as argument and combines them to one single
574 * new @a output instrument. For this task, it will create a dimension of type
575 * given by @a mainDimension in the new instrument and copies the source
576 * instruments to those dimension zones.
577 *
578 * @param instruments - (input) list of instruments that shall be combined,
579 * they will only be read, so they will be left untouched
580 * @param gig - (input/output) .gig file where the new combined instrument shall
581 * be created
582 * @param output - (output) on success this pointer will be set to the new
583 * instrument being created
584 * @param mainDimension - the dimension that shall be used to combine the
585 * instruments
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, gig::dimension_t mainDimension) {
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 #if DEBUG_COMBINE_INSTRUMENTS
622 printf("---> Start target region %d..%d\n", itGroup->first.low, itGroup->first.high);
623 #endif
624
625 // detect the total amount of zones required for the given main
626 // dimension to build up this combi for current key range
627 int iTotalZones = 0;
628 for (RegionGroup::iterator itRgn = itGroup->second.begin();
629 itRgn != itGroup->second.end(); ++itRgn)
630 {
631 gig::Region* inRgn = itRgn->second;
632 gig::dimension_def_t* def = inRgn->GetDimensionDefinition(mainDimension);
633 iTotalZones += (def) ? def->zones : 1;
634 }
635 #if DEBUG_COMBINE_INSTRUMENTS
636 printf("Required total zones: %d, vertical regions: %d\n", iTotalZones, itGroup->second.size());
637 #endif
638
639 // create all required dimensions for this output region
640 // (except the main dimension used for separating the individual
641 // instruments, we create that particular dimension as next step)
642 Dimensions dims = getDimensionsForRegionGroup(itGroup->second);
643 // the given main dimension which is used to combine the instruments is
644 // created separately after the next code block, and the main dimension
645 // should not be part of dims here, because it also used for iterating
646 // all dimensions zones, which would lead to this dimensions being
647 // iterated twice
648 dims.erase(mainDimension);
649 {
650 std::vector<gig::dimension_t> skipTheseDimensions; // used to prevent a misbehavior (i.e. crash) of the combine algorithm in case one of the source instruments has a dimension with only one zone, which is not standard conform
651
652 for (Dimensions::iterator itDim = dims.begin();
653 itDim != dims.end(); ++itDim)
654 {
655 gig::dimension_def_t def;
656 def.dimension = itDim->first; // dimension type
657 def.zones = itDim->second.size();
658 def.bits = zoneCountToBits(def.zones);
659 if (def.zones < 2) {
660 addWarning(
661 "Attempt to create dimension with type=0x%x with only "
662 "ONE zone (because at least one of the source "
663 "instruments seems to have such a velocity dimension "
664 "with only ONE zone, which is odd)! Skipping this "
665 "dimension for now.",
666 (int)itDim->first
667 );
668 skipTheseDimensions.push_back(itDim->first);
669 continue;
670 }
671 #if DEBUG_COMBINE_INSTRUMENTS
672 std::cout << "Adding new regular dimension type=" << std::hex << (int)def.dimension << std::dec << ", zones=" << (int)def.zones << ", bits=" << (int)def.bits << " ... " << std::flush;
673 #endif
674 outRgn->AddDimension(&def);
675 #if DEBUG_COMBINE_INSTRUMENTS
676 std::cout << "OK" << std::endl << std::flush;
677 #endif
678 }
679 // prevent the following dimensions to be processed further below
680 // (since the respective dimension was not created above)
681 for (int i = 0; i < skipTheseDimensions.size(); ++i)
682 dims.erase(skipTheseDimensions[i]);
683 }
684
685 // create the main dimension (if necessary for current key range)
686 if (iTotalZones > 1) {
687 gig::dimension_def_t def;
688 def.dimension = mainDimension; // dimension type
689 def.zones = iTotalZones;
690 def.bits = zoneCountToBits(def.zones);
691 #if DEBUG_COMBINE_INSTRUMENTS
692 std::cout << "Adding new main combi dimension type=" << std::hex << (int)def.dimension << std::dec << ", zones=" << (int)def.zones << ", bits=" << (int)def.bits << " ... " << std::flush;
693 #endif
694 outRgn->AddDimension(&def);
695 #if DEBUG_COMBINE_INSTRUMENTS
696 std::cout << "OK" << std::endl << std::flush;
697 #endif
698 } else {
699 dims.erase(mainDimension);
700 }
701
702 // for the next task we need to have the current RegionGroup to be
703 // sorted by instrument in the same sequence as the 'instruments' vector
704 // argument passed to this function (because the std::map behind the
705 // 'RegionGroup' type sorts by memory address instead, and that would
706 // sometimes lead to the source instruments' region to be sorted into
707 // the wrong target layer)
708 OrderedRegionGroup currentGroup = sortRegionGroup(itGroup->second, instruments);
709
710 // schedule copying the source dimension regions to the target dimension
711 // regions
712 CopyAssignSchedule schedule;
713 int iDstMainBit = 0;
714 for (OrderedRegionGroup::iterator itRgn = currentGroup.begin();
715 itRgn != currentGroup.end(); ++itRgn) // iterate over 'vertical' / source regions ...
716 {
717 gig::Region* inRgn = itRgn->second;
718 #if DEBUG_COMBINE_INSTRUMENTS
719 printf("[source region of '%s']\n", inRgn->GetParent()->pInfo->Name.c_str());
720 #endif
721
722 // determine how many main dimension zones this input region requires
723 gig::dimension_def_t* def = inRgn->GetDimensionDefinition(mainDimension);
724 const int inRgnMainZones = (def) ? def->zones : 1;
725
726 for (uint iSrcMainBit = 0; iSrcMainBit < inRgnMainZones; ++iSrcMainBit, ++iDstMainBit) {
727 scheduleCopyDimensionRegions(
728 outRgn, inRgn, dims, mainDimension,
729 iDstMainBit, iSrcMainBit, &schedule
730 );
731 }
732 }
733
734 // finally copy the scheduled source -> target dimension regions
735 for (uint i = 0; i < schedule.size(); ++i) {
736 CopyAssignSchedEntry& e = schedule[i];
737
738 // backup the target DimensionRegion's current dimension zones upper
739 // limits (because the target DimensionRegion's upper limits are
740 // already defined correctly since calling AddDimension(), and the
741 // CopyAssign() call next, will overwrite those upper limits
742 // unfortunately
743 DimensionRegionUpperLimits dstUpperLimits = getDimensionRegionUpperLimits(e.dst);
744 DimensionRegionUpperLimits srcUpperLimits = getDimensionRegionUpperLimits(e.src);
745
746 // now actually copy over the current DimensionRegion
747 const gig::Region* const origRgn = e.dst->GetParent(); // just for sanity check below
748 e.dst->CopyAssign(e.src);
749 assert(origRgn == e.dst->GetParent()); // if gigedit is crashing here, then you must update libgig (to at least SVN r2547, v3.3.0.svn10)
750
751 // restore all original dimension zone upper limits except of the
752 // velocity dimension, because the velocity dimension zone sizes are
753 // allowed to differ for individual DimensionRegions in gig v3
754 // format
755 //
756 // if the main dinension is the 'velocity' dimension, then skip
757 // restoring the source's original velocity zone limits, because
758 // dealing with merging that is not implemented yet
759 // TODO: merge custom velocity splits if main dimension is the velocity dimension (for now equal sized velocity zones are used if mainDim is 'velocity')
760 if (srcUpperLimits.count(gig::dimension_velocity) && mainDimension != gig::dimension_velocity) {
761 if (!dstUpperLimits.count(gig::dimension_velocity)) {
762 addWarning("Source instrument seems to have a velocity dimension whereas new target instrument doesn't!");
763 } else {
764 dstUpperLimits[gig::dimension_velocity] =
765 (e.velocityZone >= e.totalSrcVelocityZones)
766 ? 127 : srcUpperLimits[gig::dimension_velocity];
767 }
768 }
769 restoreDimensionRegionUpperLimits(e.dst, dstUpperLimits);
770 }
771 }
772
773 // success
774 output = outInstr;
775 }
776
777 ///////////////////////////////////////////////////////////////////////////
778 // class 'CombineInstrumentsDialog'
779
780 CombineInstrumentsDialog::CombineInstrumentsDialog(Gtk::Window& parent, gig::File* gig)
781 : ManagedDialog(_("Combine Instruments"), parent, true),
782 m_gig(gig), m_fileWasChanged(false), m_newCombinedInstrument(NULL),
783 m_cancelButton(_("_Cancel"), true), m_OKButton(_("_OK"), true),
784 m_descriptionLabel(), m_tableDimCombo(2, 2), m_comboDimType(),
785 m_labelDimType(Glib::ustring(_("Combine by Dimension:")) + " ", Gtk::ALIGN_END)
786 {
787 m_scrolledWindow.add(m_treeView);
788 m_scrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
789
790 get_vbox()->pack_start(m_descriptionLabel, Gtk::PACK_SHRINK);
791 get_vbox()->pack_start(m_tableDimCombo, Gtk::PACK_SHRINK);
792 get_vbox()->pack_start(m_scrolledWindow);
793 get_vbox()->pack_start(m_buttonBox, Gtk::PACK_SHRINK);
794
795 #if GTKMM_MAJOR_VERSION >= 3
796 m_descriptionLabel.set_line_wrap();
797 #endif
798 m_descriptionLabel.set_text(_(
799 "Select at least two instruments below that shall be combined (as "
800 "separate dimension zones of the selected dimension type) as a new "
801 "instrument. The original instruments remain untouched.\n\n"
802 "You may use this tool for example to combine solo instruments into "
803 "a combi sound arrangement by selecting the 'layer' dimension, or you "
804 "might combine similar sounding solo sounds into separate velocity "
805 "split layers by using the 'velocity' dimension, and so on."
806 ));
807
808 // add dimension type combo box
809 {
810 int iLayerDimIndex = -1;
811 Glib::RefPtr<Gtk::ListStore> refComboModel = Gtk::ListStore::create(m_comboDimsModel);
812 for (int i = 0x01, iRow = 0; i < 0xff; i++) {
813 Glib::ustring sType =
814 dimTypeAsString(static_cast<gig::dimension_t>(i));
815 if (sType.find("Unknown") != 0) {
816 Gtk::TreeModel::Row row = *(refComboModel->append());
817 row[m_comboDimsModel.m_type_id] = i;
818 row[m_comboDimsModel.m_type_name] = sType;
819 if (i == gig::dimension_layer) iLayerDimIndex = iRow;
820 iRow++;
821 }
822 }
823 m_comboDimType.set_model(refComboModel);
824 m_comboDimType.pack_start(m_comboDimsModel.m_type_id);
825 m_comboDimType.pack_start(m_comboDimsModel.m_type_name);
826 m_tableDimCombo.attach(m_labelDimType, 0, 1, 0, 1);
827 m_tableDimCombo.attach(m_comboDimType, 1, 2, 0, 1);
828 m_comboDimType.set_active(iLayerDimIndex); // preselect "layer" dimension
829 }
830
831 m_refTreeModel = Gtk::ListStore::create(m_columns);
832 m_treeView.set_model(m_refTreeModel);
833 m_treeView.set_tooltip_text(_(
834 "Use SHIFT + left click or CTRL + left click to select the instruments "
835 "you want to combine."
836 ));
837 m_treeView.append_column("Instrument", m_columns.m_col_name);
838 m_treeView.set_headers_visible(false);
839 m_treeView.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
840 m_treeView.get_selection()->signal_changed().connect(
841 sigc::mem_fun(*this, &CombineInstrumentsDialog::onSelectionChanged)
842 );
843 m_treeView.show();
844
845 for (int i = 0; true; ++i) {
846 gig::Instrument* instr = gig->GetInstrument(i);
847 if (!instr) break;
848
849 #if DEBUG_COMBINE_INSTRUMENTS
850 {
851 std::cout << "Instrument (" << i << ") '" << instr->pInfo->Name << "' Regions: " << std::flush;
852 for (gig::Region* rgn = instr->GetFirstRegion(); rgn; rgn = instr->GetNextRegion()) {
853 std::cout << rgn->KeyRange.low << ".." << rgn->KeyRange.high << ", " << std::flush;
854 }
855 std::cout << std::endl;
856 }
857 std::cout << std::endl;
858 #endif
859
860 Glib::ustring name(gig_to_utf8(instr->pInfo->Name));
861 Gtk::TreeModel::iterator iter = m_refTreeModel->append();
862 Gtk::TreeModel::Row row = *iter;
863 row[m_columns.m_col_name] = name;
864 row[m_columns.m_col_instr] = instr;
865 }
866
867 m_buttonBox.set_layout(Gtk::BUTTONBOX_END);
868 m_buttonBox.set_border_width(5);
869 m_buttonBox.pack_start(m_cancelButton, Gtk::PACK_SHRINK);
870 m_buttonBox.pack_start(m_OKButton, Gtk::PACK_SHRINK);
871 m_buttonBox.show();
872
873 m_cancelButton.show();
874 m_OKButton.set_sensitive(false);
875 m_OKButton.show();
876
877 m_cancelButton.signal_clicked().connect(
878 sigc::mem_fun(*this, &CombineInstrumentsDialog::hide)
879 );
880
881 m_OKButton.signal_clicked().connect(
882 sigc::mem_fun(*this, &CombineInstrumentsDialog::combineSelectedInstruments)
883 );
884
885 show_all_children();
886
887 // show a warning to user if he uses a .gig in v2 format
888 if (gig->pVersion->major < 3) {
889 Glib::ustring txt = _(
890 "You are currently using a .gig file in old v2 format. The current "
891 "combine algorithm will most probably fail trying to combine "
892 "instruments in this old format. So better save the file in new v3 "
893 "format before trying to combine your instruments."
894 );
895 Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_WARNING);
896 msg.run();
897 }
898 }
899
900 void CombineInstrumentsDialog::combineSelectedInstruments() {
901 std::vector<gig::Instrument*> instruments;
902 std::vector<Gtk::TreeModel::Path> v = m_treeView.get_selection()->get_selected_rows();
903 for (uint i = 0; i < v.size(); ++i) {
904 Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(v[i]);
905 Gtk::TreeModel::Row row = *it;
906 Glib::ustring name = row[m_columns.m_col_name];
907 gig::Instrument* instrument = row[m_columns.m_col_instr];
908 #if DEBUG_COMBINE_INSTRUMENTS
909 printf("Selection '%s' 0x%lx\n\n", name.c_str(), int64_t((void*)instrument));
910 #endif
911 instruments.push_back(instrument);
912 }
913
914 g_warnings.clear();
915
916 try {
917 // which main dimension was selected in the combo box?
918 gig::dimension_t mainDimension;
919 {
920 Gtk::TreeModel::iterator iterType = m_comboDimType.get_active();
921 if (!iterType) throw gig::Exception("No dimension selected");
922 Gtk::TreeModel::Row rowType = *iterType;
923 if (!rowType) throw gig::Exception("Something is wrong regarding dimension selection");
924 int iTypeID = rowType[m_comboDimsModel.m_type_id];
925 mainDimension = static_cast<gig::dimension_t>(iTypeID);
926 }
927
928 // now start the actual cobination task ...
929 combineInstruments(instruments, m_gig, m_newCombinedInstrument, mainDimension);
930 } catch (RIFF::Exception e) {;
931 Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);
932 msg.run();
933 return;
934 } catch (...) {
935 Glib::ustring txt = _("An unknown exception occurred!");
936 Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
937 msg.run();
938 return;
939 }
940
941 if (!g_warnings.empty()) {
942 Glib::ustring txt = _(
943 "Combined instrument was created successfully, but there were warnings:"
944 );
945 txt += "\n\n";
946 for (Warnings::const_iterator itWarn = g_warnings.begin();
947 itWarn != g_warnings.end(); ++itWarn)
948 {
949 txt += "-> " + *itWarn + "\n";
950 }
951 txt += "\n";
952 txt += _(
953 "You might also want to check the console for further warnings and "
954 "error messages."
955 );
956 Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_WARNING);
957 msg.run();
958 }
959
960 // no error occurred
961 m_fileWasChanged = true;
962 hide();
963 }
964
965 void CombineInstrumentsDialog::onSelectionChanged() {
966 std::vector<Gtk::TreeModel::Path> v = m_treeView.get_selection()->get_selected_rows();
967 m_OKButton.set_sensitive(v.size() >= 2);
968 }
969
970 bool CombineInstrumentsDialog::fileWasChanged() const {
971 return m_fileWasChanged;
972 }
973
974 gig::Instrument* CombineInstrumentsDialog::newCombinedInstrument() const {
975 return m_newCombinedInstrument;
976 }

  ViewVC Help
Powered by ViewVC