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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 2549 by schoenebeck, Tue May 13 16:14:33 2014 UTC revision 2616 by schoenebeck, Tue Jun 10 20:20:21 2014 UTC
# Line 11  Line 11 
11  #define DEBUG_COMBINE_INSTRUMENTS 0  #define DEBUG_COMBINE_INSTRUMENTS 0
12    
13  #include "global.h"  #include "global.h"
14    #include "compat.h"
15    
16  #include <set>  #include <set>
17  #include <iostream>  #include <iostream>
18  #include <assert.h>  #include <assert.h>
19    #include <stdarg.h>
20    #include <string.h>
21    
22  #include <glibmm/ustring.h>  #include <glibmm/ustring.h>
23  #include <gtkmm/stock.h>  #include <gtkmm/stock.h>
24  #include <gtkmm/messagedialog.h>  #include <gtkmm/messagedialog.h>
25    #include <gtkmm/label.h>
26    
27  Glib::ustring gig_to_utf8(const gig::String& gig_string);  Glib::ustring gig_to_utf8(const gig::String& gig_string);
28    Glib::ustring dimTypeAsString(gig::dimension_t d);
29    
30    typedef std::vector< std::pair<gig::Instrument*, gig::Region*> > OrderedRegionGroup;
31  typedef std::map<gig::Instrument*, gig::Region*> RegionGroup;  typedef std::map<gig::Instrument*, gig::Region*> RegionGroup;
32  typedef std::map<DLS::range_t,RegionGroup> RegionGroups;  typedef std::map<DLS::range_t,RegionGroup> RegionGroups;
33    
# Line 32  typedef std::map<gig::dimension_t,int> D Line 38  typedef std::map<gig::dimension_t,int> D
38    
39  typedef std::map<gig::dimension_t, int> DimensionRegionUpperLimits;  typedef std::map<gig::dimension_t, int> DimensionRegionUpperLimits;
40    
41  typedef std::map<gig::DimensionRegion*, DimensionZones> VelocityZones;  typedef std::set<Glib::ustring> Warnings;
42    
43    ///////////////////////////////////////////////////////////////////////////
44    // private static data
45    
46    static Warnings g_warnings;
47    
48  ///////////////////////////////////////////////////////////////////////////  ///////////////////////////////////////////////////////////////////////////
49  // private functions  // private functions
# Line 49  static void printRanges(const RegionGrou Line 60  static void printRanges(const RegionGrou
60  #endif  #endif
61    
62  /**  /**
63     * Store a warning message that shall be stored and displayed to the user as a
64     * list of warnings after the overall operation has finished. Duplicate warning
65     * messages are automatically eliminated.
66     */
67    inline void addWarning(const char* fmt, ...) {
68        va_list arg;
69        va_start(arg, fmt);
70        const int SZ = 255 + strlen(fmt);
71        char* buf = new char[SZ];
72        vsnprintf(buf, SZ, fmt, arg);
73        Glib::ustring s = buf;
74        delete [] buf;
75        va_end(arg);
76        std::cerr << _("WARNING:") << " " << s << std::endl << std::flush;
77        g_warnings.insert(s);
78    }
79    
80    /**
81   * If the two ranges overlap, then this function returns the smallest point   * If the two ranges overlap, then this function returns the smallest point
82   * within that overlapping zone. If the two ranges do not overlap, then this   * within that overlapping zone. If the two ranges do not overlap, then this
83   * function will return -1 instead.   * function will return -1 instead.
# Line 133  static RegionGroup getAllRegionsWhichOve Line 162  static RegionGroup getAllRegionsWhichOve
162          std::vector<gig::Region*> v = getAllRegionsWhichOverlapRange(instr, range);          std::vector<gig::Region*> v = getAllRegionsWhichOverlapRange(instr, range);
163          if (v.empty()) continue;          if (v.empty()) continue;
164          if (v.size() > 1) {          if (v.size() > 1) {
165              std::cerr << "WARNING: More than one region found!" << std::endl;              addWarning("More than one region found!");
166          }          }
167          group[instr] = v[0];          group[instr] = v[0];
168      }      }
# Line 143  static RegionGroup getAllRegionsWhichOve Line 172  static RegionGroup getAllRegionsWhichOve
172  /** @brief Identify required regions.  /** @brief Identify required regions.
173   *   *
174   * Takes a list of @a instruments as argument (which are planned to be combined   * Takes a list of @a instruments as argument (which are planned to be combined
175   * as layers in one single new instrument) and fulfills the following tasks:   * as separate dimension zones of a certain dimension into one single new
176     * instrument) and fulfills the following tasks:
177   *   *
178   * - 1. Identification of total amount of regions required to create a new   * - 1. Identification of total amount of regions required to create a new
179   *      instrument to become a layered version of the given instruments.   *      instrument to become a combined version of the given instruments.
180   * - 2. Precise key range of each of those identified required regions to be   * - 2. Precise key range of each of those identified required regions to be
181   *      created in that new instrument.   *      created in that new instrument.
182   * - 3. Grouping the original source regions of the given original instruments   * - 3. Grouping the original source regions of the given original instruments
# Line 177  static RegionGroups groupByRegionInterse Line 207  static RegionGroups groupByRegionInterse
207          if (!group.empty())          if (!group.empty())
208              groups[range] = group;              groups[range] = group;
209          else          else
210              std::cerr << "WARNING: empty region group!" << std::endl;              addWarning("Empty region group!");
211      }      }
212    
213      return groups;      return groups;
# Line 253  inline int getDimensionIndex(gig::dimens Line 283  inline int getDimensionIndex(gig::dimens
283  }  }
284    
285  static void fillDimValues(uint* values/*[8]*/, DimensionCase dimCase, gig::Region* rgn, bool bShouldHaveAllDimensionsPassed) {  static void fillDimValues(uint* values/*[8]*/, DimensionCase dimCase, gig::Region* rgn, bool bShouldHaveAllDimensionsPassed) {
286        #if DEBUG_COMBINE_INSTRUMENTS
287        printf("dimvalues = { ");
288        fflush(stdout);
289        #endif
290      for (DimensionCase::iterator it = dimCase.begin(); it != dimCase.end(); ++it) {      for (DimensionCase::iterator it = dimCase.begin(); it != dimCase.end(); ++it) {
291          gig::dimension_t type = it->first;          gig::dimension_t type = it->first;
292          int iDimIndex = getDimensionIndex(type, rgn);          int iDimIndex = getDimensionIndex(type, rgn);
293          if (bShouldHaveAllDimensionsPassed) assert(iDimIndex >= 0);          if (bShouldHaveAllDimensionsPassed) assert(iDimIndex >= 0);
294          else if (iDimIndex < 0) continue;          else if (iDimIndex < 0) continue;
295          values[iDimIndex] = it->second;          values[iDimIndex] = it->second;
296            #if DEBUG_COMBINE_INSTRUMENTS
297            printf("%x=%d, ", type, it->second);
298            #endif
299      }      }
300        #if DEBUG_COMBINE_INSTRUMENTS
301        printf("}\n");
302        #endif
303  }  }
304    
305  static DimensionRegionUpperLimits getDimensionRegionUpperLimits(gig::DimensionRegion* dimRgn) {  static DimensionRegionUpperLimits getDimensionRegionUpperLimits(gig::DimensionRegion* dimRgn) {
# Line 334  static DimensionZones preciseDimensionZo Line 374  static DimensionZones preciseDimensionZo
374      int iBaseBits = baseBits(type, rgn);      int iBaseBits = baseBits(type, rgn);
375      int mask = ~(((1 << def.bits) - 1) << iBaseBits);      int mask = ~(((1 << def.bits) - 1) << iBaseBits);
376    
377        #if DEBUG_COMBINE_INSTRUMENTS
378        printf("velo zones { ");
379        fflush(stdout);
380        #endif
381      int iLow = 0;      int iLow = 0;
382      for (int z = 0; z < def.zones; ++z) {      for (int z = 0; z < def.zones; ++z) {
383          gig::DimensionRegion* dimRgn2 =          gig::DimensionRegion* dimRgn2 =
384              rgn->pDimensionRegions[ (iDimRgn & mask) | ( z << iBaseBits) ];              rgn->pDimensionRegions[ (iDimRgn & mask) | ( z << iBaseBits) ];
385          int iHigh = dimRgn2->DimensionUpperLimits[iDimension];          int iHigh = dimRgn2->DimensionUpperLimits[iDimension];
386          DLS::range_t range = { iLow, iHigh};          DLS::range_t range = { iLow, iHigh};
387            #if DEBUG_COMBINE_INSTRUMENTS
388            printf("%d..%d, ", iLow, iHigh);
389            fflush(stdout);
390            #endif
391          zones.push_back(range);          zones.push_back(range);
392          iLow = iHigh + 1;          iLow = iHigh + 1;
393      }      }
394        #if DEBUG_COMBINE_INSTRUMENTS
395        printf("}\n");
396        #endif
397      return zones;      return zones;
398  }  }
399    
400  static VelocityZones getVelocityZones(gig::Region* rgn) {  struct CopyAssignSchedEntry {
401      VelocityZones zones;      gig::DimensionRegion* src;
402      for (uint i = 0; i < rgn->DimensionRegions; ++i) {      gig::DimensionRegion* dst;
403          gig::DimensionRegion* dimRgn = rgn->pDimensionRegions[i];      int velocityZone;
404          zones[dimRgn] = preciseDimensionZonesFor(gig::dimension_velocity, dimRgn);      int totalSrcVelocityZones;
405      }  };
406      return zones;  typedef std::vector<CopyAssignSchedEntry> CopyAssignSchedule;
407  }  
408    /** @brief Schedule copying DimensionRegions from source Region to target Region.
409  /** @brief Copy all DimensionRegions from source Region to target Region.   *
410   *   * Schedules copying the entire articulation informations (including sample
411   * Copies the entire articulation informations (including sample reference of   * reference) from all individual DimensionRegions of source Region @a inRgn to
412   * course) from all individual DimensionRegions of source Region @a inRgn to   * target Region @a outRgn. It is expected that the required dimensions (thus
413   * target Region @a outRgn. There are no dimension regions created during this   * the required dimension regions) were already created before calling this
414   * task. It is expected that the required dimensions (thus the required   * function.
415   * dimension regions) were already created before calling this function.   *
416   *   * To be precise, it does the task above only for the dimension zones defined by
417   * To be precise, it does the task above only for the layer selected by   * the three arguments @a mainDim, @a iSrcMainBit, @a iDstMainBit, which reflect
418   * @a iSrcLayer and @a iDstLayer. All dimensions regions of other layers that   * a selection which dimension zones shall be copied. All other dimension zones
419   * may exist, will not be copied by one single call of this function. So if   * will not be scheduled to be copied by a single call of this function. So this
420   * there is a layer dimension, this function needs to be called several times.   * function needs to be called several time in case all dimension regions shall
421     * be copied of the entire region (@a inRgn, @a outRgn).
422   *   *
423   * @param outRgn - where the dimension regions shall be copied to   * @param outRgn - where the dimension regions shall be copied to
424   * @param inRgn - all dimension regions that shall be copied from   * @param inRgn - all dimension regions that shall be copied from
425   * @param dims - dimension definitions of target region   * @param dims - precise dimension definitions of target region
426   * @param iDstLayer - layer number of destination region where the dimension   * @param mainDim - this dimension type, in combination with @a iSrcMainBit and
427   *                    regions shall be copied to   *                  @a iDstMainBit defines a selection which dimension region
428   * @param iSrcLayer - layer number of the source region where the dimension   *                  zones shall be copied by this call of this function
429   *                    regions shall be copied from   * @param iDstMainBit - destination bit of @a mainDim
430   * @param dstVelocityZones - all precise velocity zones for destination region   * @param iSrcMainBit - source bit of @a mainDim
431   *                           (since this information is stored on   * @param schedule - list of all DimensionRegion copy operations which is filled
432   *                           DimensionRegion level and this function is   *                   during the nested loops / recursions of this function call
  *                           modifying target DimensionRegions, this  
  *                           informations thus needs to be retrieved before  
  *                           calling this function)  
433   * @param dimCase - just for internal purpose (function recursion), don't pass   * @param dimCase - just for internal purpose (function recursion), don't pass
434   *                  anything here, this function will call itself recursively   *                  anything here, this function will call itself recursively
435   *                  will fill this container with concrete dimension values for   *                  will fill this container with concrete dimension values for
436   *                  selecting the precise dimension regions during its task   *                  selecting the precise dimension regions during its task
437   */   */
438  static void copyDimensionRegions(gig::Region* outRgn, gig::Region* inRgn, Dimensions dims, int iDstLayer, int iSrcLayer, const VelocityZones& dstVelocityZones, DimensionCase dimCase = DimensionCase()) {  static void scheduleCopyDimensionRegions(gig::Region* outRgn, gig::Region* inRgn,
439      if (dims.empty()) { // finally reached end of function recursion ...                                   Dimensions dims, gig::dimension_t mainDim,
440                                     int iDstMainBit, int iSrcMainBit,
441                                     CopyAssignSchedule* schedule,
442                                     DimensionCase dimCase = DimensionCase())
443    {
444        if (dims.empty()) { // reached deepest level of function recursion ...
445            CopyAssignSchedEntry e;
446    
447          // resolve the respective source & destination DimensionRegion ...                  // resolve the respective source & destination DimensionRegion ...        
448          uint srcDimValues[8] = {};          uint srcDimValues[8] = {};
449          uint dstDimValues[8] = {};          uint dstDimValues[8] = {};
450          DimensionCase srcDimCase = dimCase;          DimensionCase srcDimCase = dimCase;
451          DimensionCase dstDimCase = dimCase;          DimensionCase dstDimCase = dimCase;
452          srcDimCase[gig::dimension_layer] = iSrcLayer;          if (dims.count(mainDim)) {
453          dstDimCase[gig::dimension_layer] = iDstLayer;              srcDimCase[mainDim] = iSrcMainBit;
454                dstDimCase[mainDim] = iDstMainBit;
455            }
456    
457            #if DEBUG_COMBINE_INSTRUMENTS
458            printf("-------------------------------\n");
459            printf("iDstMainBit=%d iSrcMainBit=%d\n", iDstMainBit, iSrcMainBit);
460            #endif
461    
462          // first select source & target dimension region with an arbitrary          // first select source & target dimension region with an arbitrary
463          // velocity split zone, to get access to the precise individual velocity          // velocity split zone, to get access to the precise individual velocity
464          // split zone sizes (if there is actually a velocity dimension at all,          // split zone sizes (if there is actually a velocity dimension at all,
465          // otherwise we already select the desired source & target dimension          // otherwise we already select the desired source & target dimension
466          // region here)          // region here)
467            #if DEBUG_COMBINE_INSTRUMENTS
468            printf("src "); fflush(stdout);
469            #endif
470          fillDimValues(srcDimValues, srcDimCase, inRgn, false);          fillDimValues(srcDimValues, srcDimCase, inRgn, false);
471            #if DEBUG_COMBINE_INSTRUMENTS
472            printf("dst "); fflush(stdout);
473            #endif
474          fillDimValues(dstDimValues, dstDimCase, outRgn, true);          fillDimValues(dstDimValues, dstDimCase, outRgn, true);
475          gig::DimensionRegion* srcDimRgn = inRgn->GetDimensionRegionByValue(srcDimValues);          gig::DimensionRegion* srcDimRgn = inRgn->GetDimensionRegionByValue(srcDimValues);
476          gig::DimensionRegion* dstDimRgn = outRgn->GetDimensionRegionByValue(dstDimValues);          gig::DimensionRegion* dstDimRgn = outRgn->GetDimensionRegionByValue(dstDimValues);
477          #if DEBUG_COMBINE_INSTRUMENTS          #if DEBUG_COMBINE_INSTRUMENTS
478            printf("iDstMainBit=%d iSrcMainBit=%d\n", iDstMainBit, iSrcMainBit);
479          printf("srcDimRgn=%lx dstDimRgn=%lx\n", (uint64_t)srcDimRgn, (uint64_t)dstDimRgn);          printf("srcDimRgn=%lx dstDimRgn=%lx\n", (uint64_t)srcDimRgn, (uint64_t)dstDimRgn);
480            printf("srcSample='%s' dstSample='%s'\n",
481                   (!srcDimRgn->pSample ? "NULL" : srcDimRgn->pSample->pInfo->Name.c_str()),
482                   (!dstDimRgn->pSample ? "NULL" : dstDimRgn->pSample->pInfo->Name.c_str())
483            );
484          #endif          #endif
485    
486            assert(srcDimRgn->GetParent() == inRgn);
487            assert(dstDimRgn->GetParent() == outRgn);
488    
489          // now that we have access to the precise velocity split zone upper          // now that we have access to the precise velocity split zone upper
490          // limits, we can select the actual source & destination dimension          // limits, we can select the actual source & destination dimension
491          // regions we need to copy (assuming that source or target region has          // regions we need to copy (assuming that source or target region has
492          // a velocity dimension)          // a velocity dimension)
493          if (outRgn->GetDimensionDefinition(gig::dimension_velocity)) {          if (outRgn->GetDimensionDefinition(gig::dimension_velocity)) {
494              // re-select target dimension region              // re-select target dimension region (with correct velocity zone)
495              assert(dstVelocityZones.find(dstDimRgn) != dstVelocityZones.end());              DimensionZones dstZones = preciseDimensionZonesFor(gig::dimension_velocity, dstDimRgn);
             DimensionZones dstZones = dstVelocityZones.find(dstDimRgn)->second;  
496              assert(dstZones.size() > 1);              assert(dstZones.size() > 1);
497              int iZoneIndex = dstDimCase[gig::dimension_velocity];              const int iDstZoneIndex =
498                    (mainDim == gig::dimension_velocity)
499                        ? iDstMainBit : dstDimCase[gig::dimension_velocity]; // (mainDim == gig::dimension_velocity) exception case probably unnecessary here
500                e.velocityZone = iDstZoneIndex;
501              #if DEBUG_COMBINE_INSTRUMENTS              #if DEBUG_COMBINE_INSTRUMENTS
502              printf("dst velocity zone: %d/%d\n", iZoneIndex, dstZones.size());              printf("dst velocity zone: %d/%d\n", iDstZoneIndex, (int)dstZones.size());
503              #endif              #endif
504              assert(iZoneIndex < dstZones.size());              assert(uint(iDstZoneIndex) < dstZones.size());
505              dstDimCase[gig::dimension_velocity] = dstZones[iZoneIndex].low; // arbitrary value between low and high              dstDimCase[gig::dimension_velocity] = dstZones[iDstZoneIndex].low; // arbitrary value between low and high
506              #if DEBUG_COMBINE_INSTRUMENTS              #if DEBUG_COMBINE_INSTRUMENTS
507              printf("dst velocity value = %d\n", dstDimCase[gig::dimension_velocity]);              printf("dst velocity value = %d\n", dstDimCase[gig::dimension_velocity]);
508                printf("dst refilled "); fflush(stdout);
509              #endif              #endif
510              fillDimValues(dstDimValues, dstDimCase, outRgn, true);              fillDimValues(dstDimValues, dstDimCase, outRgn, true);
511              dstDimRgn = outRgn->GetDimensionRegionByValue(dstDimValues);              dstDimRgn = outRgn->GetDimensionRegionByValue(dstDimValues);
512              #if DEBUG_COMBINE_INSTRUMENTS              #if DEBUG_COMBINE_INSTRUMENTS
513              printf("reselected dstDimRgn=%lx\n", (uint64_t)dstDimRgn);              printf("reselected dstDimRgn=%lx\n", (uint64_t)dstDimRgn);
514                printf("dstSample='%s'%s\n",
515                    (!dstDimRgn->pSample ? "NULL" : dstDimRgn->pSample->pInfo->Name.c_str()),
516                    (dstDimRgn->pSample ? " <--- ERROR ERROR ERROR !!!!!!!!! " : "")
517                );
518              #endif              #endif
519    
520              // re-select source dimension region              // re-select source dimension region with correct velocity zone
521              // (if it has a velocity dimension)              // (if it has a velocity dimension that is)
522              if (inRgn->GetDimensionDefinition(gig::dimension_velocity)) {              if (inRgn->GetDimensionDefinition(gig::dimension_velocity)) {
523                  DimensionZones srcZones = preciseDimensionZonesFor(gig::dimension_velocity, srcDimRgn);                  DimensionZones srcZones = preciseDimensionZonesFor(gig::dimension_velocity, srcDimRgn);
524                  assert(srcZones.size() > 1);                  e.totalSrcVelocityZones = srcZones.size();
525                  if (iZoneIndex >= srcZones.size())                  assert(srcZones.size() > 0);
526                      iZoneIndex  = srcZones.size();                  if (srcZones.size() <= 1) {
527                  srcDimCase[gig::dimension_velocity] = srcZones[iZoneIndex].low; // same zone as used above for target dimension region (no matter what the precise zone ranges are)                      addWarning("Input region has a velocity dimension with only ONE zone!");
528                    }
529                    int iSrcZoneIndex =
530                        (mainDim == gig::dimension_velocity)
531                            ? iSrcMainBit : iDstZoneIndex;
532                    if (uint(iSrcZoneIndex) >= srcZones.size())
533                        iSrcZoneIndex = srcZones.size() - 1;
534                    srcDimCase[gig::dimension_velocity] = srcZones[iSrcZoneIndex].low; // same zone as used above for target dimension region (no matter what the precise zone ranges are)
535                    #if DEBUG_COMBINE_INSTRUMENTS
536                    printf("src refilled "); fflush(stdout);
537                    #endif
538                  fillDimValues(srcDimValues, srcDimCase, inRgn, false);                  fillDimValues(srcDimValues, srcDimCase, inRgn, false);
539                  srcDimRgn = inRgn->GetDimensionRegionByValue(srcDimValues);                  srcDimRgn = inRgn->GetDimensionRegionByValue(srcDimValues);
540                  #if DEBUG_COMBINE_INSTRUMENTS                  #if DEBUG_COMBINE_INSTRUMENTS
541                  printf("reselected srcDimRgn=%lx\n", (uint64_t)srcDimRgn);                  printf("reselected srcDimRgn=%lx\n", (uint64_t)srcDimRgn);
542                    printf("srcSample='%s'\n",
543                        (!srcDimRgn->pSample ? "NULL" : srcDimRgn->pSample->pInfo->Name.c_str())
544                    );
545                  #endif                  #endif
546              }              }
547          }          }
548    
549          // backup the target DimensionRegion's current dimension zones upper          // Schedule copy operation of source -> target DimensionRegion for the
550          // limits (because the target DimensionRegion's upper limits are already          // time after all nested loops have been traversed. We have to postpone
551          // defined correctly since calling AddDimension(), and the CopyAssign()          // the actual copy operations this way, because otherwise it would
552          // call next, will overwrite those upper limits unfortunately          // overwrite informations inside the destination DimensionRegion object
553          DimensionRegionUpperLimits dstUpperLimits = getDimensionRegionUpperLimits(dstDimRgn);          // that we need to read in the code block above.
554          DimensionRegionUpperLimits srcUpperLimits = getDimensionRegionUpperLimits(srcDimRgn);          e.src = srcDimRgn;
555            e.dst = dstDimRgn;
556          // copy over the selected DimensionRegion          schedule->push_back(e);
         const gig::Region* const origRgn = dstDimRgn->GetParent(); // just for sanity check below  
         dstDimRgn->CopyAssign(srcDimRgn);  
         assert(origRgn == dstDimRgn->GetParent());  
   
         // restore all original dimension zone upper limits except of the  
         // velocity dimension, because the velocity dimension zone sizes are  
         // allowed to differ for individual DimensionRegions in gig v3 format  
         if (srcUpperLimits.count(gig::dimension_velocity)) {  
             assert(dstUpperLimits.count(gig::dimension_velocity));  
             dstUpperLimits[gig::dimension_velocity] = srcUpperLimits[gig::dimension_velocity];  
         }  
         restoreDimensionRegionUpperLimits(dstDimRgn, dstUpperLimits);  
557    
558          return; // end of recursion          return; // returning from deepest level of function recursion
559      }      }
560    
561      // Copying n dimensions requires n nested loops. That's why this function      // Copying n dimensions requires n nested loops. That's why this function
# Line 479  static void copyDimensionRegions(gig::Re Line 564  static void copyDimensionRegions(gig::Re
564      // argument 'dimCase'.      // argument 'dimCase'.
565    
566      Dimensions::iterator itDimension = dims.begin();      Dimensions::iterator itDimension = dims.begin();
   
567      gig::dimension_t type = itDimension->first;      gig::dimension_t type = itDimension->first;
568      DimensionZones  zones = itDimension->second;      DimensionZones  zones = itDimension->second;
   
569      dims.erase(itDimension);      dims.erase(itDimension);
570    
571      int iZone = 0;      int iZone = 0;
# Line 492  static void copyDimensionRegions(gig::Re Line 575  static void copyDimensionRegions(gig::Re
575          DLS::range_t zoneRange = *itZone;          DLS::range_t zoneRange = *itZone;
576          gig::dimension_def_t* def = outRgn->GetDimensionDefinition(type);          gig::dimension_def_t* def = outRgn->GetDimensionDefinition(type);
577          dimCase[type] = (def->split_type == gig::split_type_bit) ? iZone : zoneRange.low;          dimCase[type] = (def->split_type == gig::split_type_bit) ? iZone : zoneRange.low;
578    
579          // recurse until 'dims' is exhausted (and dimCase filled up with concrete value)          // recurse until 'dims' is exhausted (and dimCase filled up with concrete value)
580          copyDimensionRegions(outRgn, inRgn, dims, iDstLayer, iSrcLayer, dstVelocityZones, dimCase);          scheduleCopyDimensionRegions(outRgn, inRgn, dims, mainDim, iDstMainBit, iSrcMainBit, schedule, dimCase);
581      }      }
582  }  }
583    
584    static OrderedRegionGroup sortRegionGroup(const RegionGroup& group, const std::vector<gig::Instrument*>& instruments) {
585        OrderedRegionGroup result;
586        for (std::vector<gig::Instrument*>::const_iterator it = instruments.begin();
587             it != instruments.end(); ++it)
588        {
589            RegionGroup::const_iterator itRgn = group.find(*it);
590            if (itRgn == group.end()) continue;
591            result.push_back(
592                std::pair<gig::Instrument*, gig::Region*>(
593                    itRgn->first, itRgn->second
594                )
595            );
596        }
597        return result;
598    }
599    
600  /** @brief Combine given list of instruments to one instrument.  /** @brief Combine given list of instruments to one instrument.
601   *   *
602   * Takes a list of @a instruments as argument and combines them to one single   * Takes a list of @a instruments as argument and combines them to one single
603   * new @a output instrument. For this task, it will create a 'layer' dimension   * new @a output instrument. For this task, it will create a dimension of type
604   * in the new instrument and copies the source instruments to those layers.   * given by @a mainDimension in the new instrument and copies the source
605     * instruments to those dimension zones.
606   *   *
607   * @param instruments - (input) list of instruments that shall be combined,   * @param instruments - (input) list of instruments that shall be combined,
608   *                      they will only be read, so they will be left untouched   *                      they will only be read, so they will be left untouched
# Line 509  static void copyDimensionRegions(gig::Re Line 610  static void copyDimensionRegions(gig::Re
610   *              be created   *              be created
611   * @param output - (output) on success this pointer will be set to the new   * @param output - (output) on success this pointer will be set to the new
612   *                 instrument being created   *                 instrument being created
613     * @param mainDimension - the dimension that shall be used to combine the
614     *                        instruments
615   * @throw RIFF::Exception on any kinds of errors   * @throw RIFF::Exception on any kinds of errors
616   */   */
617  static void combineInstruments(std::vector<gig::Instrument*>& instruments, gig::File* gig, gig::Instrument*& output) {  static void combineInstruments(std::vector<gig::Instrument*>& instruments, gig::File* gig, gig::Instrument*& output, gig::dimension_t mainDimension) {
618      output = NULL;      output = NULL;
619    
620      // divide the individual regions to (probably even smaller) groups of      // divide the individual regions to (probably even smaller) groups of
# Line 544  static void combineInstruments(std::vect Line 647  static void combineInstruments(std::vect
647      {      {
648          gig::Region* outRgn = outInstr->AddRegion();          gig::Region* outRgn = outInstr->AddRegion();
649          outRgn->SetKeyRange(itGroup->first.low, itGroup->first.high);          outRgn->SetKeyRange(itGroup->first.low, itGroup->first.high);
650            #if DEBUG_COMBINE_INSTRUMENTS
651            printf("---> Start target region %d..%d\n", itGroup->first.low, itGroup->first.high);
652            #endif
653    
654          // detect the total amount of layers required to build up this combi          // detect the total amount of zones required for the given main
655          // for current key range          // dimension to build up this combi for current key range
656          int iTotalLayers = 0;          int iTotalZones = 0;
657          for (RegionGroup::iterator itRgn = itGroup->second.begin();          for (RegionGroup::iterator itRgn = itGroup->second.begin();
658               itRgn != itGroup->second.end(); ++itRgn)               itRgn != itGroup->second.end(); ++itRgn)
659          {          {
660              gig::Region* inRgn = itRgn->second;              gig::Region* inRgn = itRgn->second;
661              iTotalLayers += inRgn->Layers;              gig::dimension_def_t* def = inRgn->GetDimensionDefinition(mainDimension);
662                iTotalZones += (def) ? def->zones : 1;
663          }          }
664            #if DEBUG_COMBINE_INSTRUMENTS
665            printf("Required total zones: %d, vertical regions: %d\n", iTotalZones, itGroup->second.size());
666            #endif
667    
668          // create all required dimensions for this output region          // create all required dimensions for this output region
669          // (except the layer dimension, which we create as next step)          // (except the main dimension used for separating the individual
670            // instruments, we create that particular dimension as next step)
671          Dimensions dims = getDimensionsForRegionGroup(itGroup->second);          Dimensions dims = getDimensionsForRegionGroup(itGroup->second);
672          for (Dimensions::iterator itDim = dims.begin();          // the given main dimension which is used to combine the instruments is
673               itDim != dims.end(); ++itDim)          // created separately after the next code block, and the main dimension
674            // should not be part of dims here, because it also used for iterating
675            // all dimensions zones, which would lead to this dimensions being
676            // iterated twice
677            dims.erase(mainDimension);
678          {          {
679              if (itDim->first == gig::dimension_layer) continue;              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
680    
681              gig::dimension_def_t def;              for (Dimensions::iterator itDim = dims.begin();
682              def.dimension = itDim->first; // dimension type                  itDim != dims.end(); ++itDim)
683              def.zones = itDim->second.size();              {
684              def.bits = zoneCountToBits(def.zones);                  gig::dimension_def_t def;
685              #if DEBUG_COMBINE_INSTRUMENTS                  def.dimension = itDim->first; // dimension type
686              std::cout << "Adding new regular dimension type=" << std::hex << (int)def.dimension << std::dec << ", zones=" << (int)def.zones << ", bits=" << (int)def.bits << " ... " << std::flush;                  def.zones = itDim->second.size();
687              #endif                  def.bits = zoneCountToBits(def.zones);
688              outRgn->AddDimension(&def);                  if (def.zones < 2) {
689              #if DEBUG_COMBINE_INSTRUMENTS                      addWarning(
690              std::cout << "OK" << std::endl << std::flush;                          "Attempt to create dimension with type=0x%x with only "
691              #endif                          "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          }          }
713    
714          // create the layer dimension (if necessary for current key range)          // create the main dimension (if necessary for current key range)
715          if (iTotalLayers > 1) {          if (iTotalZones > 1) {
716              gig::dimension_def_t def;              gig::dimension_def_t def;
717              def.dimension = gig::dimension_layer; // dimension type              def.dimension = mainDimension; // dimension type
718              def.zones = iTotalLayers;              def.zones = iTotalZones;
719              def.bits = zoneCountToBits(def.zones);              def.bits = zoneCountToBits(def.zones);
720              #if DEBUG_COMBINE_INSTRUMENTS              #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;              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;
722              #endif              #endif
723              outRgn->AddDimension(&def);              outRgn->AddDimension(&def);
724              #if DEBUG_COMBINE_INSTRUMENTS              #if DEBUG_COMBINE_INSTRUMENTS
725              std::cout << "OK" << std::endl << std::flush;              std::cout << "OK" << std::endl << std::flush;
726              #endif              #endif
727            } else {
728                dims.erase(mainDimension);
729          }          }
730    
731          // now copy the source dimension regions to the target dimension regions          // for the next task we need to have the current RegionGroup to be
732          int iDstLayer = 0;          // sorted by instrument in the same sequence as the 'instruments' vector
733          for (RegionGroup::iterator itRgn = itGroup->second.begin();          // argument passed to this function (because the std::map behind the
734               itRgn != itGroup->second.end(); ++itRgn) // iterate over 'vertical' / source regions ...          // 'RegionGroup' type sorts by memory address instead, and that would
735            // sometimes lead to the source instruments' region to be sorted into
736            // the wrong target layer)
737            OrderedRegionGroup currentGroup = sortRegionGroup(itGroup->second, instruments);
738    
739            // schedule copying the source dimension regions to the target dimension
740            // regions
741            CopyAssignSchedule schedule;
742            int iDstMainBit = 0;
743            for (OrderedRegionGroup::iterator itRgn = currentGroup.begin();
744                 itRgn != currentGroup.end(); ++itRgn) // iterate over 'vertical' / source regions ...
745          {          {
746              gig::Region* inRgn = itRgn->second;              gig::Region* inRgn = itRgn->second;
747              VelocityZones dstVelocityZones = getVelocityZones(outRgn);              #if DEBUG_COMBINE_INSTRUMENTS
748              for (uint iSrcLayer = 0; iSrcLayer < inRgn->Layers; ++iSrcLayer, ++iDstLayer) {              printf("[source region of '%s']\n", inRgn->GetParent()->pInfo->Name.c_str());
749                  copyDimensionRegions(outRgn, inRgn, dims, iDstLayer, iSrcLayer, dstVelocityZones);              #endif
750    
751                // determine how many main dimension zones this input region requires
752                gig::dimension_def_t* def = inRgn->GetDimensionDefinition(mainDimension);
753                const int inRgnMainZones = (def) ? def->zones : 1;
754    
755                for (uint iSrcMainBit = 0; iSrcMainBit < inRgnMainZones; ++iSrcMainBit, ++iDstMainBit) {
756                    scheduleCopyDimensionRegions(
757                        outRgn, inRgn, dims, mainDimension,
758                        iDstMainBit, iSrcMainBit, &schedule
759                    );
760                }
761            }
762    
763            // finally copy the scheduled source -> target dimension regions
764            for (uint i = 0; i < schedule.size(); ++i) {
765                CopyAssignSchedEntry& e = schedule[i];
766    
767                // backup the target DimensionRegion's current dimension zones upper
768                // limits (because the target DimensionRegion's upper limits are
769                // already defined correctly since calling AddDimension(), and the
770                // CopyAssign() call next, will overwrite those upper limits
771                // unfortunately
772                DimensionRegionUpperLimits dstUpperLimits = getDimensionRegionUpperLimits(e.dst);
773                DimensionRegionUpperLimits srcUpperLimits = getDimensionRegionUpperLimits(e.src);
774    
775                // now actually copy over the current DimensionRegion
776                const gig::Region* const origRgn = e.dst->GetParent(); // just for sanity check below
777                e.dst->CopyAssign(e.src);
778                assert(origRgn == e.dst->GetParent()); // if gigedit is crashing here, then you must update libgig (to at least SVN r2547, v3.3.0.svn10)
779    
780                // restore all original dimension zone upper limits except of the
781                // velocity dimension, because the velocity dimension zone sizes are
782                // allowed to differ for individual DimensionRegions in gig v3
783                // format
784                //
785                // if the main dinension is the 'velocity' dimension, then skip
786                // restoring the source's original velocity zone limits, because
787                // dealing with merging that is not implemented yet
788                // TODO: merge custom velocity splits if main dimension is the velocity dimension (for now equal sized velocity zones are used if mainDim is 'velocity')
789                if (srcUpperLimits.count(gig::dimension_velocity) && mainDimension != gig::dimension_velocity) {
790                    if (!dstUpperLimits.count(gig::dimension_velocity)) {
791                        addWarning("Source instrument seems to have a velocity dimension whereas new target instrument doesn't!");
792                    } else {
793                        dstUpperLimits[gig::dimension_velocity] =
794                            (e.velocityZone >= e.totalSrcVelocityZones)
795                                ? 127 : srcUpperLimits[gig::dimension_velocity];
796                    }
797              }              }
798                restoreDimensionRegionUpperLimits(e.dst, dstUpperLimits);
799          }          }
800      }      }
801    
# Line 615  CombineInstrumentsDialog::CombineInstrum Line 810  CombineInstrumentsDialog::CombineInstrum
810      : Gtk::Dialog(_("Combine Instruments"), parent, true),      : Gtk::Dialog(_("Combine Instruments"), parent, true),
811        m_gig(gig), m_fileWasChanged(false), m_newCombinedInstrument(NULL),        m_gig(gig), m_fileWasChanged(false), m_newCombinedInstrument(NULL),
812        m_cancelButton(Gtk::Stock::CANCEL), m_OKButton(Gtk::Stock::OK),        m_cancelButton(Gtk::Stock::CANCEL), m_OKButton(Gtk::Stock::OK),
813        m_descriptionLabel()        m_descriptionLabel(), m_tableDimCombo(2, 2), m_comboDimType(),
814          m_labelDimType(Glib::ustring(_("Combine by Dimension:")) + "  ", Gtk::ALIGN_END)
815  {  {
816        m_scrolledWindow.add(m_treeView);
817        m_scrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
818    
819      get_vbox()->pack_start(m_descriptionLabel, Gtk::PACK_SHRINK);      get_vbox()->pack_start(m_descriptionLabel, Gtk::PACK_SHRINK);
820      get_vbox()->pack_start(m_treeView);      get_vbox()->pack_start(m_tableDimCombo, Gtk::PACK_SHRINK);
821        get_vbox()->pack_start(m_scrolledWindow);
822      get_vbox()->pack_start(m_buttonBox, Gtk::PACK_SHRINK);      get_vbox()->pack_start(m_buttonBox, Gtk::PACK_SHRINK);
823    
824  #if GTKMM_MAJOR_VERSION >= 3  #if GTKMM_MAJOR_VERSION >= 3
825      description.set_line_wrap();      m_descriptionLabel.set_line_wrap();
826  #endif  #endif
827      m_descriptionLabel.set_text(_(      m_descriptionLabel.set_text(_(
828          "Select at least two instruments below that shall be combined  "          "Select at least two instruments below that shall be combined (as "
829          "as layers (using a \"Layer\" dimension) to a new instrument. The "          "separate dimension zones of the selected dimension type) as a new "
830          "original instruments remain untouched.")          "instrument. The original instruments remain untouched.\n\n"
831      );          "You may use this tool for example to combine solo instruments into "
832            "a combi sound arrangement by selecting the 'layer' dimension, or you "
833            "might combine similar sounding solo sounds into separate velocity "
834            "split layers by using the 'velocity' dimension, and so on."
835        ));
836    
837        // add dimension type combo box
838        {
839            int iLayerDimIndex = -1;
840            Glib::RefPtr<Gtk::ListStore> refComboModel = Gtk::ListStore::create(m_comboDimsModel);
841            for (int i = 0x01, iRow = 0; i < 0xff; i++) {
842                Glib::ustring sType =
843                    dimTypeAsString(static_cast<gig::dimension_t>(i));
844                if (sType.find("Unknown") != 0) {
845                    Gtk::TreeModel::Row row = *(refComboModel->append());
846                    row[m_comboDimsModel.m_type_id]   = i;
847                    row[m_comboDimsModel.m_type_name] = sType;
848                    if (i == gig::dimension_layer) iLayerDimIndex = iRow;
849                    iRow++;
850                }
851            }
852            m_comboDimType.set_model(refComboModel);
853            m_comboDimType.pack_start(m_comboDimsModel.m_type_id);
854            m_comboDimType.pack_start(m_comboDimsModel.m_type_name);
855            m_tableDimCombo.attach(m_labelDimType, 0, 1, 0, 1);
856            m_tableDimCombo.attach(m_comboDimType, 1, 2, 0, 1);
857            m_comboDimType.set_active(iLayerDimIndex); // preselect "layer" dimension
858        }
859    
860      m_refTreeModel = Gtk::ListStore::create(m_columns);      m_refTreeModel = Gtk::ListStore::create(m_columns);
861      m_treeView.set_model(m_refTreeModel);      m_treeView.set_model(m_refTreeModel);
862      //m_treeView.set_tooltip_text(_("asdf"));      m_treeView.set_tooltip_text(_(
863            "Use SHIFT + left click or CTRL + left click to select the instruments "
864            "you want to combine."
865        ));
866      m_treeView.append_column("Instrument", m_columns.m_col_name);      m_treeView.append_column("Instrument", m_columns.m_col_name);
867      m_treeView.set_headers_visible(false);      m_treeView.set_headers_visible(false);
868      m_treeView.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);      m_treeView.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
# Line 682  CombineInstrumentsDialog::CombineInstrum Line 912  CombineInstrumentsDialog::CombineInstrum
912      );      );
913    
914      show_all_children();      show_all_children();
915    
916        // show a warning to user if he uses a .gig in v2 format
917        if (gig->pVersion->major < 3) {
918            Glib::ustring txt = _(
919                "You are currently using a .gig file in old v2 format. The current "
920                "combine algorithm will most probably fail trying to combine "
921                "instruments in this old format. So better save the file in new v3 "
922                "format before trying to combine your instruments."
923            );
924            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_WARNING);
925            msg.run();
926        }
927  }  }
928    
929  void CombineInstrumentsDialog::combineSelectedInstruments() {  void CombineInstrumentsDialog::combineSelectedInstruments() {
# Line 698  void CombineInstrumentsDialog::combineSe Line 940  void CombineInstrumentsDialog::combineSe
940          instruments.push_back(instrument);          instruments.push_back(instrument);
941      }      }
942    
943        g_warnings.clear();
944    
945      try {      try {
946          combineInstruments(instruments, m_gig, m_newCombinedInstrument);          // which main dimension was selected in the combo box?
947            gig::dimension_t mainDimension;
948            {
949                Gtk::TreeModel::iterator iterType = m_comboDimType.get_active();
950                if (!iterType) throw gig::Exception("No dimension selected");
951                Gtk::TreeModel::Row rowType = *iterType;
952                if (!rowType) throw gig::Exception("Something is wrong regarding dimension selection");
953                int iTypeID = rowType[m_comboDimsModel.m_type_id];
954                mainDimension = static_cast<gig::dimension_t>(iTypeID);
955            }
956    
957            // now start the actual cobination task ...
958            combineInstruments(instruments, m_gig, m_newCombinedInstrument, mainDimension);
959      } catch (RIFF::Exception e) {;      } catch (RIFF::Exception e) {;
960          Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);          Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);
961          msg.run();          msg.run();
962          return;          return;
963        } catch (...) {
964            Glib::ustring txt = _("An unknown exception occurred!");
965            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
966            msg.run();
967            return;
968        }
969    
970        if (!g_warnings.empty()) {
971            Glib::ustring txt = _(
972                "Combined instrument was created successfully, but there were warnings:"
973            );
974            txt += "\n\n";
975            for (Warnings::const_iterator itWarn = g_warnings.begin();
976                 itWarn != g_warnings.end(); ++itWarn)
977            {
978                txt += "-> " + *itWarn + "\n";
979            }
980            txt += "\n";
981            txt += _(
982                "You might also want to check the console for further warnings and "
983                "error messages."
984            );
985            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_WARNING);
986            msg.run();
987      }      }
988    
989      // no error occurred      // no error occurred

Legend:
Removed from v.2549  
changed lines
  Added in v.2616

  ViewVC Help
Powered by ViewVC