void TFCompositeModifier::change_check(){

	if(managing_)
	{
		updateComposition_();
		return;
	}

	bool recalculate = false;
	
	Common::TimeStamp lastChange = palette_->lastPaletteChange();
	if(lastPaletteChange_ != lastChange)
	{
		lastPaletteChange_ = lastChange;
		editors_ = palette_->getEditors();
		//editors_.swap(palette_->getEditors());
		
		bool compositionEnabled = false;
		Composition newComposition;
		Composition::iterator found;
		for(TFPalette::Editors::iterator it = editors_.begin(); it != editors_.end(); ++it)
		{
			if(!it->second->hasAttribute(TFEditor::Composition) &&
				it->second->getDimension() == TF_DIMENSION_1)
			{
				compositionEnabled = true;

				found = composition_.find(it->first);
				if(found != composition_.end())
				{
					newComposition.insert(*found);
					composition_.erase(found);
				}
			}
		}

		if(!composition_.empty()) recalculate = true;
		for(Composition::iterator it = composition_.begin(); it != composition_.end(); ++it)
		{
			layout_->removeWidget(it->second->name);
			delete it->second;
		}
		composition_.swap(newComposition);

		compositeTools_->manageButton->setEnabled(compositionEnabled);
	}

	for(Composition::iterator it = composition_.begin(); it != composition_.end(); ++it)
	{
		lastChange = it->second->editor->lastChange();
		if(it->second->change != lastChange)
		{
			recalculate = true;
			it->second->change = lastChange;
		}
		it->second->updateName();
	}

	if(recalculate) computeResultFunction_();
}
CompositionEditor::CompositionEditor(Composition &composition, Library &library, QWidget *parent) :
  QSplitter{Qt::Horizontal, parent},
  draw{composition, this},
  componentModel{QtListFactory::createComponentList(library.getComponents(), this)},
  instances{QtListFactory::createInstanceList(composition.getInstances(), componentModel, this)},
  connections{QtListFactory::createConnectionList(composition.getConnections(), this)}
{
  this->addWidget(&draw);

  QVBoxLayout *layout = new QVBoxLayout();
  layout->addWidget(new QLabel("Instances"));
  layout->addWidget(&instanceView);
  layout->addWidget(new QLabel("Connections"));
  layout->addWidget(&connectionView);

  QWidget *rightPanel = new QWidget();
  rightPanel->setLayout(layout);
  this->addWidget(rightPanel);

  instanceView.setItemDelegateForColumn(QtNameTypeItem<IComponentInstance>::TYPE_INDEX, new ComboboxItemDelegate(modelFromTypeIndex<IComponentInstance>)); //FIXME memory leak
  instanceView.setModel(instances);
  connectionView.setModel(connections);

  connect(&draw, SIGNAL(addInstance(Point,Composition&)), this, SIGNAL(addInstance(Point,Composition&)));
}
void
AudioSegmentResizeFromStartCommand::execute()
{
    Composition *c = m_segment->getComposition();

    if (!m_newSegment) {
        RealTime oldRT = c->getElapsedRealTime(m_oldStartTime);
        RealTime newRT = c->getElapsedRealTime(m_newStartTime);

        m_newSegment = m_segment->clone(false);
        m_newSegment->setStartTime(m_newStartTime);

        // Compute an audio start time that will keep the audio exactly where
        // it was in time.
        RealTime audioStartTime = 
            m_segment->getAudioStartTime() - (oldRT - newRT);

        // Do not allow a negative audio start time.
        // ??? This is a stopgap measure as the audio segment preview code 
        //   will crash if the audio start time is negative.  Need to fix the
        //   preview code, then check to see if the playback code works
        //   properly given a negative start time.  Then this can be removed.
        if (audioStartTime <= RealTime::zeroTime)
            m_newSegment->setAudioStartTime(RealTime::zeroTime);
        else
            m_newSegment->setAudioStartTime(
                m_segment->getAudioStartTime() - (oldRT - newRT));
    }

    c->addSegment(m_newSegment);
    m_newSegment->setEndMarkerTime(m_segment->getEndMarkerTime());
    c->detachSegment(m_segment);

    m_detached = false;
}
void
SegmentJoinCommand::execute()
{
    Composition *composition = m_oldSegments[0]->getComposition();
    if (!composition) {
        RG_DEBUG << "SegmentJoinCommand::execute: ERROR: old segments are not in composition!";
        return ;
    }

    if (!m_newSegment) {
        m_newSegment = makeSegment(m_oldSegments);
    }

    composition->addSegment(m_newSegment);

    // Select this new joined segment.
    RosegardenMainWindow::self()->getView()->getTrackEditor()->
        getCompositionView()->getModel()->setSelected(m_newSegment);
    
    for (size_t i = 0; i < m_oldSegments.size(); ++i) {
        composition->detachSegment(m_oldSegments[i]);
    }

    m_detached = true;
}
Beispiel #5
0
void
MupExporter::writeClefAndKey(std::ofstream &str, TrackId trackNo)
{
    Composition *c = m_composition;

    for (Composition::iterator i = c->begin(); i != c->end(); ++i) {
        if ((*i)->getTrack() == trackNo) {

            Clef clef((*i)->getClefAtTime((*i)->getStartTime()));
            Rosegarden::Key key((*i)->getKeyAtTime((*i)->getStartTime()));


            str << "staff " << trackNo + 1 << "\n";

            if (clef.getClefType() == Clef::Treble) {
                str << "\tclef=treble\n";
            } else if (clef.getClefType() == Clef::Alto) {
                str << "\tclef=alto\n";
            } else if (clef.getClefType() == Clef::Tenor) {
                str << "\tclef=tenor\n";
            } else if (clef.getClefType() == Clef::Bass) {
                str << "\tclef=bass\n";
            }

            str << "\tkey=" << key.getAccidentalCount()
            << (key.isSharp() ? "#" : "&")
            << (key.isMinor() ? "minor" : "major") << std::endl;

            m_clefKeyMap[trackNo] = ClefKeyPair(clef, key);

            return ;
        }
    }
}
Beispiel #6
0
 //generates output and puts it in data vector
 void run(){
     while( ((structIsaBTree) ? bt.getCurrentTime()<limit : c.getCurrentTime()<limit) && ((structIsaBTree) ? bt.getHead()!=nullptr : c.getGroupSums()>0) ){
         entry vecPos = (structIsaBTree) ? bt.find() : c.selectRate();
         //std::cout<<vecPos.first<<" "<<vecPos.second.first<<" "<<vecPos.second.second<<"\n";
         if (vecPos.second.second>2){
             if (vecPos.second.second==3){
                 addCreature(creatures[vecPos.second.first-1].get("positionX"));
                 std::vector< entry > nCreature{ {10,{creatures.size(),1}}, {10,{creatures.size(),2}}, {.5,{creatures.size(),3}},{.25,{creatures.size(),4}} };
                 for (int i = 0; i<nCreature.size();i++){
                     (structIsaBTree) ? bt.insert(nCreature[i]) : c.addRate(nCreature[i]);
                 }
             }
             else{
                 (structIsaBTree) ? bt.removeAll(vecPos.second,bt.getHead()) : c.deleteC(vecPos.second.first);
             }
         }
         creatures[vecPos.second.first-1].increment(vecPos.second.second);
         for (int x = 0; x<creatures.size();x++){
            // std::cout<<"creature "<<x+1<<" position "<<creatures[x].get("positionX")<<"\n";
             if (creatures[x].get("dead")!=1)
                 data.push_back({(structIsaBTree) ? bt.getCurrentTime() : c.getCurrentTime() ,creatures[x].get("positionX")});
         }
     }
     std::cout<<"final size: "<<creatures.size()<<"\n";
 }
Beispiel #7
0
void RizzlyPrint::visit(const Composition &composition)
{
  for (const auto *inst : composition.getInstances()) {
    inst->accept(*this);
  }
  for (const auto *con : composition.getConnections()) {
    con->accept(*this);
  }
}
void
AudioSegmentResizeFromStartCommand::unexecute()
{
    Composition *c = m_newSegment->getComposition();
    c->addSegment(m_segment);
    c->detachSegment(m_newSegment);

    m_detached = true;
}
Beispiel #9
0
void CompositionTest::has_instance_with_his_parent_component()
{
  ICompositionInstance *compInstance = new CompositionInstanceMock();
  Composition *composition = new Composition(compInstance);

  CPPUNIT_ASSERT_EQUAL(compInstance, composition->getSelfInstance());

  CompositionFactory::dispose(composition);
}
Beispiel #10
0
QStringList
ProjectPackager::getAudioFiles()
{
    QStringList list;

    // get the Composition from the document, so we can iterate through it
    Composition *comp = &m_doc->getComposition();

    // We don't particularly care about tracks here, so just iterate through the
    // entire Composition to find the audio segments and get the associated
    // file IDs from which to obtain a list of actual files.  This could
    // conceivably pick up audio segments that are residing on MIDI tracks and
    // wouldn't otherwise be functional, but the important thing is to never
    // miss a single file that has any chance of being worth preserving.
    for (Composition::iterator i = comp->begin(); i != comp->end(); ++i) {
        if ((*i)->getType() == Segment::Audio) {

            AudioFileManager *manager = &m_doc->getAudioFileManager();

            unsigned int id = (*i)->getAudioFileId();

            AudioFile *file = manager->getAudioFile(id);

            // some polite sanity checking to avoid possible crashes
            if (!file) continue;

            list << file->getFilename();
        }
    }

    // QStringList::removeDuplicates() would have been easy, but it's only in Qt
    // 4.5.0 and up.  So here's the algorithm from Qt 4.5.0, courtesy of (and
    // originally Copyright 2009) Nokia

    QStringList *that = &list;

    int n = that->size();
    int j = 0;
    QSet<QString> seen;
    seen.reserve(n);
    for (int i = 0; i < n; ++i) {
        const QString &s = that->at(i);
        if (seen.contains(s))
            continue;
        seen.insert(s);
        if (j != i)
            (*that)[j] = s;
        ++j;
    }
    if (n != j)
        that->erase(that->begin() + j, that->end());
//    return n - j;

    return list;
}
Beispiel #11
0
void CompositionTest::getInstance()
{
  Composition *composition = new Composition(new CompositionInstanceMock());
  Component *component = ComponentFactory::produce("Component", {}, {});
  IComponentInstance *instance = InstanceFactory::produce(component, "instance", Point(0,0));

  composition->getInstances().add(instance);
  CPPUNIT_ASSERT_EQUAL(instance, composition->getInstance("instance"));

  CompositionFactory::dispose(composition);
  ComponentFactory::dispose(component);
}
void MainWindow::testComposition()
{
    Leaf *pLeaf = new Leaf();
    pLeaf->operation();

    Composition *pComposion = new Composition();
    pComposion->add(pLeaf);
    pComposion->operation();

    Component *pCom2 = pComposion->child(0);
    pCom2->operation();
}
void TFCompositeModifier::updateComposition_(){

	Selection selection = manager_.getComposition();
	clearLayout_();

	bool recalculate = false;
	M4D::Common::TimeStamp lastChange;
	Editor* editor;
	Composition newComposition;
	Composition::iterator found;
	for(Selection::iterator it = selection.begin(); it != selection.end(); ++it)
	{
		found = composition_.find(*it);
		if(found == composition_.end())
		{
			editor = new Editor(editors_.find(*it)->second);
			newComposition.insert(std::make_pair<TF::Size, Editor*>(
				*it,
				editor)
			);
			recalculate = true;
		}
		else
		{
			lastChange = found->second->editor->lastChange();
			if(found->second->change != lastChange)
			{
				recalculate = true;
				found->second->change = lastChange;
			}
			editor = found->second;
			editor->updateName();

			newComposition.insert(*found);
			composition_.erase(found);
		}

		layout_->addWidget(editor->name);
	}
	layout_->addItem(pushUpSpacer_);

	if(!composition_.empty()) recalculate = true;
	for(Composition::iterator it = composition_.begin(); it != composition_.end(); ++it)
	{
		layout_->removeWidget(it->second->name);
		delete it->second;
	}
	composition_.swap(newComposition);

	if(recalculate) computeResultFunction_();
}
SpecializedComponentBase CompositionObj::getSpecialized(std::shared_ptr<ComponentObj> _obj, std::string name){
    assert(this == _obj.get());
    if (auto spec = dynamic_cast<SpecializedComponentObjBase *>(this)) {
        auto obj = std::dynamic_pointer_cast<CompositionObj>(spec->getOrginal());
        assert(obj);
        auto s = SpecializedComponentObj<CompositionObj>::make(obj, pool, name);
        s->configuration = spec->configuration;
        s->replaced_children = spec->replaced_children;
        s->setActive(spec->isActive());
        return s;
    }

    Composition obj = std::dynamic_pointer_cast<CompositionObj>(_obj);
    assert(obj.get());
    return SpecializedComponentObj<CompositionObj>::make(obj, pool,name);
}
timeT
MatrixPercussionInsertionCommand::getEndTime(Segment &segment,
        timeT time,
        Event &event)
{
    timeT endTime =
        time + Note(Note::Semibreve,
                    0).getDuration();
    timeT barEndTime = segment.getBarEndForTime(time);
    timeT segmentEndTime = segment.getEndMarkerTime();

    if (barEndTime > endTime)
        endTime = barEndTime;
    if (endTime > segmentEndTime)
        endTime = segmentEndTime;

    int pitch = 0;
    if (event.has(PITCH)) {
        pitch = event.get<Int>(PITCH);
    }

    for (Segment::iterator i = segment.findTime(time);
            segment.isBeforeEndMarker(i); ++i) {

        if ((*i)->has(PITCH) &&
                (*i)->get
                <Int>(PITCH) == pitch) {

            if ((*i)->getAbsoluteTime() > time &&
                    (*i)->isa(Note::EventType)) {
                endTime = (*i)->getAbsoluteTime();
            }
        }
    }

    Composition *comp = segment.getComposition();
    std::pair<timeT, timeT> barRange =
        comp->getBarRangeForTime(time);
    timeT barDuration = barRange.second - barRange.first;


    if (endTime > time + barDuration) {
        endTime = time + barDuration;
    }

    return endTime;
}
Beispiel #16
0
void RizzlyPrintTest::onlyInstance()
{
  std::stringstream ss;
  RizzlyPrint printer(ss);
  Component *component = ComponentFactory::produce("Component", {}, {});
  Instance *instance = InstanceFactory::produce(component, "instance", Point(0,0));
  Composition *composition = new Composition(new CompositionInstanceMock());
  composition->getInstances().add(instance);

  printer.print(*composition);

  std::vector<std::string> listing = asList(ss);
  CPPUNIT_ASSERT_EQUAL(size_t(1), listing.size());
  CPPUNIT_ASSERT_EQUAL(std::string("instance: Component;"), listing[0]);

  CompositionFactory::dispose(composition);
  ComponentFactory::dispose(component);
}
Beispiel #17
0
// Get the current tempos of the composition
// @param A composition
// @param Reference to a TempoMap, to be filled.
// @author Tom Breton (Tehom)
void
FitToBeatsCommand::getCurrentTempi(Composition &composition, TempoMap &Tempos)
{
    const int numTempoChanges = composition.getTempoChangeCount();
    for (int i = 0; i < numTempoChanges; ++i) {
        TempoChange tempoChange =
            getTempoChange(composition, i); 
        Tempos[tempoChange.first] = tempoChange.second;
    }
}
Beispiel #18
0
void CompositionTest::delete_selfInstance_port_removes_dependant_connections()
{
  Component *comp1 = ComponentFactory::produce("comp1", {"in"}, {"out"});
  Composition *composition = new Composition(new CompositionInstance(comp1));
  comp1->setImplementation(composition);

  const auto inst = composition->getSelfInstance();
  auto portIn = inst->getPorts()[0];
  auto portOut = inst->getPorts()[1];
  auto connection = ConnectionFactory::produce(portIn, portOut);
  composition->getConnections().add(connection);

  ComponentPort *port = comp1->getPorts()[0];
  CPPUNIT_ASSERT_EQUAL(size_t(1), composition->getConnections().size());
  comp1->getPorts().remove(port);
  CPPUNIT_ASSERT_EQUAL(size_t(0), composition->getConnections().size());

  ComponentFactory::dispose(comp1);
}
Beispiel #19
0
void CompositionTest::deleteInstancePort_removes_dependant_connections()
{
  Component *comp1 = ComponentFactory::produce("comp1", {"in"}, {"out"});
  Composition *composition = new Composition(new CompositionInstanceMock());
  Instance *inst = InstanceFactory::produce(comp1, "inst", Point(0,0));
  composition->getInstances().add(inst);
  InstancePort *portOut = inst->getPort("out");
  InstancePort *portIn = inst->getPort("in");
  Connection *connection = ConnectionFactory::produce(portOut, portIn);
  composition->getConnections().add(connection);

  ComponentPort *port = comp1->getPorts()[0];
  CPPUNIT_ASSERT_EQUAL(size_t(1), composition->getConnections().size());
  comp1->getPorts().remove(port);
  CPPUNIT_ASSERT_EQUAL(size_t(0), composition->getConnections().size());

  CompositionFactory::dispose(composition);
  ComponentFactory::dispose(comp1);
}
Beispiel #20
0
void RizzlyPrintTest::connection()
{
  std::stringstream ss;
  RizzlyPrint printer(ss);
  Component *component = ComponentFactory::produce("Component", {"a"}, {"b"});
  Instance *instance = InstanceFactory::produce(component, "inst", Point(0,0));
  Connection *connection = ConnectionFactory::produce(instance->getPorts().front(), instance->getPorts().back());

  Composition *composition = new Composition(new CompositionInstanceMock());
  composition->getInstances().add(instance);
  composition->getConnections().add(connection);

  printer.print(*composition);

  std::vector<std::string> listing = asList(ss);
  CPPUNIT_ASSERT_EQUAL(size_t(2), listing.size());
  CPPUNIT_ASSERT_EQUAL(std::string("inst: Component;"), listing[0]);
  CPPUNIT_ASSERT_EQUAL(std::string("inst.a -> inst.b;"), listing[1]);

  CompositionFactory::dispose(composition);
  ComponentFactory::dispose(component);
}
Beispiel #21
0
int main()
{
	Composition* quick = new Composition(new SimpleCompositor);
	quick->Repair();
	Composition* slick = new Composition(new TeXCompositor);
	slick->Repair();
	Composition* iconic = new Composition(new ArrayCompositor(100));
	iconic->Repair();
	return 0;
}
Beispiel #22
0
void Loader::setupCameraLayerJson(CameraLayer& layer, const ofJson& json, Composition& comp)
{
	const ofJson& properties = json["property"];
	setupLayerJson(layer, json);
	setupPropertyKeysJson(*layer.getLookAtProperty(), properties["LookAt"], ofVec3f(1,1,-1));
	{
		auto prop = layer.getFovProperty();
		auto zoom = properties.find("Zoom");
		if(zoom != end(properties)) {
			const ofJson& keys = properties["Zoom"];
			for(auto key = keys.begin(); key != keys.end(); ++key) {
				const string& name = key.key();
				int key_frame = ofToInt(name);
				float value = 2 * atan(comp.getHeight() / (2 * keys[name].get<float>())) * (180 / PI);
				prop->addKey(key_frame, value);
			}
		}
	}
}
Beispiel #23
0
// Clone a given tempo by index.
// @remarks Currently discards ramping because TempoT doesn't hold it.
// @author Tom Breton (Tehom)
FitToBeatsCommand::TempoChange
FitToBeatsCommand::getTempoChange(Composition &composition, int i)
{
    return composition.getTempoChange(i);
}
Beispiel #24
0
void Loader::setupCompositionJson(Composition& comp, const ofJson& json)
{
	// Basics
	comp.name_ = json.value("name", "noname");
	comp.allocate(json.value("width", 1), json.value("height", 1));
	comp.setLength(json.value("length", 0));
	comp.setFrameRate(json.value("frameRate", 0));
	// Layers
	const ofJson& layers = json["layer"];
	if(layers.is_array()) {
		map<shared_ptr<Layer>, int> all;
		map<shared_ptr<Layer>, int> children;
		int layer_count = layers.size();
		for(int i = layer_count; i--;) {	// reverse iterate for draw priority
			const ofJson& layer = layers[i];
			const string& type_name = layer.value("layerType", "unknown");
			shared_ptr<Layer> l = nullptr;
			shared_ptr<LayerCap> c = nullptr;
			if(type_name == "composition") {
				auto ll = make_shared<AVLayer>();
				setupAVLayerJson(*ll, layer);
				auto cap = make_shared<CompositionCap>();
				setupCompositionJson(*cap, layer);
				comp.av_.push_back(ll);
				l = ll;
				c = cap;
			}
			else if(type_name == "solid") {
				auto ll = make_shared<AVLayer>();
				setupAVLayerJson(*ll, layer);
				auto cap = make_shared<PlaneCap>();
				setupPlaneJson(*cap, layer);
				comp.av_.push_back(ll);
				l = ll;
				c = cap;
			}
			else if(type_name == "sequence") {
				auto ll = make_shared<AVLayer>();
				setupAVLayerJson(*ll, layer);
				auto cap = make_shared<SequenceCap>();
				setupSequenceJson(*cap, layer);
				comp.av_.push_back(ll);
				l = ll;
				c = cap;
			}
			else if(type_name == "image") {
				auto ll = make_shared<AVLayer>();
				setupAVLayerJson(*ll, layer);
				auto cap = make_shared<ImageCap>();
				setupImageJson(*cap, layer);
				comp.av_.push_back(ll);
				l = ll;
				c = cap;
			}
			else if(type_name == "movie") {
				auto ll = make_shared<AVLayer>();
				setupAVLayerJson(*ll, layer);
				auto cap = make_shared<MovieCap>();
				setupMovieJson(*cap, layer);
				cap->setComposition(&comp);
				comp.av_.push_back(ll);
				l = ll;
				c = cap;
			}
			else if(type_name == "camera") {
				auto ll = make_shared<CameraLayer>();
				setupCameraLayerJson(*ll, layer, comp);
				comp.camera_.push_back(ll);
				l = ll;
			}
			else if(type_name == "shape") {
				auto ll = make_shared<AVLayer>();
				setupAVLayerJson(*ll, layer);
				auto cap = make_shared<ShapeCap>();
				setupShapeJson(*cap, layer);
				comp.av_.push_back(ll);
				l = ll;
				c = cap;
			}
			if(!l) {
				continue;
			}
			if(c) {
				l->setCap(c);
			}
			all.insert(pair<shared_ptr<Layer>,int>(l, layer.value("index", 0)));
			auto parent = layer.find("parent");
			if(parent != end(layer)) {
				children.insert(pair<shared_ptr<Layer>,int>(l, *parent));
			}
		}
		// search parent
		for(auto &child : children) {
			for(auto &parent : all) {
				if(child.second == parent.second) {
					child.first->setParent(parent.first);
				}
			}
		}
	}
	// Markers
	auto markers = json.find("marker");
	if(markers != end(json) && markers->is_array()) {
		int marker_count = markers->size();
		for(int i = 0; i < marker_count; ++i) {
			setupMarkerJson(*comp.addNewMarker(), (*markers)[i]);
		}
	}
	comp.setFrame(0);
}
Beispiel #25
0
void RizzlyPrint::print(const Composition &sheet)
{
  sheet.accept(*this);
}
Beispiel #26
0
void
Clipboard::newSegment(const Segment *copyFrom, timeT from, timeT to,
    bool expandRepeats)
{
    // create with copy ctor so as to inherit track, instrument etc
    Segment *s = copyFrom->clone(false);

    // If the segment is within the time range
    if (from <= s->getStartTime() && to >= s->getEndMarkerTime()) {
        // Insert the whole thing.
        m_segments.insert(s);

        // don't change m_partial as we are inserting a complete segment

        return;
    }

    // Only a portion of the source segment will be used.

    const timeT segStart = copyFrom->getStartTime();
    const timeT segEndMarker = copyFrom->getEndMarkerTime();
    timeT segDuration = segEndMarker - segStart;
    
    // We can't copy starting prior to the start of the segment.
    if (from < segStart)
        from = segStart;

    int firstRepeat = 0;
    int lastRepeat = 0;

    if (!copyFrom->isRepeating() || segDuration <= 0) {
        expandRepeats = false;
    }

    if (expandRepeats) {
        firstRepeat = (from - segStart) / segDuration;
        to = std::min(to, copyFrom->getRepeatEndTime());
        lastRepeat = (to - segStart) / segDuration;
    }

    s->setRepeating(false);
    
    if (s->getType() == Segment::Audio) {

        Composition *c = copyFrom->getComposition();

        for (int repeat = firstRepeat; repeat <= lastRepeat; ++repeat) {

            timeT wrappedFrom = segStart;
            timeT wrappedTo = segEndMarker;

            if (!expandRepeats) {
                wrappedFrom = from;
                wrappedTo = to;
            } else {
                if (repeat == firstRepeat) {
                    wrappedFrom = segStart + (from - segStart) % segDuration;
                }
                if (repeat == lastRepeat) {
                    wrappedTo = segStart + (to - segStart) % segDuration;
                }
            }

            if (wrappedFrom > segStart) {
                if (c) {
                    s->setAudioStartTime
                        (s->getAudioStartTime() +
                         c->getRealTimeDifference(segStart + repeat * segDuration,
                                                  from));
                }
                s->setStartTime(from);
            } else {
                s->setStartTime(segStart + repeat * segDuration);
            }

            if (wrappedTo < segEndMarker) {
                s->setEndMarkerTime(to);
                if (c) {
                    s->setAudioEndTime
                        (s->getAudioStartTime() +
                         c->getRealTimeDifference(segStart + repeat * segDuration,
                                                  to));
                }
            } else {
                s->setEndMarkerTime(segStart + (repeat + 1) * segDuration);
            }

            m_segments.insert(s);
            if (repeat < lastRepeat) {
                s = copyFrom->clone(false);
                s->setRepeating(false);
            }
        }

        m_partial = true;
        return;
    }

    // We have a normal (MIDI) segment.

    s->erase(s->begin(), s->end());
    
    for (int repeat = firstRepeat; repeat <= lastRepeat; ++repeat) {

        Segment::const_iterator ifrom = copyFrom->begin();
        Segment::const_iterator ito = copyFrom->end();

        if (!expandRepeats) {
            ifrom = copyFrom->findTime(from);
            ito = copyFrom->findTime(to);
        } else {
            if (repeat == firstRepeat) {
                ifrom = copyFrom->findTime
                    (segStart + (from - segStart) % segDuration);
            }
            if (repeat == lastRepeat) {
                ito = copyFrom->findTime
                    (segStart + (to - segStart) % segDuration);
            }
        }

        // For each event in the time range and before the end marker.
        for (Segment::const_iterator i = ifrom;
             i != ito && copyFrom->isBeforeEndMarker(i); ++i) {

            Event *e = (*i)->copyMoving(repeat * segDuration);

            s->insert(e);
        }
    }

    if (expandRepeats)
        s->setEndMarkerTime(to);

    // Make sure the end of the segment doesn't go past the end of the range.
    // Need to use the end marker time from the original segment, not s, 
    // because its value may depend on the composition it's in.
    if (segEndMarker > to)
        s->setEndMarkerTime(to);

    // Fix the beginning.
    
    timeT firstEventTime = s->getStartTime();
    
    // if the beginning was chopped off and the first event isn't at the start
    if (from > segStart  &&  firstEventTime > from) {
        // Expand the beginning to the left so that it starts at the expected
        // time (from).
        s->fillWithRests(from, firstEventTime);
    }

    // Fix zero-length segments.
    
    // if s is zero length
    if (s->getStartTime() == s->getEndMarkerTime()) {
        // Figure out what start and end time would look right.
        timeT finalStartTime = ((segStart > from) ? segStart : from);
        timeT finalEndTime = ((segEndMarker < to) ? segEndMarker : to);
        // Fill it up so it appears.
        s->fillWithRests(finalStartTime, finalEndTime);
    }

    m_segments.insert(s);

    m_partial = true;
}
Beispiel #27
0
// Initialize FitToBeatsCommand
// @author Tom Breton (Tehom)
void
FitToBeatsCommand::initialise(Segment *s)
{
    m_oldTempi.clear();
    m_newTempi.clear();
    m_oldSegments.clear();
    m_newSegments.clear();

    // Get the real times from the beat segment
    vecRealTime beatRealTimes;
    int success = 
        getBeatRealTimes(s, beatRealTimes);
    if(!success) { return; }

    // Store the current tempos
    getCurrentTempi(*m_composition, m_oldTempi);
    tempoT defaultTempo = m_composition->getCompositionDefaultTempo();

    // A temporary copy of the composition.  It is not intended to be
    // a complete copy, it just provides a place for new segments and
    // tempi to live until we have fully copied events to their new
    // state.
    Composition scratchComposition;
    scratchComposition.clear();
    scratchComposition.setCompositionDefaultTempo(defaultTempo);

    
    // Set tempos in scratchComposition such that each observed beat
    // in beatRealTimes takes one beatTime.
    {
        // Starting time is the same for both.
        timeT firstBeatTime = 
            m_composition->getElapsedTimeForRealTime(beatRealTimes[0]);

        unsigned int numBeats = beatRealTimes.size();

        // Get interval between beats from time signature.
        // Get time signature
        TimeSignature timeSig =
            m_composition->getTimeSignatureAt(firstBeatTime);
        timeT beatTime = timeSig.getBeatDuration();

        // We're going to visit the beats in reverse order, and always
        // remembering the next beat (the next beat time-wise, which
        // the iterator visited last time)
        vecRealTime::const_reverse_iterator i = beatRealTimes.rbegin();

        // Treat the final beat specially
        timeT    finalBeatTime = firstBeatTime + ((numBeats - 1) * beatTime);
        RealTime finalRealTime = beatRealTimes.back();
        scratchComposition.addTempoAtTime(finalBeatTime, defaultTempo, -1);
        // Step past it
        ++i;

        // Set up loop variables
        timeT    nextBeatTime = finalBeatTime;
        RealTime nextRealTime = finalRealTime;
        // nextTempo is unused, it will be used if we make ramped
        // tempi.
        /* tempoT   nextTempo    = defaultTempo; */


        // Treat all the other beats.
        while (i != beatRealTimes.rend()) {
            timeT        timeNow = nextBeatTime - beatTime;
            RealTime realTimeNow = *i;
            RealTime realTimeDelta = nextRealTime - realTimeNow;
            // Calculate what tempoT will get us to the right real
            // time.  For now, we use unramped tempi.
            tempoT rampTo = -1;
            tempoT tempo = Composition::timeRatioToTempo(realTimeDelta,
                                                         beatTime, rampTo);
            scratchComposition.addTempoAtTime(timeNow, tempo, rampTo);

            // Step
            nextBeatTime = timeNow;
            nextRealTime = realTimeNow;
            /* nextTempo    = tempo; */
            ++i;
        }
    }
    // We don't try to copy over tempo changes that are outside the
    // range of the groove segment (before or after).  We don't try to
    // correct for accumulated error.

    // Done setting Tempi

    // Collect tempi
    getCurrentTempi(scratchComposition, m_newTempi);


    // Copy all the events to scratchComposition.  The copies will be
    // at the same realtime but not the same timeT.  Even events in
    // the groove segment get copied.
    segmentcontainer &origSegments = m_composition->getSegments();
    for (Composition::iterator i = origSegments.begin();
         i != origSegments.end();
         ++i) {
        Segment * const oldSegment = *i;

        // We'd prefer to just make a segment with no events that's
        // otherwise the same as the old one but we can't.
        Segment *newSegment = oldSegment->clone(false);
        newSegment->clear();

        // Add the segments into appropriate containers.
        // scratchComposition owns the new segments during initialise,
        // but m_newSegments will own them after initialise returns.
        m_oldSegments.insert(oldSegment);
        m_newSegments.insert(newSegment);
        scratchComposition.addSegment(newSegment);

        //Iterate over notes in the old segment.
        const timeT earliestTime = 0;
        for (Segment::iterator j = oldSegment->findTime(earliestTime);
             oldSegment->isBeforeEndMarker(j);
             ++j)  {
            // Get the old-timed event times.
            timeT oldStartTime = (*j)->getAbsoluteTime();
            timeT duration = (*j)->getDuration();

            // Get the real event times.
            RealTime RealStartTime =
                m_composition->getElapsedRealTime(oldStartTime);

            RealTime RealEndTime;
            if (duration == 0) {
                RealEndTime = RealStartTime;
            }
            else {
                timeT oldEndTime = oldStartTime + duration;
                RealEndTime = 
                    m_composition->getElapsedRealTime(oldEndTime);
            }

            // Get the new target times.  Use scratchComposition
            // because its times use the new Tempi.
            timeT newStartTime =
                scratchComposition.getElapsedTimeForRealTime(RealStartTime);
            timeT newDuration;
            if (duration == 0) {
                newDuration = 0;
            }
            else {
                timeT newEndTime =
                    scratchComposition.getElapsedTimeForRealTime(RealEndTime);
                newDuration = newEndTime - newStartTime;
            }

            // Add a parallel event in the new segment.
            newSegment->insert(new Event(**j, newStartTime, newDuration));
        }
    }

    // Detach the segments before scratchComposition goes out of
    // scope.  m_newSegments contains exactly the segments that need
    // to be detached.
    for (segmentcontainer::iterator i = m_newSegments.begin();
         i != m_newSegments.end();
         ++i) {
        scratchComposition.weakDetachSegment(*i);
    }

    // We do the actual swapping of old <-> new in (un)execute.
}
Beispiel #28
0
	Composition getCounters(BWAPI::UnitType enemyUnitType)
	{
		auto allUnitTypes = BWAPI::UnitTypes::allUnitTypes();
			
		std::unordered_map<BWAPI::UnitType, int> unitTypeCounterAmount; //LF new name pls

		auto groundDamageType = enemyUnitType.groundWeapon().damageType();
		auto airDamageType = enemyUnitType.airWeapon().damageType();
		auto sizeType = enemyUnitType.size();
		bool flyer = enemyUnitType.isFlyer();

		for each (auto unitType in allUnitTypes)
		{	
			if (unitType.getRace() != util::game::getSelf()->getRace() || unitType.isHero() || unitType.isBuilding() || unitType.isWorker())
				continue;

			//if enemy unit flies and friendly unit can damage it...
			if (flyer)
			{
				if (unitType.airWeapon().damageAmount() > 0)
				{
					unitTypeCounterAmount[unitType]++;

					//if friendly unit flies and enemy unit can't damage it...
					if (!(enemyUnitType.airWeapon().damageAmount() > 0))
						unitTypeCounterAmount[unitType]++;

					//if enemy unit damage type is concussive and friendly unit size is small... 
					if (airDamageType == BWAPI::DamageTypes::Concussive && unitType.size() == BWAPI::UnitSizeTypes::Small)
						unitTypeCounterAmount[unitType]++;

					//if enemy unit damage type is explosive and friendly unit size is large... 
					else if (airDamageType == BWAPI::DamageTypes::Explosive && unitType.size() == BWAPI::UnitSizeTypes::Large)
						unitTypeCounterAmount[unitType]++;

					//if enemy unit size is small and friendly damage type is explosive...
					if (sizeType == BWAPI::UnitSizeTypes::Small && unitType.airWeapon().damageType() == BWAPI::DamageTypes::Explosive)
						unitTypeCounterAmount[unitType]++;

					//if enemy unit size is medium or large and friendly damage type is concussive...
					else if ((sizeType == BWAPI::UnitSizeTypes::Medium || sizeType == BWAPI::UnitSizeTypes::Large) && unitType.airWeapon().damageType() == BWAPI::DamageTypes::Concussive)
						unitTypeCounterAmount[unitType]++;
				}
				else
					continue;
			}
					

			//if enemy unit is ground unit and friendly unit can damage it...
			if (!flyer && unitType.groundWeapon().damageAmount() > 0)
			{
				unitTypeCounterAmount[unitType]++;

				//if friendly unit flies and enemy unit can't damage it...
				if (unitType.isFlyer() && !(enemyUnitType.airWeapon().damageAmount() > 0))
					unitTypeCounterAmount[unitType]++;

				//if enemy unit damage type is concussive and friendly unit size is small... 
				if (groundDamageType == BWAPI::DamageTypes::Concussive && unitType.size() == BWAPI::UnitSizeTypes::Small)
					unitTypeCounterAmount[unitType]++;

				//if enemy unit damage type is explosive and friendly unit size is large... 
				else if (groundDamageType == BWAPI::DamageTypes::Explosive && unitType.size() == BWAPI::UnitSizeTypes::Large)
					unitTypeCounterAmount[unitType]++;

				//if enemy unit size is small and friendly damage type is explosive...
				if (sizeType == BWAPI::UnitSizeTypes::Small && unitType.groundWeapon().damageType() == BWAPI::DamageTypes::Explosive)
					unitTypeCounterAmount[unitType]++;

				//if enemy unit size is medium or large and friendly damage type is concussive...
				else if ((sizeType == BWAPI::UnitSizeTypes::Medium || sizeType == BWAPI::UnitSizeTypes::Large) && unitType.groundWeapon().damageType() == BWAPI::DamageTypes::Concussive)
					unitTypeCounterAmount[unitType]++;
			}
			else
				continue;
		}
		
		Composition counterComposition;
		for (auto &unitType = unitTypeCounterAmount.begin(); unitType != unitTypeCounterAmount.end(); unitType++)
		{
			if (unitType->first == BWAPI::UnitTypes::Spell_Scanner_Sweep)
				counterComposition.addType(BWAPI::UnitTypes::Terran_Comsat_Station, unitType->second);
			else if (unitType->first == BWAPI::UnitTypes::Terran_Siege_Tank_Siege_Mode)
				counterComposition.addType(BWAPI::UnitTypes::Terran_Siege_Tank_Tank_Mode, unitType->second);
			else if(unitType->first == BWAPI::UnitTypes::Terran_Vulture_Spider_Mine)
				counterComposition.addType(BWAPI::UnitTypes::Terran_Vulture, unitType->second);
			else
				counterComposition.addType(unitType->first, unitType->second);
		}
		return counterComposition;
	}
Beispiel #29
0
void
LyricEditDialog::unparse()
{
    // This and SetLyricsCommand::execute() are opposites that will
    // need to be kept in sync with any changes in one another.  (They
    // should really both be in a common lyric management class.)

    countVerses();

    Composition *comp = m_segment->getComposition();

    bool firstNote = true;
    timeT lastTime = m_segment->getStartTime();
    int lastBarNo = comp->getBarNumber(lastTime);
    std::map<int, bool> haveLyric;

    QString fragment = QString("[%1] ").arg(lastBarNo + 1);

    m_skeleton = fragment;
    m_texts.clear();
    for (int v = 0; v < m_verseCount; ++v) {
        m_texts.push_back(fragment);
        haveLyric[v] = false;
    }

    for (Segment::iterator i = m_segment->begin();
         m_segment->isBeforeEndMarker(i); ++i) {

        bool isNote = (*i)->isa(Note::EventType);
        bool isLyric = false;

        if (!isNote) {
            if ((*i)->isa(Text::EventType)) {
                std::string textType;
                if ((*i)->get<String>(Text::TextTypePropertyName, textType) &&
                    textType == Text::Lyric) {
                    isLyric = true;
                }
            }
        } else {
            if ((*i)->has(BaseProperties::TIED_BACKWARD) &&
                (*i)->get<Bool>(BaseProperties::TIED_BACKWARD)) {
                continue;
            }
        }

        if (!isNote && !isLyric) continue;

        timeT myTime = (*i)->getNotationAbsoluteTime();
        int myBarNo = comp->getBarNumber(myTime);

        if (myBarNo > lastBarNo) {

            fragment = "";

            while (myBarNo > lastBarNo) {
                fragment += " /";
                ++lastBarNo;
            }

            fragment += QString("\n[%1] ").arg(myBarNo + 1);

            m_skeleton += fragment;
            for (int v = 0; v < m_verseCount; ++v) m_texts[v] += fragment;
        }

        if (isNote) {
            if ((myTime > lastTime) || firstNote) {
                m_skeleton += " .";
                for (int v = 0; v < m_verseCount; ++v) {
                    if (!haveLyric[v]) m_texts[v] += " .";
                    haveLyric[v] = false;
                }
                lastTime = myTime;
                firstNote = false;
            }
        }

        if (isLyric) {

            std::string ssyllable;
            (*i)->get<String>(Text::TextPropertyName, ssyllable);

            long verse = 0;
            (*i)->get<Int>(Text::LyricVersePropertyName, verse);

            QString syllable(strtoqstr(ssyllable));
            syllable.replace(QRegExp("\\s+"), "~");

            m_texts[verse] += " " + syllable;
            haveLyric[verse] = true;
        }
    }

    if (!m_texts.empty()) {
        m_textEdit->setPlainText(m_texts[0]);
    } else {
        m_texts.push_back(m_skeleton);
    }
}
Beispiel #30
0
bool RG21Loader::load(const QString &fileName, Composition &comp)
{
    m_composition = &comp;
    comp.clear();

    QFile file(fileName);
    if (file.open(QIODevice::ReadOnly)) {
        m_stream = new QTextStream(&file);
    } else {
        return false;
    }

    m_studio->unassignAllInstruments();

    while (!m_stream->atEnd()) {

        if (!readNextLine())
            break;

        QString firstToken = m_tokens.first();

        if (firstToken == "Staves" || firstToken == "Staffs") { // nb staves

            m_nbStaves = m_tokens[1].toUInt();

        } else if (firstToken == "Name") { // Staff name

            m_currentStaffName = m_tokens[1]; // we don't do anything with it yet
            m_currentSegment = new Segment;
            ++m_currentSegmentNb;

        } else if (firstToken == "Clef") {

            parseClef();

        } else if (firstToken == "Key") {

            parseKey();

        } else if (firstToken == "Metronome") {

            if (!readNextLine())
                break;
            parseMetronome();

        } else if (firstToken == ":") { // chord

            m_tokens.removeFirst(); // get rid of 1st token ':'
            parseChordItem();

        } else if (firstToken == "Rest") { // rest

            if (!readNextLine())
                break;

            parseRest();

        } else if (firstToken == "Text") {

            if (!readNextLine())
                break;

            parseText();

        } else if (firstToken == "Group") {

            if (!readNextLine())
                break;

            parseGroupStart();

        } else if (firstToken == "Mark") {

            if (m_tokens[1] == "start")
                parseIndicationStart();
            else if (m_tokens[1] == "end")
                closeIndication();

        } else if (firstToken == "Bar") {

            parseBarType();

        } else if (firstToken == "Stave") {

            parseStaveType();

        } else if (firstToken == "End") {

            if (m_inGroup)
                closeGroup();
            else
                closeSegment();

        } else {

            RG_DEBUG << "RG21Loader::parse: Unsupported element type \"" << firstToken << "\", ignoring" << endl;
        }
    }

    delete m_stream;
    m_stream = 0;

    return true;
}