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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2553 - (hide annotations) (download)
Wed May 14 19:57:56 2014 UTC (9 years, 10 months ago) by schoenebeck
File size: 38304 byte(s)
* Added and implemented "Tools" -> "Merge Files..." which can be used
  to merge the content of separate .gig files.

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

  ViewVC Help
Powered by ViewVC