text
stringlengths
54
60.6k
<commit_before>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE JPetParamAndDataFactoryTest #include <boost/test/unit_test.hpp> #include "JPetParamAndDataFactory.h" #include <boost/filesystem.hpp> BOOST_AUTO_TEST_SUITE(FirstSuite) BOOST_AUTO_TEST_CASE( scin ) { JPetBarrelSlot p_barrelSlot(1, true, "name", 1, 1); JPetScin scin = param_and_data_factory::makeScin(1, 2.0, 3.0, 4.0, 5.0, p_barrelSlot ); BOOST_REQUIRE_EQUAL(scin.getID(), 1); BOOST_REQUIRE_EQUAL(scin.getAttenLen(), 2.0); JPetScin::Dimension dim = JPetScin::kLength; BOOST_REQUIRE_EQUAL(scin.getScinSize(dim), 3.0); dim = JPetScin::kHeight; BOOST_REQUIRE_EQUAL(scin.getScinSize(dim), 4.0); dim = JPetScin::kWidth; BOOST_REQUIRE_EQUAL(scin.getScinSize(dim), 5.0); BOOST_REQUIRE_EQUAL(scin.getBarrelSlot().getID(), p_barrelSlot.getID()); BOOST_REQUIRE_EQUAL(scin.getBarrelSlot().isActive(), p_barrelSlot.isActive()); BOOST_REQUIRE_EQUAL(scin.getBarrelSlot().getName(), p_barrelSlot.getName()); BOOST_REQUIRE_EQUAL(scin.getBarrelSlot().getTheta(), p_barrelSlot.getTheta()); BOOST_REQUIRE_EQUAL(scin.getBarrelSlot().getInFrameID(), p_barrelSlot.getInFrameID()); } BOOST_AUTO_TEST_CASE( feb ) { JPetTRB p_TRB(1, 2, 2); const std::string status = "status"; const std::string description = "description"; JPetFEB feb = param_and_data_factory::makeFEB( 1, true, status, description, 2, 7, 1, 0, p_TRB); BOOST_REQUIRE_EQUAL(feb.getID(), 1); BOOST_REQUIRE_EQUAL(feb.isActive(), true); BOOST_REQUIRE_EQUAL(feb.status(), "status"); BOOST_REQUIRE_EQUAL(feb.description(), "description"); BOOST_REQUIRE_EQUAL(feb.version(), 2); BOOST_REQUIRE_EQUAL(feb.getCreator(), 7); BOOST_REQUIRE_EQUAL(feb.getNtimeOutsPerInput(), 1); BOOST_REQUIRE_EQUAL(feb.getNnotimeOutsPerInput(), 0); BOOST_REQUIRE_EQUAL(feb.getTRB().getID(), p_TRB.getID()); BOOST_REQUIRE_EQUAL(feb.getTRB().getType(), p_TRB.getType()); BOOST_REQUIRE_EQUAL(feb.getTRB().getChannel(), p_TRB.getChannel()); } BOOST_AUTO_TEST_CASE( layer ) { const std::string name = "name"; JPetFrame frame(1, true, "status", "description", 2, 3); JPetLayer layer = param_and_data_factory::makeLayer(1, true, name, 3, frame); BOOST_REQUIRE_EQUAL(layer.getID(), 1); BOOST_REQUIRE_EQUAL(layer.getIsActive(), true); BOOST_REQUIRE_EQUAL(layer.getName(), "name"); BOOST_REQUIRE_EQUAL(layer.getRadius(), 3); BOOST_REQUIRE_EQUAL(layer.getFrame().getID(), frame.getID()); BOOST_REQUIRE_EQUAL(layer.getFrame().getIsActive(), frame.getIsActive()); BOOST_REQUIRE_EQUAL(layer.getFrame().getStatus(), frame.getStatus()); BOOST_REQUIRE_EQUAL(layer.getFrame().getCreator(), frame.getCreator()); } BOOST_AUTO_TEST_CASE( hit ) { JPetBarrelSlot bs(1, true, "name", 2, 3); JPetScin sc(1, 2, 3, 4, 5); JPetPhysSignal p_sigA(true); JPetPhysSignal p_sigB(true); p_sigA.setTime(1); p_sigA.setPhe(2); p_sigB.setTime(3); p_sigB.setPhe(4); TVector3 position(6.0, 7.0, 8.0); JPetHit hit = param_and_data_factory::makeHit(0.0f, 1.0f, 2.0f, 3.0f, position, p_sigA, p_sigB, bs, sc, 4.0f, 5.0f); BOOST_REQUIRE_EQUAL(hit.getEnergy(), 0.0f); BOOST_REQUIRE_EQUAL(hit.getQualityOfEnergy(), 1.0f); BOOST_REQUIRE_EQUAL(hit.getTime(), 2.0f); BOOST_REQUIRE_EQUAL(hit.getQualityOfTime(), 3.0f); BOOST_REQUIRE_EQUAL(hit.getTimeDiff(), 5.0f); BOOST_REQUIRE_EQUAL(hit.getQualityOfTimeDiff(), 4.0f); BOOST_REQUIRE_EQUAL(hit.getPosX(), 6.0 ); BOOST_REQUIRE_EQUAL(hit.getPosY(), 7.0 ); BOOST_REQUIRE_EQUAL(hit.getPosZ(), 8.0 ); BOOST_REQUIRE(hit.isSignalASet()); BOOST_REQUIRE(hit.isSignalBSet()); BOOST_REQUIRE_EQUAL(hit.getBarrelSlot().getID(), bs.getID() ); BOOST_REQUIRE_EQUAL(hit.getBarrelSlot().isActive(), bs.isActive() ); BOOST_REQUIRE_EQUAL(hit.getBarrelSlot().getName(), bs.getName() ); BOOST_REQUIRE_EQUAL(hit.getBarrelSlot().getTheta(), bs.getTheta() ); BOOST_REQUIRE_EQUAL(hit.getScintillator().getID(), sc.getID() ); BOOST_REQUIRE_EQUAL(hit.getScintillator().getAttenLen(), sc.getAttenLen() ); BOOST_REQUIRE_EQUAL(hit.getSignalA().getTime(), p_sigA.getTime() ); BOOST_REQUIRE_EQUAL(hit.getSignalA().getPhe(), p_sigA.getPhe() ); BOOST_REQUIRE_EQUAL(hit.getSignalB().getTime(), p_sigB.getTime() ); BOOST_REQUIRE_EQUAL(hit.getSignalB().getPhe(), p_sigB.getPhe() ); } BOOST_AUTO_TEST_CASE( sigCh ) { JPetPM pm(1, ""); pm.setHVopt(2); pm.setHVset(3); JPetTRB trb(1, 2, 3); JPetFEB feb(1); feb.setTRB(trb); JPetTOMBChannel channel(1); channel.setTRB(trb); JPetSigCh::EdgeType type = JPetSigCh::Trailing; Int_t daqch; JPetSigCh sigCh = param_and_data_factory::makeSigCh(pm, trb, feb, channel, 4.0, type, 3.0, daqch, 0.0); BOOST_REQUIRE_EQUAL(sigCh.getPM().getHVopt(), pm.getHVopt()); BOOST_REQUIRE_EQUAL(sigCh.getPM().getHVset(), pm.getHVset()); BOOST_REQUIRE_EQUAL(sigCh.getTRB().getID(), trb.getID()); BOOST_REQUIRE_EQUAL(sigCh.getTRB().getType(), trb.getType()); BOOST_REQUIRE_EQUAL(sigCh.getTRB().getChannel(), trb.getChannel()); BOOST_REQUIRE_EQUAL(sigCh.getFEB().getID(), feb.getID()); BOOST_REQUIRE_EQUAL(sigCh.getFEB().getTRB().getID(), feb.getTRB().getID()); BOOST_REQUIRE_EQUAL(sigCh.getTOMBChannel().getChannel(), channel.getChannel()); BOOST_REQUIRE_EQUAL(sigCh.getTOMBChannel().getTRB().getID(), channel.getTRB().getID()); BOOST_REQUIRE_EQUAL(sigCh.getValue(), 4.0); BOOST_REQUIRE_EQUAL(sigCh.getThresholdNumber(), 0.0); BOOST_REQUIRE_EQUAL(sigCh.getThreshold(), 3.0); BOOST_REQUIRE_EQUAL(sigCh.getType(), type); BOOST_REQUIRE_EQUAL(sigCh.getDAQch(), daqch); } BOOST_AUTO_TEST_CASE( barrelSlot ) { const std::string name = "name"; JPetLayer p_layer(1, true, "name", 3); JPetBarrelSlot barrelSlot = param_and_data_factory::makeBarrelSlot(p_layer, 1 , true, name, 0, 2); BOOST_REQUIRE_EQUAL(barrelSlot.getID(), 1); BOOST_REQUIRE(barrelSlot.isActive()); BOOST_REQUIRE_EQUAL(barrelSlot.getName(), "name"); BOOST_REQUIRE_EQUAL(barrelSlot.getTheta(), 0); BOOST_REQUIRE_EQUAL(barrelSlot.getInFrameID(), 2); BOOST_REQUIRE_EQUAL(barrelSlot.getLayer().getID(), p_layer.getID()); BOOST_REQUIRE_EQUAL(barrelSlot.getLayer().getRadius(), p_layer.getRadius()); } BOOST_AUTO_TEST_CASE( timeWindow ) { JPetSigCh::EdgeType type = JPetSigCh::Trailing; std::vector<JPetSigCh> vec = {JPetSigCh(type, 1), JPetSigCh(type, 1)}; JPetTimeWindow timeWindow = param_and_data_factory::makeTimeWindow(vec, 1); BOOST_REQUIRE_EQUAL(timeWindow.getNumberOfSigCh(), 2); BOOST_REQUIRE_EQUAL(timeWindow.getIndex(), 1); } BOOST_AUTO_TEST_CASE( pm ) { JPetPM::Side side = JPetPM::SideA; JPetBarrelSlot p_barrelSlot(1, true, "name", 2, 3); JPetScin p_scin(1, 2, 3, 4, 5); JPetFEB p_FEB(1, true, "p_status", "p_description", 2, 3, 4, 5); std::pair<float, float> gain(3.0, 4.0); JPetPM pm = param_and_data_factory::makePM(side, 1, 1, 2, gain, "no writing", p_FEB, p_scin, p_barrelSlot); BOOST_REQUIRE_EQUAL(pm.getID(), 1); BOOST_REQUIRE_EQUAL(pm.getHVset(), 1); BOOST_REQUIRE_EQUAL(pm.getHVopt(), 2); BOOST_REQUIRE_EQUAL(pm.getSide(), JPetPM::SideA); BOOST_REQUIRE_EQUAL(pm.getHVgain().first, 3.0); BOOST_REQUIRE_EQUAL(pm.getHVgain().second, 4.0); BOOST_REQUIRE_EQUAL(pm.getDescription(), "no writing"); BOOST_REQUIRE_EQUAL(pm.getScin().getID(), p_scin.getID() ); BOOST_REQUIRE_EQUAL(pm.getScin().getAttenLen(), p_scin.getAttenLen() ); BOOST_REQUIRE_EQUAL(pm.getBarrelSlot().getID(), p_barrelSlot.getID()); BOOST_REQUIRE_EQUAL(pm.getBarrelSlot().getName(), p_barrelSlot.getName()); BOOST_REQUIRE_EQUAL(pm.getFEB().getID(), p_FEB.getID()); BOOST_REQUIRE_EQUAL(pm.getFEB().isActive(), p_FEB.isActive()); } BOOST_AUTO_TEST_CASE( baseSignal ) { JPetPM pm(1, ""); pm.setHVopt(2); pm.setHVset(3); JPetBarrelSlot p_barrelSlot(1, true, "name", 2, 3); JPetBaseSignal bs = param_and_data_factory::makeBaseSignal(1, pm, p_barrelSlot); BOOST_REQUIRE_EQUAL(bs.getTimeWindowIndex(), 1 ); BOOST_REQUIRE_EQUAL(bs.getPM().getHVopt(), pm.getHVopt() ); BOOST_REQUIRE_EQUAL(bs.getPM().getHVset(), pm.getHVset() ); BOOST_REQUIRE_EQUAL(bs.getBarrelSlot().getID(), p_barrelSlot.getID()); BOOST_REQUIRE_EQUAL(bs.getBarrelSlot().getName(), p_barrelSlot.getName()); } BOOST_AUTO_TEST_CASE( physSignal ) { JPetRecoSignal recoSignal(2); JPetPhysSignal ps = param_and_data_factory::makePhysSignal( 1, 2, 3, 4, recoSignal); BOOST_REQUIRE_EQUAL(ps.getTime(), 1 ); BOOST_REQUIRE_EQUAL(ps.getQualityOfTime(), 2 ); BOOST_REQUIRE_EQUAL(ps.getPhe(), 3 ); BOOST_REQUIRE_EQUAL(ps.getQualityOfPhe(), 4 ); BOOST_REQUIRE_EQUAL(ps.getRecoSignal().getAmplitude(), recoSignal.getAmplitude() ); BOOST_REQUIRE_EQUAL(ps.getRecoSignal().getCharge(), recoSignal.getCharge() ); BOOST_REQUIRE_EQUAL(ps.getRecoSignal().getOffset(), recoSignal.getOffset() ); } BOOST_AUTO_TEST_CASE( rawSignal ) { JPetSigCh::EdgeType type = JPetSigCh::Trailing; std::vector<JPetSigCh> vec = {JPetSigCh(type, 1), JPetSigCh(type, 1)}; JPetRawSignal rs = param_and_data_factory::makeRawSignal(vec); BOOST_REQUIRE_EQUAL(rs.getNumberOfPoints(type), 2); } BOOST_AUTO_TEST_CASE( tombChannel ) { JPetPM pm(1, ""); pm.setHVopt(2); pm.setHVset(3); JPetTRB trb(1, 2, 3); JPetFEB feb(1, true, "p_status", "p_description", 2, 3, 4, 5); JPetTOMBChannel tombChannel = param_and_data_factory::makeTOMBChannel(3, feb, trb, pm, 4, 5, 6); BOOST_REQUIRE_EQUAL(tombChannel.getChannel(), 3); BOOST_REQUIRE_EQUAL(tombChannel.getThreshold(), 4); BOOST_REQUIRE_EQUAL(tombChannel.getLocalChannelNumber(), 5); BOOST_REQUIRE_EQUAL(tombChannel.getFEBInputNumber(), 6); BOOST_REQUIRE_EQUAL(tombChannel.getTRB().getID(), trb.getID()); BOOST_REQUIRE_EQUAL(tombChannel.getTRB().getType(), trb.getType()); BOOST_REQUIRE_EQUAL(tombChannel.getTRB().getChannel(), trb.getChannel()); BOOST_REQUIRE_EQUAL(tombChannel.getFEB().getID() , feb.getID()); BOOST_REQUIRE_EQUAL(tombChannel.getFEB().isActive() , feb.isActive()); BOOST_REQUIRE_EQUAL(tombChannel.getPM().getHVopt(), pm.getHVopt()); BOOST_REQUIRE_EQUAL(tombChannel.getPM().getHVset(), pm.getHVset()); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Temporarily comment out UT for TimeWindow factory<commit_after>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE JPetParamAndDataFactoryTest #include <boost/test/unit_test.hpp> #include "JPetParamAndDataFactory.h" #include <boost/filesystem.hpp> BOOST_AUTO_TEST_SUITE(FirstSuite) BOOST_AUTO_TEST_CASE( scin ) { JPetBarrelSlot p_barrelSlot(1, true, "name", 1, 1); JPetScin scin = param_and_data_factory::makeScin(1, 2.0, 3.0, 4.0, 5.0, p_barrelSlot ); BOOST_REQUIRE_EQUAL(scin.getID(), 1); BOOST_REQUIRE_EQUAL(scin.getAttenLen(), 2.0); JPetScin::Dimension dim = JPetScin::kLength; BOOST_REQUIRE_EQUAL(scin.getScinSize(dim), 3.0); dim = JPetScin::kHeight; BOOST_REQUIRE_EQUAL(scin.getScinSize(dim), 4.0); dim = JPetScin::kWidth; BOOST_REQUIRE_EQUAL(scin.getScinSize(dim), 5.0); BOOST_REQUIRE_EQUAL(scin.getBarrelSlot().getID(), p_barrelSlot.getID()); BOOST_REQUIRE_EQUAL(scin.getBarrelSlot().isActive(), p_barrelSlot.isActive()); BOOST_REQUIRE_EQUAL(scin.getBarrelSlot().getName(), p_barrelSlot.getName()); BOOST_REQUIRE_EQUAL(scin.getBarrelSlot().getTheta(), p_barrelSlot.getTheta()); BOOST_REQUIRE_EQUAL(scin.getBarrelSlot().getInFrameID(), p_barrelSlot.getInFrameID()); } BOOST_AUTO_TEST_CASE( feb ) { JPetTRB p_TRB(1, 2, 2); const std::string status = "status"; const std::string description = "description"; JPetFEB feb = param_and_data_factory::makeFEB( 1, true, status, description, 2, 7, 1, 0, p_TRB); BOOST_REQUIRE_EQUAL(feb.getID(), 1); BOOST_REQUIRE_EQUAL(feb.isActive(), true); BOOST_REQUIRE_EQUAL(feb.status(), "status"); BOOST_REQUIRE_EQUAL(feb.description(), "description"); BOOST_REQUIRE_EQUAL(feb.version(), 2); BOOST_REQUIRE_EQUAL(feb.getCreator(), 7); BOOST_REQUIRE_EQUAL(feb.getNtimeOutsPerInput(), 1); BOOST_REQUIRE_EQUAL(feb.getNnotimeOutsPerInput(), 0); BOOST_REQUIRE_EQUAL(feb.getTRB().getID(), p_TRB.getID()); BOOST_REQUIRE_EQUAL(feb.getTRB().getType(), p_TRB.getType()); BOOST_REQUIRE_EQUAL(feb.getTRB().getChannel(), p_TRB.getChannel()); } BOOST_AUTO_TEST_CASE( layer ) { const std::string name = "name"; JPetFrame frame(1, true, "status", "description", 2, 3); JPetLayer layer = param_and_data_factory::makeLayer(1, true, name, 3, frame); BOOST_REQUIRE_EQUAL(layer.getID(), 1); BOOST_REQUIRE_EQUAL(layer.getIsActive(), true); BOOST_REQUIRE_EQUAL(layer.getName(), "name"); BOOST_REQUIRE_EQUAL(layer.getRadius(), 3); BOOST_REQUIRE_EQUAL(layer.getFrame().getID(), frame.getID()); BOOST_REQUIRE_EQUAL(layer.getFrame().getIsActive(), frame.getIsActive()); BOOST_REQUIRE_EQUAL(layer.getFrame().getStatus(), frame.getStatus()); BOOST_REQUIRE_EQUAL(layer.getFrame().getCreator(), frame.getCreator()); } BOOST_AUTO_TEST_CASE( hit ) { JPetBarrelSlot bs(1, true, "name", 2, 3); JPetScin sc(1, 2, 3, 4, 5); JPetPhysSignal p_sigA(true); JPetPhysSignal p_sigB(true); p_sigA.setTime(1); p_sigA.setPhe(2); p_sigB.setTime(3); p_sigB.setPhe(4); TVector3 position(6.0, 7.0, 8.0); JPetHit hit = param_and_data_factory::makeHit(0.0f, 1.0f, 2.0f, 3.0f, position, p_sigA, p_sigB, bs, sc, 4.0f, 5.0f); BOOST_REQUIRE_EQUAL(hit.getEnergy(), 0.0f); BOOST_REQUIRE_EQUAL(hit.getQualityOfEnergy(), 1.0f); BOOST_REQUIRE_EQUAL(hit.getTime(), 2.0f); BOOST_REQUIRE_EQUAL(hit.getQualityOfTime(), 3.0f); BOOST_REQUIRE_EQUAL(hit.getTimeDiff(), 5.0f); BOOST_REQUIRE_EQUAL(hit.getQualityOfTimeDiff(), 4.0f); BOOST_REQUIRE_EQUAL(hit.getPosX(), 6.0 ); BOOST_REQUIRE_EQUAL(hit.getPosY(), 7.0 ); BOOST_REQUIRE_EQUAL(hit.getPosZ(), 8.0 ); BOOST_REQUIRE(hit.isSignalASet()); BOOST_REQUIRE(hit.isSignalBSet()); BOOST_REQUIRE_EQUAL(hit.getBarrelSlot().getID(), bs.getID() ); BOOST_REQUIRE_EQUAL(hit.getBarrelSlot().isActive(), bs.isActive() ); BOOST_REQUIRE_EQUAL(hit.getBarrelSlot().getName(), bs.getName() ); BOOST_REQUIRE_EQUAL(hit.getBarrelSlot().getTheta(), bs.getTheta() ); BOOST_REQUIRE_EQUAL(hit.getScintillator().getID(), sc.getID() ); BOOST_REQUIRE_EQUAL(hit.getScintillator().getAttenLen(), sc.getAttenLen() ); BOOST_REQUIRE_EQUAL(hit.getSignalA().getTime(), p_sigA.getTime() ); BOOST_REQUIRE_EQUAL(hit.getSignalA().getPhe(), p_sigA.getPhe() ); BOOST_REQUIRE_EQUAL(hit.getSignalB().getTime(), p_sigB.getTime() ); BOOST_REQUIRE_EQUAL(hit.getSignalB().getPhe(), p_sigB.getPhe() ); } BOOST_AUTO_TEST_CASE( sigCh ) { JPetPM pm(1, ""); pm.setHVopt(2); pm.setHVset(3); JPetTRB trb(1, 2, 3); JPetFEB feb(1); feb.setTRB(trb); JPetTOMBChannel channel(1); channel.setTRB(trb); JPetSigCh::EdgeType type = JPetSigCh::Trailing; Int_t daqch; JPetSigCh sigCh = param_and_data_factory::makeSigCh(pm, trb, feb, channel, 4.0, type, 3.0, daqch, 0.0); BOOST_REQUIRE_EQUAL(sigCh.getPM().getHVopt(), pm.getHVopt()); BOOST_REQUIRE_EQUAL(sigCh.getPM().getHVset(), pm.getHVset()); BOOST_REQUIRE_EQUAL(sigCh.getTRB().getID(), trb.getID()); BOOST_REQUIRE_EQUAL(sigCh.getTRB().getType(), trb.getType()); BOOST_REQUIRE_EQUAL(sigCh.getTRB().getChannel(), trb.getChannel()); BOOST_REQUIRE_EQUAL(sigCh.getFEB().getID(), feb.getID()); BOOST_REQUIRE_EQUAL(sigCh.getFEB().getTRB().getID(), feb.getTRB().getID()); BOOST_REQUIRE_EQUAL(sigCh.getTOMBChannel().getChannel(), channel.getChannel()); BOOST_REQUIRE_EQUAL(sigCh.getTOMBChannel().getTRB().getID(), channel.getTRB().getID()); BOOST_REQUIRE_EQUAL(sigCh.getValue(), 4.0); BOOST_REQUIRE_EQUAL(sigCh.getThresholdNumber(), 0.0); BOOST_REQUIRE_EQUAL(sigCh.getThreshold(), 3.0); BOOST_REQUIRE_EQUAL(sigCh.getType(), type); BOOST_REQUIRE_EQUAL(sigCh.getDAQch(), daqch); } BOOST_AUTO_TEST_CASE( barrelSlot ) { const std::string name = "name"; JPetLayer p_layer(1, true, "name", 3); JPetBarrelSlot barrelSlot = param_and_data_factory::makeBarrelSlot(p_layer, 1 , true, name, 0, 2); BOOST_REQUIRE_EQUAL(barrelSlot.getID(), 1); BOOST_REQUIRE(barrelSlot.isActive()); BOOST_REQUIRE_EQUAL(barrelSlot.getName(), "name"); BOOST_REQUIRE_EQUAL(barrelSlot.getTheta(), 0); BOOST_REQUIRE_EQUAL(barrelSlot.getInFrameID(), 2); BOOST_REQUIRE_EQUAL(barrelSlot.getLayer().getID(), p_layer.getID()); BOOST_REQUIRE_EQUAL(barrelSlot.getLayer().getRadius(), p_layer.getRadius()); } /* BOOST_AUTO_TEST_CASE( timeWindow ) { JPetSigCh::EdgeType type = JPetSigCh::Trailing; std::vector<JPetSigCh> vec ={JPetSigCh(type, 1), JPetSigCh(type, 1)}; JPetTimeWindow timeWindow = param_and_data_factory::makeTimeWindow(vec); BOOST_REQUIRE_EQUAL(timeWindow.getNumberOfEvents(), 2); } */ BOOST_AUTO_TEST_CASE( pm ) { JPetPM::Side side = JPetPM::SideA; JPetBarrelSlot p_barrelSlot(1, true, "name", 2, 3); JPetScin p_scin(1, 2, 3, 4, 5); JPetFEB p_FEB(1, true, "p_status", "p_description", 2, 3, 4, 5); std::pair<float, float> gain(3.0, 4.0); JPetPM pm = param_and_data_factory::makePM(side, 1, 1, 2, gain, "no writing", p_FEB, p_scin, p_barrelSlot); BOOST_REQUIRE_EQUAL(pm.getID(), 1); BOOST_REQUIRE_EQUAL(pm.getHVset(), 1); BOOST_REQUIRE_EQUAL(pm.getHVopt(), 2); BOOST_REQUIRE_EQUAL(pm.getSide(), JPetPM::SideA); BOOST_REQUIRE_EQUAL(pm.getHVgain().first, 3.0); BOOST_REQUIRE_EQUAL(pm.getHVgain().second, 4.0); BOOST_REQUIRE_EQUAL(pm.getDescription(), "no writing"); BOOST_REQUIRE_EQUAL(pm.getScin().getID(), p_scin.getID() ); BOOST_REQUIRE_EQUAL(pm.getScin().getAttenLen(), p_scin.getAttenLen() ); BOOST_REQUIRE_EQUAL(pm.getBarrelSlot().getID(), p_barrelSlot.getID()); BOOST_REQUIRE_EQUAL(pm.getBarrelSlot().getName(), p_barrelSlot.getName()); BOOST_REQUIRE_EQUAL(pm.getFEB().getID(), p_FEB.getID()); BOOST_REQUIRE_EQUAL(pm.getFEB().isActive(), p_FEB.isActive()); } BOOST_AUTO_TEST_CASE( baseSignal ) { JPetPM pm(1, ""); pm.setHVopt(2); pm.setHVset(3); JPetBarrelSlot p_barrelSlot(1, true, "name", 2, 3); JPetBaseSignal bs = param_and_data_factory::makeBaseSignal(1, pm, p_barrelSlot); BOOST_REQUIRE_EQUAL(bs.getTimeWindowIndex(), 1 ); BOOST_REQUIRE_EQUAL(bs.getPM().getHVopt(), pm.getHVopt() ); BOOST_REQUIRE_EQUAL(bs.getPM().getHVset(), pm.getHVset() ); BOOST_REQUIRE_EQUAL(bs.getBarrelSlot().getID(), p_barrelSlot.getID()); BOOST_REQUIRE_EQUAL(bs.getBarrelSlot().getName(), p_barrelSlot.getName()); } BOOST_AUTO_TEST_CASE( physSignal ) { JPetRecoSignal recoSignal(2); JPetPhysSignal ps = param_and_data_factory::makePhysSignal( 1, 2, 3, 4, recoSignal); BOOST_REQUIRE_EQUAL(ps.getTime(), 1 ); BOOST_REQUIRE_EQUAL(ps.getQualityOfTime(), 2 ); BOOST_REQUIRE_EQUAL(ps.getPhe(), 3 ); BOOST_REQUIRE_EQUAL(ps.getQualityOfPhe(), 4 ); BOOST_REQUIRE_EQUAL(ps.getRecoSignal().getAmplitude(), recoSignal.getAmplitude() ); BOOST_REQUIRE_EQUAL(ps.getRecoSignal().getCharge(), recoSignal.getCharge() ); BOOST_REQUIRE_EQUAL(ps.getRecoSignal().getOffset(), recoSignal.getOffset() ); } BOOST_AUTO_TEST_CASE( rawSignal ) { JPetSigCh::EdgeType type = JPetSigCh::Trailing; std::vector<JPetSigCh> vec = {JPetSigCh(type, 1), JPetSigCh(type, 1)}; JPetRawSignal rs = param_and_data_factory::makeRawSignal(vec); BOOST_REQUIRE_EQUAL(rs.getNumberOfPoints(type), 2); } BOOST_AUTO_TEST_CASE( tombChannel ) { JPetPM pm(1, ""); pm.setHVopt(2); pm.setHVset(3); JPetTRB trb(1, 2, 3); JPetFEB feb(1, true, "p_status", "p_description", 2, 3, 4, 5); JPetTOMBChannel tombChannel = param_and_data_factory::makeTOMBChannel(3, feb, trb, pm, 4, 5, 6); BOOST_REQUIRE_EQUAL(tombChannel.getChannel(), 3); BOOST_REQUIRE_EQUAL(tombChannel.getThreshold(), 4); BOOST_REQUIRE_EQUAL(tombChannel.getLocalChannelNumber(), 5); BOOST_REQUIRE_EQUAL(tombChannel.getFEBInputNumber(), 6); BOOST_REQUIRE_EQUAL(tombChannel.getTRB().getID(), trb.getID()); BOOST_REQUIRE_EQUAL(tombChannel.getTRB().getType(), trb.getType()); BOOST_REQUIRE_EQUAL(tombChannel.getTRB().getChannel(), trb.getChannel()); BOOST_REQUIRE_EQUAL(tombChannel.getFEB().getID() , feb.getID()); BOOST_REQUIRE_EQUAL(tombChannel.getFEB().isActive() , feb.isActive()); BOOST_REQUIRE_EQUAL(tombChannel.getPM().getHVopt(), pm.getHVopt()); BOOST_REQUIRE_EQUAL(tombChannel.getPM().getHVset(), pm.getHVset()); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/* Copyright (c) 2017-2018 Andrew Depke */ #include "WindowsProcess.h" #include <Windows.h> #include <Psapi.h> namespace Red { bool GetProcessModules(std::vector<ProcessModule>* Output) { if (!Output) { return false; } HMODULE Modules[1024]; HANDLE Process = GetCurrentProcess(); DWORD BytesNeeded; if (EnumProcessModules(Process, Modules, sizeof(Modules), &BytesNeeded)) { for (int Iter = 0; Iter < (BytesNeeded / sizeof(HMODULE)); ++Iter) { char ModuleName[MAX_PATH]; if (GetModuleFileNameA(Modules[Iter], ModuleName, (sizeof(ModuleName) / sizeof(sizeof(TCHAR))))) { ProcessModule Module; Module.Name = ModuleName; Output->push_back(Module); } } } else { return false; } return true; } } // namespace Red<commit_msg>Fixed Array Size Trimming<commit_after>/* Copyright (c) 2017-2018 Andrew Depke */ #include "WindowsProcess.h" #include <Windows.h> #include <Psapi.h> namespace Red { bool GetProcessModules(std::vector<ProcessModule>* Output) { if (!Output) { return false; } HMODULE Modules[1024]; HANDLE Process = GetCurrentProcess(); DWORD BytesNeeded; if (EnumProcessModules(Process, Modules, sizeof(Modules), &BytesNeeded)) { for (int Iter = 0; Iter < (BytesNeeded / sizeof(HMODULE)); ++Iter) { char ModuleName[MAX_PATH]; if (GetModuleFileNameA(Modules[Iter], ModuleName, sizeof(ModuleName))) { ProcessModule Module; Module.Name = ModuleName; Output->push_back(Module); } } } else { return false; } return true; } } // namespace Red<|endoftext|>
<commit_before>#ifndef __Z2H_PARSER__ #define __Z2H_PARSER__ = 1 #include <cmath> #include <string> #include <vector> #include <fstream> #include <sstream> #include <iostream> #include <stddef.h> #include <sys/stat.h> #include <functional> #include "symbol.hpp" #include "token.hpp" #include "binder.hpp" using namespace std::placeholders; namespace z2h { template <typename TParser> struct Parser : public Binder<TParser> { std::string source; size_t position; std::vector<Token *> tokens; size_t index; ~Parser() { while (!tokens.empty()) delete tokens.back(), tokens.pop_back(); } Parser() : source("") , position(0) , tokens({}) , index(0) { } // Exception must be defined by the inheriting parser, throw exceptions defined there virtual std::exception Exception(const char *file, size_t line, const std::string &message = "") = 0; // Symbols must be defined by the inheriting parser virtual std::vector<Symbol *> Symbols() = 0; // the default for the eof symbol is first in in the list of symbols virtual Symbol * EofSymbol() { return Symbols()[0]; } // the default for the eos symbol is second in in the list of symbols virtual Symbol * EosSymbol() { return Symbols()[1]; } std::string Open(const std::string &filename) { struct stat buffer; if (stat(filename.c_str(), &buffer) != 0) Exception(__FILE__, __LINE__, filename + " doesn't exist or is unreadable"); std::ifstream file(filename); std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); return text; } std::vector<Token *> TokenizeFile(const std::string &filename) { auto source = Open(filename); return Tokenize(source); } std::vector<Token *> Tokenize(std::string source) { this->index = 0; this->source = source; auto eof = EofSymbol(); auto token = Consume(); while (*eof != *token->symbol) { token = Consume(); } return tokens; } virtual std::vector<Ast *> ParseFile(const std::string &filename) { auto source = Open(filename); return Parse(source); } virtual std::vector<Ast *> Parse(std::string source) { this->index = 0; this->source = source; return Statements(); } virtual Token * Scan() { auto eof = EofSymbol(); Token *match = nullptr; if (position < source.length()) { for (auto symbol : Symbols()) { auto token = symbol->Scan(symbol, source.substr(position, source.length() - position), position); if (nullptr == match) { match = token; } else if (nullptr != token && (token->length > match->length || (token->symbol->lbp > match->symbol->lbp && token->length == match->length))) { delete match; match = token; } else { delete token; } } if (nullptr == match) { throw Exception(__FILE__, __LINE__, "Parser::Scan: invalid symbol"); } return match; } std::cout << "FAILED SCAN" << std::endl; return new Token(eof, "EOF", position, 0, false); //eof } virtual Token * LookAhead(size_t &distance, bool skips = false) { Token *token = nullptr; auto i = index; while (distance) { if (i < tokens.size()) { token = tokens[i]; } else { token = Scan(); position += token->length; tokens.push_back(token); } if (skips || !token->skip) { --distance; } ++i; } distance = i - index; return token; } Token * LookAhead1() { size_t distance = 1; return this->LookAhead(distance); } Token * LookAhead2() { size_t distance = 2; return this->LookAhead(distance); } virtual Token * Consume(Symbol *expected = nullptr) { if (expected) { return Consume({expected}); } return Consume({}); } virtual Token * Consume(std::initializer_list<Symbol *> expectations) { size_t distance = 1; auto token = LookAhead(distance); if (expectations.size()) { for (auto expectation : expectations) { if (expectation && expectation == token->symbol) { index += distance; return token; } } return nullptr; } index += distance; return token; } virtual Ast * Expression(size_t rbp = 0) { auto *curr = Consume(); size_t distance = 1; Ast *left = curr->symbol->Nud(curr); auto *next = LookAhead(distance); while (rbp < next->symbol->lbp) { curr = Consume(); if (nullptr == curr->symbol->Led) { std::cout << __LINE__ << "no Led: curr=" << *curr << std::endl; std::ostringstream out; out << "unexpected: nullptr==Led curr=" << *curr; throw Exception(__FILE__, __LINE__, out.str()); } left = curr->symbol->Led(left, curr); size_t distance = 1; next = LookAhead(distance); } return left; } virtual Ast * Statement() { size_t distance = 1; auto *la1 = LookAhead(distance); if (nullptr != la1->symbol->Std) { Consume(); return la1->symbol->Std(); } auto ast = Expression(); return ast; } virtual std::vector<Ast *> Statements() { std::vector<Ast *> statements; auto eos = EosSymbol(); auto statement = Statement(); while (statement) { statements.push_back(statement); statement = Consume(eos) ? Statement() : nullptr; } return statements; } size_t Line() { return 0; } size_t Column() { return 0; } }; } #endif /*__Z2H_PARSER__*/ <commit_msg>removed FAILED message ... -sai<commit_after>#ifndef __Z2H_PARSER__ #define __Z2H_PARSER__ = 1 #include <cmath> #include <string> #include <vector> #include <fstream> #include <sstream> #include <iostream> #include <stddef.h> #include <sys/stat.h> #include <functional> #include "symbol.hpp" #include "token.hpp" #include "binder.hpp" using namespace std::placeholders; namespace z2h { template <typename TParser> struct Parser : public Binder<TParser> { std::string source; size_t position; std::vector<Token *> tokens; size_t index; ~Parser() { while (!tokens.empty()) delete tokens.back(), tokens.pop_back(); } Parser() : source("") , position(0) , tokens({}) , index(0) { } // Exception must be defined by the inheriting parser, throw exceptions defined there virtual std::exception Exception(const char *file, size_t line, const std::string &message = "") = 0; // Symbols must be defined by the inheriting parser virtual std::vector<Symbol *> Symbols() = 0; // the default for the eof symbol is first in in the list of symbols virtual Symbol * EofSymbol() { return Symbols()[0]; } // the default for the eos symbol is second in in the list of symbols virtual Symbol * EosSymbol() { return Symbols()[1]; } std::string Open(const std::string &filename) { struct stat buffer; if (stat(filename.c_str(), &buffer) != 0) Exception(__FILE__, __LINE__, filename + " doesn't exist or is unreadable"); std::ifstream file(filename); std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); return text; } std::vector<Token *> TokenizeFile(const std::string &filename) { auto source = Open(filename); return Tokenize(source); } std::vector<Token *> Tokenize(std::string source) { this->index = 0; this->source = source; auto eof = EofSymbol(); auto token = Consume(); while (*eof != *token->symbol) { token = Consume(); } return tokens; } virtual std::vector<Ast *> ParseFile(const std::string &filename) { auto source = Open(filename); return Parse(source); } virtual std::vector<Ast *> Parse(std::string source) { this->index = 0; this->source = source; return Statements(); } virtual Token * Scan() { auto eof = EofSymbol(); Token *match = nullptr; if (position < source.length()) { for (auto symbol : Symbols()) { auto token = symbol->Scan(symbol, source.substr(position, source.length() - position), position); if (nullptr == match) { match = token; } else if (nullptr != token && (token->length > match->length || (token->symbol->lbp > match->symbol->lbp && token->length == match->length))) { delete match; match = token; } else { delete token; } } if (nullptr == match) { throw Exception(__FILE__, __LINE__, "Parser::Scan: invalid symbol"); } return match; } return new Token(eof, "EOF", position, 0, false); //eof } virtual Token * LookAhead(size_t &distance, bool skips = false) { Token *token = nullptr; auto i = index; while (distance) { if (i < tokens.size()) { token = tokens[i]; } else { token = Scan(); position += token->length; tokens.push_back(token); } if (skips || !token->skip) { --distance; } ++i; } distance = i - index; return token; } Token * LookAhead1() { size_t distance = 1; return this->LookAhead(distance); } Token * LookAhead2() { size_t distance = 2; return this->LookAhead(distance); } virtual Token * Consume(Symbol *expected = nullptr) { if (expected) { return Consume({expected}); } return Consume({}); } virtual Token * Consume(std::initializer_list<Symbol *> expectations) { size_t distance = 1; auto token = LookAhead(distance); if (expectations.size()) { for (auto expectation : expectations) { if (expectation && expectation == token->symbol) { index += distance; return token; } } return nullptr; } index += distance; return token; } virtual Ast * Expression(size_t rbp = 0) { auto *curr = Consume(); size_t distance = 1; Ast *left = curr->symbol->Nud(curr); auto *next = LookAhead(distance); while (rbp < next->symbol->lbp) { curr = Consume(); if (nullptr == curr->symbol->Led) { std::cout << __LINE__ << "no Led: curr=" << *curr << std::endl; std::ostringstream out; out << "unexpected: nullptr==Led curr=" << *curr; throw Exception(__FILE__, __LINE__, out.str()); } left = curr->symbol->Led(left, curr); size_t distance = 1; next = LookAhead(distance); } return left; } virtual Ast * Statement() { size_t distance = 1; auto *la1 = LookAhead(distance); if (nullptr != la1->symbol->Std) { Consume(); return la1->symbol->Std(); } auto ast = Expression(); return ast; } virtual std::vector<Ast *> Statements() { std::vector<Ast *> statements; auto eos = EosSymbol(); auto statement = Statement(); while (statement) { statements.push_back(statement); statement = Consume(eos) ? Statement() : nullptr; } return statements; } size_t Line() { return 0; } size_t Column() { return 0; } }; } #endif /*__Z2H_PARSER__*/ <|endoftext|>
<commit_before>#ifndef ATL_PARSER_HPP #define ATL_PARSER_HPP /** * @file /home/ryan/programming/atl/parser.hpp * @author Ryan Domigan <ryan_domigan@[email protected]> * Created on Jun 29, 2013 */ #include <iterator> #include <sstream> #include <string> #include <vector> #include <iostream> #include <functional> #include <iterator> #include "./exception.hpp" #include "./type.hpp" #include "./conversion.hpp" #include "./type_testing.hpp" #include "./helpers.hpp" #include "./print.hpp" namespace atl { /* this is a really simple minded parser; just breaks everything up into the ast. */ class ParseString { private: GC &_gc; unsigned long _line; static const string delim; /* symbol deliminator */ static const string _ws; /* white space */ string scratch; inline bool digit(char c) { return ((c >= '0') && (c <= '9')); } bool string_is_number(const string& str) { return (digit(str[0]) || ((str[0] == '-') && (str.length() > 1) && digit(str[1]))); } template<class Itr> void parse(GC::DynamicVector &vec, Itr &&itr, Itr &&end) { for(; itr != end; ++itr) { switch(*itr) { case '\n': ++_line; case ' ': /* whitespace */ case '\t': continue; case ';': /* comment */ for(; itr != end && *itr != '\n'; ++itr); if(*itr == '\n') ++_line; continue; case '\'':{ /* quote */ auto quote = vec.push_seq<Ast>(); vec[0] = aimm<Quote>(); ++vec; ++itr; parse(vec, itr, end); quote->end_at(vec.end()); return; } case '(':{ /* sub expression */ ++itr; if(*itr == ')') { auto null = vec.push_seq<Ast>(); null->end_at(vec.end()); return; } auto ast = vec.push_seq<Ast>(); while(*itr != ')') { if(itr == end) throw UnbalancedParens(to_string(_line).append(": error: unbalanced parens")); parse(vec, itr, end); } ++itr; ast->end_at(vec.end()); return; } case ')': return; case '"': { /* string */ std::string *str = reinterpret_cast<std::string*>(_gc.make<String>()); for(++itr; *itr != '"'; ++itr) { if(itr == end) throw to_string(_line).append("string not terminated."); if(*itr == '\n') ++_line; str->push_back(*itr); } ++itr; vec[0] = Any(tag<String>::value, str); ++vec; return; } default: { scratch.clear(); for(; (itr != end) && (delim.find(*itr) == string::npos); ++itr) scratch.push_back(*itr); if((itr != end) && (*itr == '\n')) ++_line; if(string_is_number(scratch)) { vec[0] = aimm( atoi(scratch.c_str()) ); } else { std::string *sym = reinterpret_cast<std::string*>(_gc.make<Symbol>(scratch)); vec[0] = Any(tag<Symbol>::value, sym); } ++vec; return; }}} return; } public: ParseString(GC &gc) : _gc(gc) { _line = 1; //_gc.mark_callback( [this](GC &gc) { _gc.mark(_mark); }); } /* parse one S-expression from a string into an ast */ Any& string_(const std::string& input) { auto vec = _gc.dynamic_vector(); **vec = nil<Null>::value(); parse(*vec, input.begin(), input.end()); return *vec->begin(); } /* parse one S-expression from a stream into an ast */ Any& stream(istream &stream) { auto initial_flags = stream.flags(); noskipws(stream); auto vec = _gc.dynamic_vector(); **vec = nil<Null>::value(); parse(*vec, istream_iterator<char>(stream), istream_iterator<char>() ); stream.flags(initial_flags); return *vec->begin(); } void reset_line_number() { _line = 1; } }; const std::string ParseString::_ws = " \n\t"; const std::string ParseString::delim = "()\" \n\t"; } #endif <commit_msg>Parser whitespace changes and some syntax notes<commit_after>#ifndef ATL_PARSER_HPP #define ATL_PARSER_HPP /** * @file /home/ryan/programming/atl/parser.hpp * @author Ryan Domigan <ryan_domigan@[email protected]> * Created on Jun 29, 2013 */ #include <iterator> #include <sstream> #include <string> #include <vector> #include <iostream> #include <functional> #include <iterator> #include "./exception.hpp" #include "./type.hpp" #include "./conversion.hpp" #include "./type_testing.hpp" #include "./helpers.hpp" #include "./print.hpp" namespace atl { // A simple minded parser, this just transforms a string into an Ast. There are a couple of reserved symbols: // '(' ')' : Open and close an Ast branch // DELIM '\\' DELIM : After much debate, I'm making Lambda a reserved word. In principle, I'd like everything to be a // usable symbol at local scope. This may still change (should I be able to do something like // `(def foo \ ) ((foo (a b) (+ a b)) 1 2)`)? // DELIM 'let' DELIM: Simalar to lambda, if I'm going to getting Hindly Milner with polymorphic let is going to be much easier // If I can get a tagged type. // DELIM '\'' : 'n expands to (quote n) (should probably be a macro). Can still be used as part of a variable name (ie x and x' are both // valid symbols). // '\"' : starts and ends a string literal // DELIM 0..9 DELIM: a number (a number must be all digits ie 124567, possibly with a decimal point. If there is a non-digit ie 12345a, it // is a symbol. hex/octal/binary representations are not a thing ATM). class ParseString { private: GC &_gc; unsigned long _line; static const string delim; /* symbol deliminator */ static const string _ws; /* white space */ string scratch; inline bool digit(char c) { return ((c >= '0') && (c <= '9')); } bool string_is_number(const string& str) { return (digit(str[0]) || ((str[0] == '-') && (str.length() > 1) && digit(str[1]))); } template<class Itr> void parse(GC::DynamicVector &vec, Itr &&itr, Itr &&end) { for(; itr != end; ++itr) { switch(*itr) { case '\n': ++_line; case ' ': /* whitespace */ case '\t': continue; case ';': /* comment */ for(; itr != end && *itr != '\n'; ++itr); if(*itr == '\n') ++_line; continue; case '\'': { /* quote */ auto quote = vec.push_seq<Ast>(); vec[0] = aimm<Quote>(); ++vec; ++itr; parse(vec, itr, end); quote->end_at(vec.end()); return; } case '(': { /* sub expression */ ++itr; if(*itr == ')') { auto null = vec.push_seq<Ast>(); null->end_at(vec.end()); return; } auto ast = vec.push_seq<Ast>(); while(*itr != ')') { if(itr == end) throw UnbalancedParens (to_string(_line) .append(": error: unbalanced parens")); parse(vec, itr, end); } ++itr; ast->end_at(vec.end()); return; } case ')': return; case '"': { /* string */ std::string *str = reinterpret_cast<std::string*>(_gc.make<String>()); for(++itr; *itr != '"'; ++itr) { if(itr == end) throw to_string(_line) .append("string not terminated."); if(*itr == '\n') ++_line; str->push_back(*itr); } ++itr; vec[0] = Any(tag<String>::value, str); ++vec; return; } default: { scratch.clear(); for(; (itr != end) && (delim.find(*itr) == string::npos); ++itr) scratch.push_back(*itr); if((itr != end) && (*itr == '\n')) ++_line; if(string_is_number(scratch)) { vec[0] = aimm( atoi(scratch.c_str()) ); } else if(scratch == "\\") // Lambda { vec[0] = aimm<Lambda>(); } else if(scratch == "let") { vec[0] = aimm<Let>(); } else { vec[0] = _gc.amake<Symbol>(scratch); } ++vec; return; } } } return; } public: ParseString(GC &gc) : _gc(gc) { _line = 1; //_gc.mark_callback( [this](GC &gc) { _gc.mark(_mark); }); } /* parse one S-expression from a string into an ast */ Any& string_(const std::string& input) { auto vec = _gc.dynamic_seq(); **vec = nil<Null>::value(); parse(*vec, input.begin(), input.end()); return *vec->begin(); } /* parse one S-expression from a stream into an ast */ Any& stream(istream &stream) { auto initial_flags = stream.flags(); noskipws(stream); auto vec = _gc.dynamic_seq(); **vec = nil<Null>::value(); parse(*vec, istream_iterator<char>(stream), istream_iterator<char>() ); stream.flags(initial_flags); return *vec->begin(); } void reset_line_number() { _line = 1; } }; const std::string ParseString::_ws = " \n\t"; const std::string ParseString::delim = "()\" \n\t"; } #endif <|endoftext|>
<commit_before>#include "HedgeLib/Archives/LWArchive.h" #include "HedgeLib/Archives/PACx.h" #include "HedgeLib/IO/File.h" #include <string> #include <cstring> // hl_DPACProxyEntry HL_IMPL_ENDIAN_SWAP_CPP(hl_DPACProxyEntry); HL_IMPL_X64_OFFSETS(hl_DPACProxyEntry); HL_IMPL_ENDIAN_SWAP(hl_DPACProxyEntry) { hl_Swap(v->Index); } // hl_DPACSplitTable HL_IMPL_ENDIAN_SWAP_CPP(hl_DPACSplitTable); HL_IMPL_X64_OFFSETS(hl_DPACSplitTable); HL_IMPL_ENDIAN_SWAP(hl_DPACSplitTable) { hl_Swap(v->SplitCount); } // hl_DPACDataEntry HL_IMPL_ENDIAN_SWAP_CPP(hl_DPACDataEntry); HL_IMPL_ENDIAN_SWAP(hl_DPACDataEntry) { hl_Swap(v->DataSize); hl_Swap(v->Unknown1); hl_Swap(v->Unknown2); } // hl_DPACNode HL_IMPL_X64_OFFSETS(hl_DPACNode); // hl_DLWArchive HL_IMPL_ENDIAN_SWAP_CPP(hl_DLWArchive); HL_IMPL_ENDIAN_SWAP_RECURSIVE_CPP(hl_DLWArchive); HL_IMPL_WRITE_CPP(hl_DLWArchive); HL_IMPL_X64_OFFSETS(hl_DLWArchive); HL_IMPL_ENDIAN_SWAP(hl_DLWArchive) { v->Header.EndianSwap(); hl_Swap(v->TypeTree); } HL_IMPL_ENDIAN_SWAP_RECURSIVE(hl_DLWArchive) { // Swap type tree and all of its children if (be) hl_Swap(v->TypeTree); hl_DPACNode* typeNodes = HL_GETPTR32(hl_DPACNode, v->TypeTree.Offset); for (uint32_t i = 0; i < v->TypeTree.Count; ++i) { // Check if file tree is split table bool isSplitTable = (std::strcmp(typeNodes[i].Name, "pac.d:ResPacDepend") == 0); // Get file tree from type node HL_ARR32(hl_DPACNode)* fileTree = HL_GETPTR32( HL_ARR32(hl_DPACNode), typeNodes[i].Data); hl_DPACNode* fileNodes = HL_GETPTR32(hl_DPACNode, fileTree->Offset); // Swap nodes in file tree if (be) hl_Swap(*fileTree); for (uint32_t i2 = 0; i2 < fileTree->Count; ++i2) { // Swap data entries in node hl_DPACDataEntry* dataEntry = HL_GETPTR32( hl_DPACDataEntry, fileNodes[i2].Data); dataEntry->EndianSwap(); // If this is a split table, swap it too if (isSplitTable) { reinterpret_cast<hl_DPACSplitTable*>( dataEntry + 1)->EndianSwap(); } } if (!be) hl_Swap(*fileTree); } if (!be) hl_Swap(v->TypeTree); // Swap proxy table if (v->Header.ProxyTableSize) { hl_DPACProxyEntryTable* proxyTable = reinterpret_cast<hl_DPACProxyEntryTable*>( reinterpret_cast<uintptr_t>(&v->TypeTree) + v->Header.TreesSize + v->Header.DataEntriesSize); hl_SwapRecursive<hl_DPACProxyEntry>(be, *proxyTable); } } HL_IMPL_WRITE(hl_DLWArchive) { // Prepare data node header hl_OffsetTable offTable; hl_StringTable strTable; long nodePos = file->Tell(); ptr->Header.Header.Signature = HL_BINA_V2_DATA_NODE_SIGNATURE; ptr->Header.Unknown1 = 1; // Write data node header and type tree file->Write(*ptr); //long eof = file->Tell(); long treesPos = (nodePos + sizeof(hl_DPACxV2DataNode)); // Fix type tree offset file->FixOffsetRel32(-4, 0, offTable); // Write type nodes hl_DPACNode* typeNodes = HL_GETPTR32( hl_DPACNode, ptr->TypeTree.Offset); file->WriteNoSwap(typeNodes, ptr->TypeTree.Count); // Write file trees long eof, offPos = (treesPos + sizeof(ptr->TypeTree)); for (uint32_t i = 0; i < ptr->TypeTree.Count; ++i) { // Write file tree and fix type node offsets HL_ARR32(hl_DPACNode)* fileTree = HL_GETPTR32( HL_ARR32(hl_DPACNode), typeNodes[i].Data); hl_AddString(&strTable, typeNodes[i].Name, offPos); offPos += 4; file->FixOffset32(offPos, file->Tell(), offTable); file->Write(*fileTree); offPos += 4; // Write file nodes hl_DPACNode* fileNodes = HL_GETPTR32( hl_DPACNode, fileTree->Offset); file->WriteNoSwap(fileNodes, fileTree->Count); } // Write data entries long dataEntriesPos = file->Tell(); hl_DPACSplitTable* splitTable = nullptr; hl_DPACProxyEntryTable proxyEntryTable = {}; long splitPos; for (uint32_t i = 0; i < ptr->TypeTree.Count; ++i) { // Fix file tree offset HL_ARR32(hl_DPACNode)* fileTree = HL_GETPTR32( HL_ARR32(hl_DPACNode), typeNodes[i].Data); offPos += 4; file->FixOffset32(offPos, offPos + 4, offTable); offPos += 4; // Write file data and fix file node offset hl_DPACNode* fileNodes = HL_GETPTR32( hl_DPACNode, fileTree->Offset); bool isSplitsList = (std::strcmp(typeNodes[i].Name, "pac.d:ResPacDepend") == 0); for (uint32_t i2 = 0; i2 < fileTree->Count; ++i2) { // Fix file node offset hl_DPACDataEntry* dataEntry = HL_GETPTR32( hl_DPACDataEntry, fileNodes[i2].Data); hl_AddString(&strTable, fileNodes[i2].Name, offPos); offPos += 4; file->Pad(16); eof = file->Tell(); file->FixOffset32(offPos, eof, offTable); offPos += 4; // Write data entry file->Write(*dataEntry); // Write split entry table if (isSplitsList) { // Write split table long splitTablePos = (eof + sizeof(*dataEntry)); splitTable = reinterpret_cast<hl_DPACSplitTable*>(++dataEntry); file->Write(*splitTable); // Fix split entry table offset splitPos = (splitTablePos + sizeof(*splitTable)); file->FixOffset32(splitTablePos, splitPos, offTable); // Write split entries file->WriteNulls(splitTable->SplitCount * sizeof(HL_STR32)); // We fix splits after writing file data // to do things like the game does. } // Write file data else if (dataEntry->Flags != HL_PACX_DATA_FLAGS_NO_DATA) { file->WriteBytes(++dataEntry, dataEntry->DataSize); // TODO: Merge BINA offsets/string table from file data into PACx if needed } else { ++proxyEntryTable.Count; } } } // Fix split table if (splitTable) { for (uint32_t i = 0; i < splitTable->SplitCount; ++i) { // Get offset position hl_AddString(&strTable, splitTable->Splits[i], splitPos); splitPos += sizeof(HL_STR32); } } // Write proxy entry table long proxyEntryTablePos = file->Tell(); if (proxyEntryTable.Count) { offPos = (proxyEntryTablePos + 4); file->Write(proxyEntryTable); file->FixOffset32(offPos, offPos + 4, offTable); offPos += 4; // Write proxy entries for (uint32_t i = 0; i < ptr->TypeTree.Count; ++i) { HL_ARR32(hl_DPACNode)* fileTree = HL_GETPTR32( HL_ARR32(hl_DPACNode), typeNodes[i].Data); hl_DPACNode* fileNodes = HL_GETPTR32( hl_DPACNode, fileTree->Offset); for (uint32_t i2 = 0; i2 < fileTree->Count; ++i2) { hl_DPACDataEntry* dataEntry = HL_GETPTR32( hl_DPACDataEntry, fileNodes[i2].Data); if (dataEntry->Flags != HL_PACX_DATA_FLAGS_NO_DATA) continue; file->WriteNoSwap<uint64_t>(0); hl_AddString(&strTable, typeNodes[i].Name, offPos); offPos += 4; hl_AddString(&strTable, fileNodes[i2].Name, offPos); offPos += 8; file->Write(i2); } } } // Write string table uint32_t strTablePos = static_cast<uint32_t>(file->Tell()); hl_BINAWriteStringTable(file, &strTable, &offTable); // Write offset table uint32_t offTablePos = static_cast<uint32_t>(file->Tell()); hl_BINAWriteOffsetTable(file, &offTable); // Fill-in node size eof = file->Tell(); uint32_t nodeSize = static_cast<uint32_t>(eof - nodePos); file->JumpTo(nodePos + 4); file->Write(nodeSize); // Fill-in data entries size uint32_t dataEntriesSize = static_cast<uint32_t>( proxyEntryTablePos - dataEntriesPos); file->Write(dataEntriesSize); // Fill-in trees size uint32_t treesSize = static_cast<uint32_t>( dataEntriesPos - treesPos); file->Write(treesSize); // Fill-in proxy table size uint32_t proxyTableSize = static_cast<uint32_t>( strTablePos - proxyEntryTablePos); file->Write(proxyTableSize); // Fill-in string table size uint32_t stringTableSize = (offTablePos - strTablePos); file->Write(stringTableSize); // Fill-in offset table size uint32_t offsetTableSize = (eof - offTablePos); file->Write(offsetTableSize); file->JumpTo(eof); } void hl_ExtractLWArchive(const struct hl_Blob* blob, const char* dir) { std::filesystem::path fdir = dir; std::filesystem::create_directory(fdir); const hl_DLWArchive* arc = hl_BINAGetData<hl_DLWArchive>(blob); hl_DPACNode* typeNodes = HL_GETPTR32( hl_DPACNode, arc->TypeTree.Offset); for (uint32_t i = 0; i < arc->TypeTree.Count; ++i) { HL_ARR32(hl_DPACNode)* fileTree = HL_GETPTR32( HL_ARR32(hl_DPACNode), typeNodes[i].Data); hl_DPACNode* fileNodes = HL_GETPTR32( hl_DPACNode, fileTree->Offset); char* ext = HL_GETPTR32(char, typeNodes[i].Name); uintptr_t colonPos = reinterpret_cast<uintptr_t>( std::strchr(ext, (int)':')); if (!colonPos) { // TODO: Return an error?? continue; } size_t extLen = static_cast<size_t>( colonPos - reinterpret_cast<uintptr_t>(ext)); for (uint32_t i2 = 0; i2 < fileTree->Count; ++i2) { hl_DPACDataEntry* dataEntry = HL_GETPTR32( hl_DPACDataEntry, fileNodes[i2].Data); if (dataEntry->Flags & HL_PACX_DATA_FLAGS_NO_DATA) continue; std::string fileName = std::string( HL_GETPTR32(char, fileNodes[i2].Name)); fileName += '.'; fileName.append(ext, extLen); // Write data to file uint8_t* data = reinterpret_cast<uint8_t*>(dataEntry + 1); hl_File file = hl_File::OpenWrite(fdir / fileName); // TODO: BINA CRAP file.WriteBytes(data, dataEntry->DataSize); file.Close(); } } } <commit_msg>Skip split table when extracting LWArchives<commit_after>#include "HedgeLib/Archives/LWArchive.h" #include "HedgeLib/Archives/PACx.h" #include "HedgeLib/IO/File.h" #include <string> #include <cstring> static const char* const pacSplitType = "pac.d:ResPacDepend"; // hl_DPACProxyEntry HL_IMPL_ENDIAN_SWAP_CPP(hl_DPACProxyEntry); HL_IMPL_X64_OFFSETS(hl_DPACProxyEntry); HL_IMPL_ENDIAN_SWAP(hl_DPACProxyEntry) { hl_Swap(v->Index); } // hl_DPACSplitTable HL_IMPL_ENDIAN_SWAP_CPP(hl_DPACSplitTable); HL_IMPL_X64_OFFSETS(hl_DPACSplitTable); HL_IMPL_ENDIAN_SWAP(hl_DPACSplitTable) { hl_Swap(v->SplitCount); } // hl_DPACDataEntry HL_IMPL_ENDIAN_SWAP_CPP(hl_DPACDataEntry); HL_IMPL_ENDIAN_SWAP(hl_DPACDataEntry) { hl_Swap(v->DataSize); hl_Swap(v->Unknown1); hl_Swap(v->Unknown2); } // hl_DPACNode HL_IMPL_X64_OFFSETS(hl_DPACNode); // hl_DLWArchive HL_IMPL_ENDIAN_SWAP_CPP(hl_DLWArchive); HL_IMPL_ENDIAN_SWAP_RECURSIVE_CPP(hl_DLWArchive); HL_IMPL_WRITE_CPP(hl_DLWArchive); HL_IMPL_X64_OFFSETS(hl_DLWArchive); HL_IMPL_ENDIAN_SWAP(hl_DLWArchive) { v->Header.EndianSwap(); hl_Swap(v->TypeTree); } HL_IMPL_ENDIAN_SWAP_RECURSIVE(hl_DLWArchive) { // Swap type tree and all of its children if (be) hl_Swap(v->TypeTree); hl_DPACNode* typeNodes = HL_GETPTR32(hl_DPACNode, v->TypeTree.Offset); for (uint32_t i = 0; i < v->TypeTree.Count; ++i) { // Check if file tree is split table bool isSplitTable = (std::strcmp(typeNodes[i].Name, pacSplitType) == 0); // Get file tree from type node HL_ARR32(hl_DPACNode)* fileTree = HL_GETPTR32( HL_ARR32(hl_DPACNode), typeNodes[i].Data); hl_DPACNode* fileNodes = HL_GETPTR32(hl_DPACNode, fileTree->Offset); // Swap nodes in file tree if (be) hl_Swap(*fileTree); for (uint32_t i2 = 0; i2 < fileTree->Count; ++i2) { // Swap data entries in node hl_DPACDataEntry* dataEntry = HL_GETPTR32( hl_DPACDataEntry, fileNodes[i2].Data); dataEntry->EndianSwap(); // If this is a split table, swap it too if (isSplitTable) { reinterpret_cast<hl_DPACSplitTable*>( dataEntry + 1)->EndianSwap(); } } if (!be) hl_Swap(*fileTree); } if (!be) hl_Swap(v->TypeTree); // Swap proxy table if (v->Header.ProxyTableSize) { hl_DPACProxyEntryTable* proxyTable = reinterpret_cast<hl_DPACProxyEntryTable*>( reinterpret_cast<uintptr_t>(&v->TypeTree) + v->Header.TreesSize + v->Header.DataEntriesSize); hl_SwapRecursive<hl_DPACProxyEntry>(be, *proxyTable); } } HL_IMPL_WRITE(hl_DLWArchive) { // Prepare data node header hl_OffsetTable offTable; hl_StringTable strTable; long nodePos = file->Tell(); ptr->Header.Header.Signature = HL_BINA_V2_DATA_NODE_SIGNATURE; ptr->Header.Unknown1 = 1; // Write data node header and type tree file->Write(*ptr); //long eof = file->Tell(); long treesPos = (nodePos + sizeof(hl_DPACxV2DataNode)); // Fix type tree offset file->FixOffsetRel32(-4, 0, offTable); // Write type nodes hl_DPACNode* typeNodes = HL_GETPTR32( hl_DPACNode, ptr->TypeTree.Offset); file->WriteNoSwap(typeNodes, ptr->TypeTree.Count); // Write file trees long eof, offPos = (treesPos + sizeof(ptr->TypeTree)); for (uint32_t i = 0; i < ptr->TypeTree.Count; ++i) { // Write file tree and fix type node offsets HL_ARR32(hl_DPACNode)* fileTree = HL_GETPTR32( HL_ARR32(hl_DPACNode), typeNodes[i].Data); hl_AddString(&strTable, typeNodes[i].Name, offPos); offPos += 4; file->FixOffset32(offPos, file->Tell(), offTable); file->Write(*fileTree); offPos += 4; // Write file nodes hl_DPACNode* fileNodes = HL_GETPTR32( hl_DPACNode, fileTree->Offset); file->WriteNoSwap(fileNodes, fileTree->Count); } // Write data entries long dataEntriesPos = file->Tell(); hl_DPACSplitTable* splitTable = nullptr; hl_DPACProxyEntryTable proxyEntryTable = {}; long splitPos; for (uint32_t i = 0; i < ptr->TypeTree.Count; ++i) { // Fix file tree offset HL_ARR32(hl_DPACNode)* fileTree = HL_GETPTR32( HL_ARR32(hl_DPACNode), typeNodes[i].Data); offPos += 4; file->FixOffset32(offPos, offPos + 4, offTable); offPos += 4; // Write file data and fix file node offset hl_DPACNode* fileNodes = HL_GETPTR32( hl_DPACNode, fileTree->Offset); bool isSplitsList = (std::strcmp( typeNodes[i].Name, pacSplitType) == 0); for (uint32_t i2 = 0; i2 < fileTree->Count; ++i2) { // Fix file node offset hl_DPACDataEntry* dataEntry = HL_GETPTR32( hl_DPACDataEntry, fileNodes[i2].Data); hl_AddString(&strTable, fileNodes[i2].Name, offPos); offPos += 4; file->Pad(16); eof = file->Tell(); file->FixOffset32(offPos, eof, offTable); offPos += 4; // Write data entry file->Write(*dataEntry); // Write split entry table if (isSplitsList) { // Write split table long splitTablePos = (eof + sizeof(*dataEntry)); splitTable = reinterpret_cast<hl_DPACSplitTable*>(++dataEntry); file->Write(*splitTable); // Fix split entry table offset splitPos = (splitTablePos + sizeof(*splitTable)); file->FixOffset32(splitTablePos, splitPos, offTable); // Write split entries file->WriteNulls(splitTable->SplitCount * sizeof(HL_STR32)); // We fix splits after writing file data // to do things like the game does. } // Write file data else if (dataEntry->Flags != HL_PACX_DATA_FLAGS_NO_DATA) { file->WriteBytes(++dataEntry, dataEntry->DataSize); // TODO: Merge BINA offsets/string table from file data into PACx if needed } else { ++proxyEntryTable.Count; } } } // Fix split table if (splitTable) { for (uint32_t i = 0; i < splitTable->SplitCount; ++i) { // Get offset position hl_AddString(&strTable, splitTable->Splits[i], splitPos); splitPos += sizeof(HL_STR32); } } // Write proxy entry table long proxyEntryTablePos = file->Tell(); if (proxyEntryTable.Count) { offPos = (proxyEntryTablePos + 4); file->Write(proxyEntryTable); file->FixOffset32(offPos, offPos + 4, offTable); offPos += 4; // Write proxy entries for (uint32_t i = 0; i < ptr->TypeTree.Count; ++i) { HL_ARR32(hl_DPACNode)* fileTree = HL_GETPTR32( HL_ARR32(hl_DPACNode), typeNodes[i].Data); hl_DPACNode* fileNodes = HL_GETPTR32( hl_DPACNode, fileTree->Offset); for (uint32_t i2 = 0; i2 < fileTree->Count; ++i2) { hl_DPACDataEntry* dataEntry = HL_GETPTR32( hl_DPACDataEntry, fileNodes[i2].Data); if (dataEntry->Flags != HL_PACX_DATA_FLAGS_NO_DATA) continue; file->WriteNoSwap<uint64_t>(0); hl_AddString(&strTable, typeNodes[i].Name, offPos); offPos += 4; hl_AddString(&strTable, fileNodes[i2].Name, offPos); offPos += 8; file->Write(i2); } } } // Write string table uint32_t strTablePos = static_cast<uint32_t>(file->Tell()); hl_BINAWriteStringTable(file, &strTable, &offTable); // Write offset table uint32_t offTablePos = static_cast<uint32_t>(file->Tell()); hl_BINAWriteOffsetTable(file, &offTable); // Fill-in node size eof = file->Tell(); uint32_t nodeSize = static_cast<uint32_t>(eof - nodePos); file->JumpTo(nodePos + 4); file->Write(nodeSize); // Fill-in data entries size uint32_t dataEntriesSize = static_cast<uint32_t>( proxyEntryTablePos - dataEntriesPos); file->Write(dataEntriesSize); // Fill-in trees size uint32_t treesSize = static_cast<uint32_t>( dataEntriesPos - treesPos); file->Write(treesSize); // Fill-in proxy table size uint32_t proxyTableSize = static_cast<uint32_t>( strTablePos - proxyEntryTablePos); file->Write(proxyTableSize); // Fill-in string table size uint32_t stringTableSize = (offTablePos - strTablePos); file->Write(stringTableSize); // Fill-in offset table size uint32_t offsetTableSize = (eof - offTablePos); file->Write(offsetTableSize); file->JumpTo(eof); } void hl_ExtractLWArchive(const struct hl_Blob* blob, const char* dir) { // Create directory for file extraction std::filesystem::path fdir = dir; std::filesystem::create_directory(fdir); // Iterate through type tree const hl_DLWArchive* arc = hl_BINAGetData<hl_DLWArchive>(blob); hl_DPACNode* typeNodes = HL_GETPTR32( hl_DPACNode, arc->TypeTree.Offset); for (uint32_t i = 0; i < arc->TypeTree.Count; ++i) { // Get extension char* ext = HL_GETPTR32(char, typeNodes[i].Name); if (std::strcmp(ext, pacSplitType) == 0) continue; // Skip split table uintptr_t colonPos = reinterpret_cast<uintptr_t>( std::strchr(ext, (int)':')); if (!colonPos) { // TODO: Return an error?? continue; } size_t extLen = static_cast<size_t>( colonPos - reinterpret_cast<uintptr_t>(ext)); // Get file tree HL_ARR32(hl_DPACNode)* fileTree = HL_GETPTR32( HL_ARR32(hl_DPACNode), typeNodes[i].Data); hl_DPACNode* fileNodes = HL_GETPTR32( hl_DPACNode, fileTree->Offset); // Iterate through file nodes for (uint32_t i2 = 0; i2 < fileTree->Count; ++i2) { hl_DPACDataEntry* dataEntry = HL_GETPTR32( hl_DPACDataEntry, fileNodes[i2].Data); if (dataEntry->Flags & HL_PACX_DATA_FLAGS_NO_DATA) continue; std::string fileName = std::string( HL_GETPTR32(char, fileNodes[i2].Name)); fileName += '.'; fileName.append(ext, extLen); // Write data to file uint8_t* data = reinterpret_cast<uint8_t*>(dataEntry + 1); hl_File file = hl_File::OpenWrite(fdir / fileName); // TODO: BINA CRAP file.WriteBytes(data, dataEntry->DataSize); file.Close(); } } } <|endoftext|>
<commit_before><commit_msg>fdo#30711: fix some problems in 7a1c5e54:<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: txtsecte.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: vg $ $Date: 2005-03-23 12:42:46 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLOFF_TXTPARAE_HXX #include "txtparae.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #include <vector> #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_ #include <com/sun/star/container/XIndexReplace.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUES_HPP_ #include <com/sun/star/beans/PropertyValues.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_ #include <com/sun/star/beans/PropertyState.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_ #include <com/sun/star/text/XText.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_XTEXTSECTION_HPP_ #include <com/sun/star/text/XTextSection.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_SECTIONFILELINK_HPP_ #include <com/sun/star/text/SectionFileLink.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_ #include <com/sun/star/container/XNamed.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_XDOCUMENTINDEX_HPP_ #include <com/sun/star/text/XDocumentIndex.hpp> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_FAMILIES_HXX_ #include "families.hxx" #endif #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLEXP_HXX #include "xmlexp.hxx" #endif #ifndef _XMLOFF_XMLTKMAP_HXX #include "xmltkmap.hxx" #endif #ifndef _XMLOFF_XMLTEXTNUMRULEINFO_HXX #include "XMLTextNumRuleInfo.hxx" #endif #ifndef _XMLOFF_XMLSECTIONEXPORT_HXX_ #include "XMLSectionExport.hxx" #endif #ifndef _XMLOFF_XMLREDLINEEXPORT_HXX #include "XMLRedlineExport.hxx" #endif #ifndef _XMLOFF_MULTIPROPERTYSETHELPER_HXX #include "MultiPropertySetHelper.hxx" #endif using namespace ::com::sun::star; using namespace ::com::sun::star::text; using namespace ::com::sun::star::uno; using namespace ::std; using ::rtl::OUString; using ::rtl::OUStringBuffer; using ::com::sun::star::beans::XPropertySet; using ::com::sun::star::beans::PropertyValue; using ::com::sun::star::beans::PropertyValues; using ::com::sun::star::beans::PropertyState; using ::com::sun::star::container::XIndexReplace; using ::com::sun::star::container::XNamed; using ::com::sun::star::lang::XServiceInfo; Reference<XText> lcl_findXText(const Reference<XTextSection>& rSect) { Reference<XText> xText; Reference<XTextContent> xTextContent(rSect, UNO_QUERY); if (xTextContent.is()) { xText.set(xTextContent->getAnchor()->getText()); } return xText; } void XMLTextParagraphExport::exportListAndSectionChange( Reference<XTextSection> & rPrevSection, const Reference<XTextContent> & rNextSectionContent, const XMLTextNumRuleInfo& rPrevRule, const XMLTextNumRuleInfo& rNextRule, sal_Bool bAutoStyles) { Reference<XTextSection> xNextSection; // first: get current XTextSection Reference<XPropertySet> xPropSet(rNextSectionContent, UNO_QUERY); if (xPropSet.is()) { if (xPropSet->getPropertySetInfo()->hasPropertyByName(sTextSection)) { xPropSet->getPropertyValue(sTextSection) >>= xNextSection; } // else: no current section } exportListAndSectionChange(rPrevSection, xNextSection, rPrevRule, rNextRule, bAutoStyles); } void XMLTextParagraphExport::exportListAndSectionChange( Reference<XTextSection> & rPrevSection, MultiPropertySetHelper& rPropSetHelper, sal_Int16 nTextSectionId, const Reference<XTextContent> & rNextSectionContent, const XMLTextNumRuleInfo& rPrevRule, const XMLTextNumRuleInfo& rNextRule, sal_Bool bAutoStyles) { Reference<XTextSection> xNextSection; // first: get current XTextSection Reference<XPropertySet> xPropSet(rNextSectionContent, UNO_QUERY); if (xPropSet.is()) { if( !rPropSetHelper.checkedProperties() ) rPropSetHelper.hasProperties( xPropSet->getPropertySetInfo() ); if( rPropSetHelper.hasProperty( nTextSectionId )) { xNextSection.set(rPropSetHelper.getValue( nTextSectionId , xPropSet, sal_True ), uno::UNO_QUERY); } // else: no current section } exportListAndSectionChange(rPrevSection, xNextSection, rPrevRule, rNextRule, bAutoStyles); } void XMLTextParagraphExport::exportListAndSectionChange( Reference<XTextSection> & rPrevSection, const Reference<XTextSection> & rNextSection, const XMLTextNumRuleInfo& rPrevRule, const XMLTextNumRuleInfo& rNextRule, sal_Bool bAutoStyles) { // old != new? -> maybe we have to start or end a new section if (rPrevSection != rNextSection) { // a new section started, or an old one gets closed! // close old list XMLTextNumRuleInfo aEmptyNumRule; if ( !bAutoStyles ) exportListChange(rPrevRule, aEmptyNumRule); // Build stacks of old and new sections // Sections on top of mute sections should not be on the stack vector<Reference<XTextSection> > aOldStack; Reference<XTextSection> aCurrent(rPrevSection); while(aCurrent.is()) { // if we have a mute section, ignore all its children // (all previous ones) if (pSectionExport->IsMuteSection(aCurrent)) aOldStack.clear(); aOldStack.push_back(aCurrent); aCurrent.set(aCurrent->getParentSection()); } vector<Reference<XTextSection> > aNewStack; aCurrent.set(rNextSection); sal_Bool bMute = sal_False; while(aCurrent.is()) { // if we have a mute section, ignore all its children // (all previous ones) if (pSectionExport->IsMuteSection(aCurrent)) { aNewStack.clear(); bMute = sal_True; } aNewStack.push_back(aCurrent); aCurrent.set(aCurrent->getParentSection()); } // compare the two stacks vector<Reference<XTextSection> > ::reverse_iterator aOld = aOldStack.rbegin(); vector<Reference<XTextSection> > ::reverse_iterator aNew = aNewStack.rbegin(); // compare bottom sections and skip equal section while ( (aOld != aOldStack.rend()) && (aNew != aNewStack.rend()) && (*aOld) == (*aNew) ) { ++aOld; ++aNew; } // close all elements of aOld ... // (order: newest to oldest) if (aOld != aOldStack.rend()) { vector<Reference<XTextSection> > ::iterator aOldForward( aOldStack.begin()); while ((aOldForward != aOldStack.end()) && (*aOldForward != *aOld)) { if ( !bAutoStyles && (NULL != pRedlineExport) ) pRedlineExport->ExportStartOrEndRedline(*aOldForward, sal_False); pSectionExport->ExportSectionEnd(*aOldForward, bAutoStyles); ++aOldForward; } if (aOldForward != aOldStack.end()) { if ( !bAutoStyles && (NULL != pRedlineExport) ) pRedlineExport->ExportStartOrEndRedline(*aOldForward, sal_False); pSectionExport->ExportSectionEnd(*aOldForward, bAutoStyles); } } // ...then open all of aNew // (order: oldest to newest) while (aNew != aNewStack.rend()) { if ( !bAutoStyles && (NULL != pRedlineExport) ) pRedlineExport->ExportStartOrEndRedline(*aNew, sal_True); pSectionExport->ExportSectionStart(*aNew, bAutoStyles); ++aNew; } // start new list if ( !bAutoStyles && !bMute ) exportListChange(aEmptyNumRule, rNextRule); } else { // list change, if sections have not changed if ( !bAutoStyles ) exportListChange(rPrevRule, rNextRule); } // save old section (old numRule gets saved in calling method) rPrevSection.set(rNextSection); } <commit_msg>INTEGRATION: CWS ooo19126 (1.14.94); FILE MERGED 2005/09/05 14:40:11 rt 1.14.94.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: txtsecte.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: rt $ $Date: 2005-09-09 15:33:18 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _XMLOFF_TXTPARAE_HXX #include "txtparae.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #include <vector> #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_ #include <com/sun/star/container/XIndexReplace.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUES_HPP_ #include <com/sun/star/beans/PropertyValues.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_ #include <com/sun/star/beans/PropertyState.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_ #include <com/sun/star/text/XText.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_XTEXTSECTION_HPP_ #include <com/sun/star/text/XTextSection.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_SECTIONFILELINK_HPP_ #include <com/sun/star/text/SectionFileLink.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_ #include <com/sun/star/container/XNamed.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_XDOCUMENTINDEX_HPP_ #include <com/sun/star/text/XDocumentIndex.hpp> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_FAMILIES_HXX_ #include "families.hxx" #endif #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLEXP_HXX #include "xmlexp.hxx" #endif #ifndef _XMLOFF_XMLTKMAP_HXX #include "xmltkmap.hxx" #endif #ifndef _XMLOFF_XMLTEXTNUMRULEINFO_HXX #include "XMLTextNumRuleInfo.hxx" #endif #ifndef _XMLOFF_XMLSECTIONEXPORT_HXX_ #include "XMLSectionExport.hxx" #endif #ifndef _XMLOFF_XMLREDLINEEXPORT_HXX #include "XMLRedlineExport.hxx" #endif #ifndef _XMLOFF_MULTIPROPERTYSETHELPER_HXX #include "MultiPropertySetHelper.hxx" #endif using namespace ::com::sun::star; using namespace ::com::sun::star::text; using namespace ::com::sun::star::uno; using namespace ::std; using ::rtl::OUString; using ::rtl::OUStringBuffer; using ::com::sun::star::beans::XPropertySet; using ::com::sun::star::beans::PropertyValue; using ::com::sun::star::beans::PropertyValues; using ::com::sun::star::beans::PropertyState; using ::com::sun::star::container::XIndexReplace; using ::com::sun::star::container::XNamed; using ::com::sun::star::lang::XServiceInfo; Reference<XText> lcl_findXText(const Reference<XTextSection>& rSect) { Reference<XText> xText; Reference<XTextContent> xTextContent(rSect, UNO_QUERY); if (xTextContent.is()) { xText.set(xTextContent->getAnchor()->getText()); } return xText; } void XMLTextParagraphExport::exportListAndSectionChange( Reference<XTextSection> & rPrevSection, const Reference<XTextContent> & rNextSectionContent, const XMLTextNumRuleInfo& rPrevRule, const XMLTextNumRuleInfo& rNextRule, sal_Bool bAutoStyles) { Reference<XTextSection> xNextSection; // first: get current XTextSection Reference<XPropertySet> xPropSet(rNextSectionContent, UNO_QUERY); if (xPropSet.is()) { if (xPropSet->getPropertySetInfo()->hasPropertyByName(sTextSection)) { xPropSet->getPropertyValue(sTextSection) >>= xNextSection; } // else: no current section } exportListAndSectionChange(rPrevSection, xNextSection, rPrevRule, rNextRule, bAutoStyles); } void XMLTextParagraphExport::exportListAndSectionChange( Reference<XTextSection> & rPrevSection, MultiPropertySetHelper& rPropSetHelper, sal_Int16 nTextSectionId, const Reference<XTextContent> & rNextSectionContent, const XMLTextNumRuleInfo& rPrevRule, const XMLTextNumRuleInfo& rNextRule, sal_Bool bAutoStyles) { Reference<XTextSection> xNextSection; // first: get current XTextSection Reference<XPropertySet> xPropSet(rNextSectionContent, UNO_QUERY); if (xPropSet.is()) { if( !rPropSetHelper.checkedProperties() ) rPropSetHelper.hasProperties( xPropSet->getPropertySetInfo() ); if( rPropSetHelper.hasProperty( nTextSectionId )) { xNextSection.set(rPropSetHelper.getValue( nTextSectionId , xPropSet, sal_True ), uno::UNO_QUERY); } // else: no current section } exportListAndSectionChange(rPrevSection, xNextSection, rPrevRule, rNextRule, bAutoStyles); } void XMLTextParagraphExport::exportListAndSectionChange( Reference<XTextSection> & rPrevSection, const Reference<XTextSection> & rNextSection, const XMLTextNumRuleInfo& rPrevRule, const XMLTextNumRuleInfo& rNextRule, sal_Bool bAutoStyles) { // old != new? -> maybe we have to start or end a new section if (rPrevSection != rNextSection) { // a new section started, or an old one gets closed! // close old list XMLTextNumRuleInfo aEmptyNumRule; if ( !bAutoStyles ) exportListChange(rPrevRule, aEmptyNumRule); // Build stacks of old and new sections // Sections on top of mute sections should not be on the stack vector<Reference<XTextSection> > aOldStack; Reference<XTextSection> aCurrent(rPrevSection); while(aCurrent.is()) { // if we have a mute section, ignore all its children // (all previous ones) if (pSectionExport->IsMuteSection(aCurrent)) aOldStack.clear(); aOldStack.push_back(aCurrent); aCurrent.set(aCurrent->getParentSection()); } vector<Reference<XTextSection> > aNewStack; aCurrent.set(rNextSection); sal_Bool bMute = sal_False; while(aCurrent.is()) { // if we have a mute section, ignore all its children // (all previous ones) if (pSectionExport->IsMuteSection(aCurrent)) { aNewStack.clear(); bMute = sal_True; } aNewStack.push_back(aCurrent); aCurrent.set(aCurrent->getParentSection()); } // compare the two stacks vector<Reference<XTextSection> > ::reverse_iterator aOld = aOldStack.rbegin(); vector<Reference<XTextSection> > ::reverse_iterator aNew = aNewStack.rbegin(); // compare bottom sections and skip equal section while ( (aOld != aOldStack.rend()) && (aNew != aNewStack.rend()) && (*aOld) == (*aNew) ) { ++aOld; ++aNew; } // close all elements of aOld ... // (order: newest to oldest) if (aOld != aOldStack.rend()) { vector<Reference<XTextSection> > ::iterator aOldForward( aOldStack.begin()); while ((aOldForward != aOldStack.end()) && (*aOldForward != *aOld)) { if ( !bAutoStyles && (NULL != pRedlineExport) ) pRedlineExport->ExportStartOrEndRedline(*aOldForward, sal_False); pSectionExport->ExportSectionEnd(*aOldForward, bAutoStyles); ++aOldForward; } if (aOldForward != aOldStack.end()) { if ( !bAutoStyles && (NULL != pRedlineExport) ) pRedlineExport->ExportStartOrEndRedline(*aOldForward, sal_False); pSectionExport->ExportSectionEnd(*aOldForward, bAutoStyles); } } // ...then open all of aNew // (order: oldest to newest) while (aNew != aNewStack.rend()) { if ( !bAutoStyles && (NULL != pRedlineExport) ) pRedlineExport->ExportStartOrEndRedline(*aNew, sal_True); pSectionExport->ExportSectionStart(*aNew, bAutoStyles); ++aNew; } // start new list if ( !bAutoStyles && !bMute ) exportListChange(aEmptyNumRule, rNextRule); } else { // list change, if sections have not changed if ( !bAutoStyles ) exportListChange(rPrevRule, rNextRule); } // save old section (old numRule gets saved in calling method) rPrevSection.set(rNextSection); } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkExtractSliceFilter2.h> #include <mitkExceptionMacro.h> #include <mitkImageAccessByItk.h> #include <mitkImageWriteAccessor.h> #include <itkBSplineInterpolateImageFunction.h> #include <itkLinearInterpolateImageFunction.h> #include <itkNearestNeighborInterpolateImageFunction.h> #include <limits> struct mitk::ExtractSliceFilter2::Impl { Impl(); ~Impl(); PlaneGeometry::Pointer OutputGeometry; mitk::ExtractSliceFilter2::Interpolator Interpolator; itk::Object::Pointer InterpolateImageFunction; }; mitk::ExtractSliceFilter2::Impl::Impl() : Interpolator(NearestNeighbor) { } mitk::ExtractSliceFilter2::Impl::~Impl() { } namespace { template <class TInputImage> void CreateInterpolateImageFunction(const TInputImage* inputImage, mitk::ExtractSliceFilter2::Interpolator interpolator, itk::Object::Pointer& result) { typename itk::InterpolateImageFunction<TInputImage>::Pointer interpolateImageFunction; switch (interpolator) { case mitk::ExtractSliceFilter2::NearestNeighbor: interpolateImageFunction = itk::NearestNeighborInterpolateImageFunction<TInputImage>::New().GetPointer(); break; case mitk::ExtractSliceFilter2::Linear: interpolateImageFunction = itk::LinearInterpolateImageFunction<TInputImage>::New().GetPointer(); break; case mitk::ExtractSliceFilter2::Cubic: { auto bSplineInterpolateImageFunction = itk::BSplineInterpolateImageFunction<TInputImage>::New(); bSplineInterpolateImageFunction->SetSplineOrder(2); interpolateImageFunction = bSplineInterpolateImageFunction.GetPointer(); break; } default: mitkThrow() << "Interplator is unknown."; } interpolateImageFunction->SetInputImage(inputImage); result = interpolateImageFunction.GetPointer(); } template <typename TPixel, unsigned int VImageDimension> void GenerateData(const itk::Image<TPixel, VImageDimension>* inputImage, mitk::Image* outputImage, const mitk::ExtractSliceFilter2::OutputImageRegionType& outputRegion, itk::Object* interpolateImageFunction) { typedef itk::Image<TPixel, VImageDimension> TInputImage; typedef itk::InterpolateImageFunction<TInputImage> TInterpolateImageFunction; auto outputGeometry = outputImage->GetSlicedGeometry()->GetPlaneGeometry(0); auto interpolator = static_cast<TInterpolateImageFunction*>(interpolateImageFunction); auto origin = outputGeometry->GetOrigin(); auto spacing = outputGeometry->GetSpacing(); auto xDirection = outputGeometry->GetAxisVector(0); auto yDirection = outputGeometry->GetAxisVector(1); xDirection.Normalize(); yDirection.Normalize(); auto spacingAlongXDirection = xDirection * spacing[0]; auto spacingAlongYDirection = yDirection * spacing[1]; origin -= spacingAlongXDirection * 0.5; origin -= spacingAlongYDirection * 0.5; const std::size_t pixelSize = outputImage->GetPixelType().GetSize(); const std::size_t width = outputGeometry->GetExtent(0); const std::size_t xBegin = outputRegion.GetIndex(0); const std::size_t yBegin = outputRegion.GetIndex(1); const std::size_t xEnd = xBegin + outputRegion.GetSize(0); const std::size_t yEnd = yBegin + outputRegion.GetSize(1); mitk::ImageWriteAccessor writeAccess(outputImage, nullptr, mitk::ImageAccessorBase::IgnoreLock); auto data = static_cast<char*>(writeAccess.GetData());; const TPixel backgroundPixel = std::numeric_limits<TPixel>::lowest(); TPixel pixel; itk::ContinuousIndex<mitk::ScalarType, 3> index; mitk::Point3D yPoint; mitk::Point3D point; for (std::size_t y = yBegin; y < yEnd; ++y) { yPoint = origin + spacingAlongYDirection * y; for (std::size_t x = xBegin; x < xEnd; ++x) { point = yPoint + spacingAlongXDirection * x; if (inputImage->TransformPhysicalPointToContinuousIndex(point, index)) { pixel = interpolator->EvaluateAtContinuousIndex(index); memcpy(static_cast<void*>(data + pixelSize * (width * y + x)), static_cast<const void*>(&pixel), pixelSize); } else { memcpy(static_cast<void*>(data + pixelSize * (width * y + x)), static_cast<const void*>(&backgroundPixel), pixelSize); } } } } void VerifyInputImage(const mitk::Image* inputImage) { auto dimension = inputImage->GetDimension(); if (3 != dimension) mitkThrow() << "Input images with " << dimension << " dimensions are not supported."; if (!inputImage->IsInitialized()) mitkThrow() << "Input image is not initialized."; if (!inputImage->IsVolumeSet()) mitkThrow() << "Input image volume is not set."; auto geometry = inputImage->GetGeometry(); if (nullptr == geometry || !geometry->IsValid()) mitkThrow() << "Input image has invalid geometry."; if (!geometry->GetImageGeometry()) mitkThrow() << "Geometry of input image is not an image geometry."; } void VerifyOutputGeometry(const mitk::PlaneGeometry* outputGeometry) { if (nullptr == outputGeometry) mitkThrow() << "Output geometry is not set."; if (!outputGeometry->GetImageGeometry()) mitkThrow() << "Output geometry is not an image geometry."; } } mitk::ExtractSliceFilter2::ExtractSliceFilter2() : m_Impl(new Impl) { } mitk::ExtractSliceFilter2::~ExtractSliceFilter2() { delete m_Impl; } void mitk::ExtractSliceFilter2::AllocateOutputs() { const auto* inputImage = this->GetInput(); const auto* outputGeometry = this->GetOutputGeometry(); auto outputImage = this->GetOutput(); auto pixelType = inputImage->GetPixelType(); outputImage->Initialize(pixelType, 1, *outputGeometry); auto data = new char[static_cast<std::size_t>(pixelType.GetSize() * outputGeometry->GetExtent(0) * outputGeometry->GetExtent(1))]; try { if (!outputImage->SetImportVolume(data, 0, 0, mitk::Image::ReferenceMemory)) throw; } catch (...) { delete[] data; } } void mitk::ExtractSliceFilter2::BeforeThreadedGenerateData() { if (nullptr != m_Impl->InterpolateImageFunction && this->GetInput()->GetMTime() < this->GetMTime()) return; const auto* inputImage = this->GetInput(); AccessFixedDimensionByItk_2(inputImage, CreateInterpolateImageFunction, 3, this->GetInterpolator(), m_Impl->InterpolateImageFunction); } void mitk::ExtractSliceFilter2::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, itk::ThreadIdType) { const auto* inputImage = this->GetInput(); AccessFixedDimensionByItk_3(inputImage, ::GenerateData, 3, this->GetOutput(), outputRegionForThread, m_Impl->InterpolateImageFunction); } void mitk::ExtractSliceFilter2::SetInput(const InputImageType* image) { if (this->GetInput() == image) return; Superclass::SetInput(image); m_Impl->InterpolateImageFunction = nullptr; } void mitk::ExtractSliceFilter2::SetInput(unsigned int index, const InputImageType* image) { if (0 != index) mitkThrow() << "Input index " << index << " is invalid."; this->SetInput(image); } const mitk::PlaneGeometry* mitk::ExtractSliceFilter2::GetOutputGeometry() const { return m_Impl->OutputGeometry; } void mitk::ExtractSliceFilter2::SetOutputGeometry(PlaneGeometry::Pointer outputGeometry) { if (m_Impl->OutputGeometry != outputGeometry) { m_Impl->OutputGeometry = outputGeometry; this->Modified(); } } mitk::ExtractSliceFilter2::Interpolator mitk::ExtractSliceFilter2::GetInterpolator() const { return m_Impl->Interpolator; } void mitk::ExtractSliceFilter2::SetInterpolator(Interpolator interpolator) { if (m_Impl->Interpolator != interpolator) { m_Impl->Interpolator = interpolator; m_Impl->InterpolateImageFunction = nullptr; this->Modified(); } } void mitk::ExtractSliceFilter2::VerifyInputInformation() { Superclass::VerifyInputInformation(); VerifyInputImage(this->GetInput()); VerifyOutputGeometry(this->GetOutputGeometry()); } <commit_msg>Fix origin for interpolators<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkExtractSliceFilter2.h> #include <mitkExceptionMacro.h> #include <mitkImageAccessByItk.h> #include <mitkImageWriteAccessor.h> #include <itkBSplineInterpolateImageFunction.h> #include <itkLinearInterpolateImageFunction.h> #include <itkNearestNeighborInterpolateImageFunction.h> #include <limits> struct mitk::ExtractSliceFilter2::Impl { Impl(); ~Impl(); PlaneGeometry::Pointer OutputGeometry; mitk::ExtractSliceFilter2::Interpolator Interpolator; itk::Object::Pointer InterpolateImageFunction; }; mitk::ExtractSliceFilter2::Impl::Impl() : Interpolator(NearestNeighbor) { } mitk::ExtractSliceFilter2::Impl::~Impl() { } namespace { template <class TInputImage> void CreateInterpolateImageFunction(const TInputImage* inputImage, mitk::ExtractSliceFilter2::Interpolator interpolator, itk::Object::Pointer& result) { typename itk::InterpolateImageFunction<TInputImage>::Pointer interpolateImageFunction; switch (interpolator) { case mitk::ExtractSliceFilter2::NearestNeighbor: interpolateImageFunction = itk::NearestNeighborInterpolateImageFunction<TInputImage>::New().GetPointer(); break; case mitk::ExtractSliceFilter2::Linear: interpolateImageFunction = itk::LinearInterpolateImageFunction<TInputImage>::New().GetPointer(); break; case mitk::ExtractSliceFilter2::Cubic: { auto bSplineInterpolateImageFunction = itk::BSplineInterpolateImageFunction<TInputImage>::New(); bSplineInterpolateImageFunction->SetSplineOrder(2); interpolateImageFunction = bSplineInterpolateImageFunction.GetPointer(); break; } default: mitkThrow() << "Interplator is unknown."; } interpolateImageFunction->SetInputImage(inputImage); result = interpolateImageFunction.GetPointer(); } template <typename TPixel, unsigned int VImageDimension> void GenerateData(const itk::Image<TPixel, VImageDimension>* inputImage, mitk::Image* outputImage, const mitk::ExtractSliceFilter2::OutputImageRegionType& outputRegion, itk::Object* interpolateImageFunction) { typedef itk::Image<TPixel, VImageDimension> TInputImage; typedef itk::InterpolateImageFunction<TInputImage> TInterpolateImageFunction; auto outputGeometry = outputImage->GetSlicedGeometry()->GetPlaneGeometry(0); auto interpolator = static_cast<TInterpolateImageFunction*>(interpolateImageFunction); auto origin = outputGeometry->GetOrigin(); auto spacing = outputGeometry->GetSpacing(); auto xDirection = outputGeometry->GetAxisVector(0); auto yDirection = outputGeometry->GetAxisVector(1); xDirection.Normalize(); yDirection.Normalize(); auto spacingAlongXDirection = xDirection * spacing[0]; auto spacingAlongYDirection = yDirection * spacing[1]; const std::size_t pixelSize = outputImage->GetPixelType().GetSize(); const std::size_t width = outputGeometry->GetExtent(0); const std::size_t xBegin = outputRegion.GetIndex(0); const std::size_t yBegin = outputRegion.GetIndex(1); const std::size_t xEnd = xBegin + outputRegion.GetSize(0); const std::size_t yEnd = yBegin + outputRegion.GetSize(1); mitk::ImageWriteAccessor writeAccess(outputImage, nullptr, mitk::ImageAccessorBase::IgnoreLock); auto data = static_cast<char*>(writeAccess.GetData());; const TPixel backgroundPixel = std::numeric_limits<TPixel>::lowest(); TPixel pixel; itk::ContinuousIndex<mitk::ScalarType, 3> index; mitk::Point3D yPoint; mitk::Point3D point; for (std::size_t y = yBegin; y < yEnd; ++y) { yPoint = origin + spacingAlongYDirection * y; for (std::size_t x = xBegin; x < xEnd; ++x) { point = yPoint + spacingAlongXDirection * x; if (inputImage->TransformPhysicalPointToContinuousIndex(point, index)) { pixel = interpolator->EvaluateAtContinuousIndex(index); memcpy(static_cast<void*>(data + pixelSize * (width * y + x)), static_cast<const void*>(&pixel), pixelSize); } else { memcpy(static_cast<void*>(data + pixelSize * (width * y + x)), static_cast<const void*>(&backgroundPixel), pixelSize); } } } } void VerifyInputImage(const mitk::Image* inputImage) { auto dimension = inputImage->GetDimension(); if (3 != dimension) mitkThrow() << "Input images with " << dimension << " dimensions are not supported."; if (!inputImage->IsInitialized()) mitkThrow() << "Input image is not initialized."; if (!inputImage->IsVolumeSet()) mitkThrow() << "Input image volume is not set."; auto geometry = inputImage->GetGeometry(); if (nullptr == geometry || !geometry->IsValid()) mitkThrow() << "Input image has invalid geometry."; if (!geometry->GetImageGeometry()) mitkThrow() << "Geometry of input image is not an image geometry."; } void VerifyOutputGeometry(const mitk::PlaneGeometry* outputGeometry) { if (nullptr == outputGeometry) mitkThrow() << "Output geometry is not set."; if (!outputGeometry->GetImageGeometry()) mitkThrow() << "Output geometry is not an image geometry."; } } mitk::ExtractSliceFilter2::ExtractSliceFilter2() : m_Impl(new Impl) { } mitk::ExtractSliceFilter2::~ExtractSliceFilter2() { delete m_Impl; } void mitk::ExtractSliceFilter2::AllocateOutputs() { const auto* inputImage = this->GetInput(); const auto* outputGeometry = this->GetOutputGeometry(); auto outputImage = this->GetOutput(); auto pixelType = inputImage->GetPixelType(); outputImage->Initialize(pixelType, 1, *outputGeometry); auto data = new char[static_cast<std::size_t>(pixelType.GetSize() * outputGeometry->GetExtent(0) * outputGeometry->GetExtent(1))]; try { if (!outputImage->SetImportVolume(data, 0, 0, mitk::Image::ReferenceMemory)) throw; } catch (...) { delete[] data; } } void mitk::ExtractSliceFilter2::BeforeThreadedGenerateData() { if (nullptr != m_Impl->InterpolateImageFunction && this->GetInput()->GetMTime() < this->GetMTime()) return; const auto* inputImage = this->GetInput(); AccessFixedDimensionByItk_2(inputImage, CreateInterpolateImageFunction, 3, this->GetInterpolator(), m_Impl->InterpolateImageFunction); } void mitk::ExtractSliceFilter2::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, itk::ThreadIdType) { const auto* inputImage = this->GetInput(); AccessFixedDimensionByItk_3(inputImage, ::GenerateData, 3, this->GetOutput(), outputRegionForThread, m_Impl->InterpolateImageFunction); } void mitk::ExtractSliceFilter2::SetInput(const InputImageType* image) { if (this->GetInput() == image) return; Superclass::SetInput(image); m_Impl->InterpolateImageFunction = nullptr; } void mitk::ExtractSliceFilter2::SetInput(unsigned int index, const InputImageType* image) { if (0 != index) mitkThrow() << "Input index " << index << " is invalid."; this->SetInput(image); } const mitk::PlaneGeometry* mitk::ExtractSliceFilter2::GetOutputGeometry() const { return m_Impl->OutputGeometry; } void mitk::ExtractSliceFilter2::SetOutputGeometry(PlaneGeometry::Pointer outputGeometry) { if (m_Impl->OutputGeometry != outputGeometry) { m_Impl->OutputGeometry = outputGeometry; this->Modified(); } } mitk::ExtractSliceFilter2::Interpolator mitk::ExtractSliceFilter2::GetInterpolator() const { return m_Impl->Interpolator; } void mitk::ExtractSliceFilter2::SetInterpolator(Interpolator interpolator) { if (m_Impl->Interpolator != interpolator) { m_Impl->Interpolator = interpolator; m_Impl->InterpolateImageFunction = nullptr; this->Modified(); } } void mitk::ExtractSliceFilter2::VerifyInputInformation() { Superclass::VerifyInputInformation(); VerifyInputImage(this->GetInput()); VerifyOutputGeometry(this->GetOutputGeometry()); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/tools/test_shell/test_shell_webkit_init.h" #include "base/path_service.h" #include "base/stats_counters.h" #include "media/base/media.h" #include "third_party/WebKit/WebKit/chromium/public/WebDatabase.h" #include "third_party/WebKit/WebKit/chromium/public/WebKit.h" #include "third_party/WebKit/WebKit/chromium/public/WebRuntimeFeatures.h" #include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h" #include "third_party/WebKit/WebKit/chromium/public/WebSecurityPolicy.h" #include "webkit/extensions/v8/gears_extension.h" #include "webkit/extensions/v8/interval_extension.h" #include "webkit/tools/test_shell/test_shell.h" #if defined(OS_WIN) #include "webkit/tools/test_shell/test_shell_webthemeengine.h" #endif TestShellWebKitInit::TestShellWebKitInit(bool layout_test_mode) { v8::V8::SetCounterFunction(StatsTable::FindLocation); WebKit::initialize(this); WebKit::setLayoutTestMode(layout_test_mode); WebKit::WebSecurityPolicy::registerURLSchemeAsLocal( WebKit::WebString::fromUTF8("test-shell-resource")); WebKit::WebSecurityPolicy::registerURLSchemeAsNoAccess( WebKit::WebString::fromUTF8("test-shell-resource")); WebKit::WebScriptController::enableV8SingleThreadMode(); WebKit::WebScriptController::registerExtension( extensions_v8::GearsExtension::Get()); WebKit::WebScriptController::registerExtension( extensions_v8::IntervalExtension::Get()); WebKit::WebRuntimeFeatures::enableSockets(true); WebKit::WebRuntimeFeatures::enableApplicationCache(true); WebKit::WebRuntimeFeatures::enableDatabase(true); WebKit::WebRuntimeFeatures::enableWebGL(true); WebKit::WebRuntimeFeatures::enablePushState(true); WebKit::WebRuntimeFeatures::enableNotifications(true); WebKit::WebRuntimeFeatures::enableTouch(true); WebKit::WebRuntimeFeatures::enableIndexedDatabase(true); WebKit::WebRuntimeFeatures::enableSpeechInput(true); // TODO(hwennborg): Enable this once the implementation supports it. WebKit::WebRuntimeFeatures::enableDeviceOrientation(false); // Load libraries for media and enable the media player. FilePath module_path; WebKit::WebRuntimeFeatures::enableMediaPlayer( PathService::Get(base::DIR_MODULE, &module_path) && media::InitializeMediaLibrary(module_path)); WebKit::WebRuntimeFeatures::enableGeolocation(true); // Construct and initialize an appcache system for this scope. // A new empty temp directory is created to house any cached // content during the run. Upon exit that directory is deleted. // If we can't create a tempdir, we'll use in-memory storage. if (!appcache_dir_.CreateUniqueTempDir()) { LOG(WARNING) << "Failed to create a temp dir for the appcache, " "using in-memory storage."; DCHECK(appcache_dir_.path().empty()); } SimpleAppCacheSystem::InitializeOnUIThread(appcache_dir_.path()); WebKit::WebDatabase::setObserver(&database_system_); file_system_.set_sandbox_enabled(false); #if defined(OS_WIN) // Ensure we pick up the default theme engine. SetThemeEngine(NULL); #endif } TestShellWebKitInit::~TestShellWebKitInit() { WebKit::shutdown(); } WebKit::WebClipboard* TestShellWebKitInit::clipboard() { // Mock out clipboard calls in layout test mode so that tests don't mess // with each other's copies/pastes when running in parallel. if (TestShell::layout_test_mode()) { return &mock_clipboard_; } else { return &real_clipboard_; } } WebKit::WebData TestShellWebKitInit::loadResource(const char* name) { if (!strcmp(name, "deleteButton")) { // Create a red 30x30 square. const char red_square[] = "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52" "\x00\x00\x00\x1e\x00\x00\x00\x1e\x04\x03\x00\x00\x00\xc9\x1e\xb3" "\x91\x00\x00\x00\x30\x50\x4c\x54\x45\x00\x00\x00\x80\x00\x00\x00" "\x80\x00\x80\x80\x00\x00\x00\x80\x80\x00\x80\x00\x80\x80\x80\x80" "\x80\xc0\xc0\xc0\xff\x00\x00\x00\xff\x00\xff\xff\x00\x00\x00\xff" "\xff\x00\xff\x00\xff\xff\xff\xff\xff\x7b\x1f\xb1\xc4\x00\x00\x00" "\x09\x70\x48\x59\x73\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a" "\x9c\x18\x00\x00\x00\x17\x49\x44\x41\x54\x78\x01\x63\x98\x89\x0a" "\x18\x50\xb9\x33\x47\xf9\xa8\x01\x32\xd4\xc2\x03\x00\x33\x84\x0d" "\x02\x3a\x91\xeb\xa5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60" "\x82"; return WebKit::WebData(red_square, arraysize(red_square)); } return webkit_glue::WebKitClientImpl::loadResource(name); } <commit_msg>Disable device motion in test shell.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/tools/test_shell/test_shell_webkit_init.h" #include "base/path_service.h" #include "base/stats_counters.h" #include "media/base/media.h" #include "third_party/WebKit/WebKit/chromium/public/WebDatabase.h" #include "third_party/WebKit/WebKit/chromium/public/WebKit.h" #include "third_party/WebKit/WebKit/chromium/public/WebRuntimeFeatures.h" #include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h" #include "third_party/WebKit/WebKit/chromium/public/WebSecurityPolicy.h" #include "webkit/extensions/v8/gears_extension.h" #include "webkit/extensions/v8/interval_extension.h" #include "webkit/tools/test_shell/test_shell.h" #if defined(OS_WIN) #include "webkit/tools/test_shell/test_shell_webthemeengine.h" #endif TestShellWebKitInit::TestShellWebKitInit(bool layout_test_mode) { v8::V8::SetCounterFunction(StatsTable::FindLocation); WebKit::initialize(this); WebKit::setLayoutTestMode(layout_test_mode); WebKit::WebSecurityPolicy::registerURLSchemeAsLocal( WebKit::WebString::fromUTF8("test-shell-resource")); WebKit::WebSecurityPolicy::registerURLSchemeAsNoAccess( WebKit::WebString::fromUTF8("test-shell-resource")); WebKit::WebScriptController::enableV8SingleThreadMode(); WebKit::WebScriptController::registerExtension( extensions_v8::GearsExtension::Get()); WebKit::WebScriptController::registerExtension( extensions_v8::IntervalExtension::Get()); WebKit::WebRuntimeFeatures::enableSockets(true); WebKit::WebRuntimeFeatures::enableApplicationCache(true); WebKit::WebRuntimeFeatures::enableDatabase(true); WebKit::WebRuntimeFeatures::enableWebGL(true); WebKit::WebRuntimeFeatures::enablePushState(true); WebKit::WebRuntimeFeatures::enableNotifications(true); WebKit::WebRuntimeFeatures::enableTouch(true); WebKit::WebRuntimeFeatures::enableIndexedDatabase(true); WebKit::WebRuntimeFeatures::enableSpeechInput(true); // TODO(hwennborg): Enable this once the implementation supports it. WebKit::WebRuntimeFeatures::enableDeviceMotion(false); WebKit::WebRuntimeFeatures::enableDeviceOrientation(false); // Load libraries for media and enable the media player. FilePath module_path; WebKit::WebRuntimeFeatures::enableMediaPlayer( PathService::Get(base::DIR_MODULE, &module_path) && media::InitializeMediaLibrary(module_path)); WebKit::WebRuntimeFeatures::enableGeolocation(true); // Construct and initialize an appcache system for this scope. // A new empty temp directory is created to house any cached // content during the run. Upon exit that directory is deleted. // If we can't create a tempdir, we'll use in-memory storage. if (!appcache_dir_.CreateUniqueTempDir()) { LOG(WARNING) << "Failed to create a temp dir for the appcache, " "using in-memory storage."; DCHECK(appcache_dir_.path().empty()); } SimpleAppCacheSystem::InitializeOnUIThread(appcache_dir_.path()); WebKit::WebDatabase::setObserver(&database_system_); file_system_.set_sandbox_enabled(false); #if defined(OS_WIN) // Ensure we pick up the default theme engine. SetThemeEngine(NULL); #endif } TestShellWebKitInit::~TestShellWebKitInit() { WebKit::shutdown(); } WebKit::WebClipboard* TestShellWebKitInit::clipboard() { // Mock out clipboard calls in layout test mode so that tests don't mess // with each other's copies/pastes when running in parallel. if (TestShell::layout_test_mode()) { return &mock_clipboard_; } else { return &real_clipboard_; } } WebKit::WebData TestShellWebKitInit::loadResource(const char* name) { if (!strcmp(name, "deleteButton")) { // Create a red 30x30 square. const char red_square[] = "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52" "\x00\x00\x00\x1e\x00\x00\x00\x1e\x04\x03\x00\x00\x00\xc9\x1e\xb3" "\x91\x00\x00\x00\x30\x50\x4c\x54\x45\x00\x00\x00\x80\x00\x00\x00" "\x80\x00\x80\x80\x00\x00\x00\x80\x80\x00\x80\x00\x80\x80\x80\x80" "\x80\xc0\xc0\xc0\xff\x00\x00\x00\xff\x00\xff\xff\x00\x00\x00\xff" "\xff\x00\xff\x00\xff\xff\xff\xff\xff\x7b\x1f\xb1\xc4\x00\x00\x00" "\x09\x70\x48\x59\x73\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a" "\x9c\x18\x00\x00\x00\x17\x49\x44\x41\x54\x78\x01\x63\x98\x89\x0a" "\x18\x50\xb9\x33\x47\xf9\xa8\x01\x32\xd4\xc2\x03\x00\x33\x84\x0d" "\x02\x3a\x91\xeb\xa5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60" "\x82"; return WebKit::WebData(red_square, arraysize(red_square)); } return webkit_glue::WebKitClientImpl::loadResource(name); } <|endoftext|>
<commit_before><commit_msg>update<commit_after>/* * D. Two Friends * time limit per test1 second * memory limit per test64 megabytes * inputstandard input * outputstandard output * Two neighbours, Alan and Bob, live in the city, where there are three buildings only: a cinema, a shop and the house, where they live. The rest is a big asphalt square. * * Once they went to the cinema, and the film impressed them so deeply, that when they left the cinema, they did not want to stop discussing it. * * Bob wants to get home, but Alan has to go to the shop first, and only then go home. So, they agreed to cover some distance together discussing the film (their common path might pass through the shop, or they might walk circles around the cinema together), and then to part each other's company and go each his own way. After they part, they will start thinking about their daily pursuits; and even if they meet again, they won't be able to go on with the discussion. Thus, Bob's path will be a continuous curve, having the cinema and the house as its ends. Alan's path — a continuous curve, going through the shop, and having the cinema and the house as its ends. * * The film ended late, that's why the whole distance covered by Alan should not differ from the shortest one by more than t1, and the distance covered by Bob should not differ from the shortest one by more than t2. * * Find the maximum distance that Alan and Bob will cover together, discussing the film. * * Input * The first line contains two integers: t1, t2 (0 ≤ t1, t2 ≤ 100). The second line contains the cinema's coordinates, the third one — the house's, and the last line — the shop's. * * All the coordinates are given in meters, are integer, and do not exceed 100 in absolute magnitude. No two given places are in the same building. * * Output * In the only line output one number — the maximum distance that Alan and Bob will cover together, discussing the film. Output the answer accurate to not less than 4 decimal places. * * Examples * input * 0 2 * 0 0 * 4 0 * -3 0 * output * 1.0000000000 * input * 0 0 * 0 0 * 2 0 * 1 0 * output * 2.0000000000 * */ int main() { return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/tools/test_shell/test_shell_webkit_init.h" #include "base/path_service.h" #include "base/stats_counters.h" #include "media/base/media.h" #include "third_party/WebKit/WebKit/chromium/public/WebDatabase.h" #include "third_party/WebKit/WebKit/chromium/public/WebKit.h" #include "third_party/WebKit/WebKit/chromium/public/WebRuntimeFeatures.h" #include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h" #include "third_party/WebKit/WebKit/chromium/public/WebSecurityPolicy.h" #include "webkit/extensions/v8/gears_extension.h" #include "webkit/extensions/v8/interval_extension.h" #include "webkit/tools/test_shell/test_shell.h" #if defined(OS_WIN) #include "webkit/tools/test_shell/test_shell_webthemeengine.h" #endif TestShellWebKitInit::TestShellWebKitInit(bool layout_test_mode) { v8::V8::SetCounterFunction(StatsTable::FindLocation); WebKit::initialize(this); WebKit::setLayoutTestMode(layout_test_mode); WebKit::WebSecurityPolicy::registerURLSchemeAsLocal( WebKit::WebString::fromUTF8("test-shell-resource")); WebKit::WebSecurityPolicy::registerURLSchemeAsNoAccess( WebKit::WebString::fromUTF8("test-shell-resource")); WebKit::WebScriptController::enableV8SingleThreadMode(); WebKit::WebScriptController::registerExtension( extensions_v8::GearsExtension::Get()); WebKit::WebScriptController::registerExtension( extensions_v8::IntervalExtension::Get()); WebKit::WebRuntimeFeatures::enableSockets(true); WebKit::WebRuntimeFeatures::enableApplicationCache(true); WebKit::WebRuntimeFeatures::enableDatabase(true); WebKit::WebRuntimeFeatures::enableWebGL(true); WebKit::WebRuntimeFeatures::enablePushState(true); WebKit::WebRuntimeFeatures::enableNotifications(true); WebKit::WebRuntimeFeatures::enableTouch(true); WebKit::WebRuntimeFeatures::enableIndexedDatabase(true); // Load libraries for media and enable the media player. FilePath module_path; WebKit::WebRuntimeFeatures::enableMediaPlayer( PathService::Get(base::DIR_MODULE, &module_path) && media::InitializeMediaLibrary(module_path)); WebKit::WebRuntimeFeatures::enableGeolocation(true); // Construct and initialize an appcache system for this scope. // A new empty temp directory is created to house any cached // content during the run. Upon exit that directory is deleted. // If we can't create a tempdir, we'll use in-memory storage. if (!appcache_dir_.CreateUniqueTempDir()) { LOG(WARNING) << "Failed to create a temp dir for the appcache, " "using in-memory storage."; DCHECK(appcache_dir_.path().empty()); } SimpleAppCacheSystem::InitializeOnUIThread(appcache_dir_.path()); WebKit::WebDatabase::setObserver(&database_system_); file_system_.set_sandbox_enabled(false); #if defined(OS_WIN) // Ensure we pick up the default theme engine. SetThemeEngine(NULL); #endif } TestShellWebKitInit::~TestShellWebKitInit() { WebKit::shutdown(); } WebKit::WebClipboard* TestShellWebKitInit::clipboard() { // Mock out clipboard calls in layout test mode so that tests don't mess // with each other's copies/pastes when running in parallel. if (TestShell::layout_test_mode()) { return &mock_clipboard_; } else { return &real_clipboard_; } } WebKit::WebData TestShellWebKitInit::loadResource(const char* name) { if (!strcmp(name, "deleteButton")) { // Create a red 30x30 square. const char red_square[] = "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52" "\x00\x00\x00\x1e\x00\x00\x00\x1e\x04\x03\x00\x00\x00\xc9\x1e\xb3" "\x91\x00\x00\x00\x30\x50\x4c\x54\x45\x00\x00\x00\x80\x00\x00\x00" "\x80\x00\x80\x80\x00\x00\x00\x80\x80\x00\x80\x00\x80\x80\x80\x80" "\x80\xc0\xc0\xc0\xff\x00\x00\x00\xff\x00\xff\xff\x00\x00\x00\xff" "\xff\x00\xff\x00\xff\xff\xff\xff\xff\x7b\x1f\xb1\xc4\x00\x00\x00" "\x09\x70\x48\x59\x73\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a" "\x9c\x18\x00\x00\x00\x17\x49\x44\x41\x54\x78\x01\x63\x98\x89\x0a" "\x18\x50\xb9\x33\x47\xf9\xa8\x01\x32\xd4\xc2\x03\x00\x33\x84\x0d" "\x02\x3a\x91\xeb\xa5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60" "\x82"; return WebKit::WebData(red_square, arraysize(red_square)); } return webkit_glue::WebKitClientImpl::loadResource(name); } <commit_msg>Disable run-time flag for device orientation in test_shell<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/tools/test_shell/test_shell_webkit_init.h" #include "base/path_service.h" #include "base/stats_counters.h" #include "media/base/media.h" #include "third_party/WebKit/WebKit/chromium/public/WebDatabase.h" #include "third_party/WebKit/WebKit/chromium/public/WebKit.h" #include "third_party/WebKit/WebKit/chromium/public/WebRuntimeFeatures.h" #include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h" #include "third_party/WebKit/WebKit/chromium/public/WebSecurityPolicy.h" #include "webkit/extensions/v8/gears_extension.h" #include "webkit/extensions/v8/interval_extension.h" #include "webkit/tools/test_shell/test_shell.h" #if defined(OS_WIN) #include "webkit/tools/test_shell/test_shell_webthemeengine.h" #endif TestShellWebKitInit::TestShellWebKitInit(bool layout_test_mode) { v8::V8::SetCounterFunction(StatsTable::FindLocation); WebKit::initialize(this); WebKit::setLayoutTestMode(layout_test_mode); WebKit::WebSecurityPolicy::registerURLSchemeAsLocal( WebKit::WebString::fromUTF8("test-shell-resource")); WebKit::WebSecurityPolicy::registerURLSchemeAsNoAccess( WebKit::WebString::fromUTF8("test-shell-resource")); WebKit::WebScriptController::enableV8SingleThreadMode(); WebKit::WebScriptController::registerExtension( extensions_v8::GearsExtension::Get()); WebKit::WebScriptController::registerExtension( extensions_v8::IntervalExtension::Get()); WebKit::WebRuntimeFeatures::enableSockets(true); WebKit::WebRuntimeFeatures::enableApplicationCache(true); WebKit::WebRuntimeFeatures::enableDatabase(true); WebKit::WebRuntimeFeatures::enableWebGL(true); WebKit::WebRuntimeFeatures::enablePushState(true); WebKit::WebRuntimeFeatures::enableNotifications(true); WebKit::WebRuntimeFeatures::enableTouch(true); WebKit::WebRuntimeFeatures::enableIndexedDatabase(true); // TODO(hwennborg): Enable this once the implementation supports it. WebKit::WebRuntimeFeatures::enableDeviceOrientation(false); // Load libraries for media and enable the media player. FilePath module_path; WebKit::WebRuntimeFeatures::enableMediaPlayer( PathService::Get(base::DIR_MODULE, &module_path) && media::InitializeMediaLibrary(module_path)); WebKit::WebRuntimeFeatures::enableGeolocation(true); // Construct and initialize an appcache system for this scope. // A new empty temp directory is created to house any cached // content during the run. Upon exit that directory is deleted. // If we can't create a tempdir, we'll use in-memory storage. if (!appcache_dir_.CreateUniqueTempDir()) { LOG(WARNING) << "Failed to create a temp dir for the appcache, " "using in-memory storage."; DCHECK(appcache_dir_.path().empty()); } SimpleAppCacheSystem::InitializeOnUIThread(appcache_dir_.path()); WebKit::WebDatabase::setObserver(&database_system_); file_system_.set_sandbox_enabled(false); #if defined(OS_WIN) // Ensure we pick up the default theme engine. SetThemeEngine(NULL); #endif } TestShellWebKitInit::~TestShellWebKitInit() { WebKit::shutdown(); } WebKit::WebClipboard* TestShellWebKitInit::clipboard() { // Mock out clipboard calls in layout test mode so that tests don't mess // with each other's copies/pastes when running in parallel. if (TestShell::layout_test_mode()) { return &mock_clipboard_; } else { return &real_clipboard_; } } WebKit::WebData TestShellWebKitInit::loadResource(const char* name) { if (!strcmp(name, "deleteButton")) { // Create a red 30x30 square. const char red_square[] = "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52" "\x00\x00\x00\x1e\x00\x00\x00\x1e\x04\x03\x00\x00\x00\xc9\x1e\xb3" "\x91\x00\x00\x00\x30\x50\x4c\x54\x45\x00\x00\x00\x80\x00\x00\x00" "\x80\x00\x80\x80\x00\x00\x00\x80\x80\x00\x80\x00\x80\x80\x80\x80" "\x80\xc0\xc0\xc0\xff\x00\x00\x00\xff\x00\xff\xff\x00\x00\x00\xff" "\xff\x00\xff\x00\xff\xff\xff\xff\xff\x7b\x1f\xb1\xc4\x00\x00\x00" "\x09\x70\x48\x59\x73\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a" "\x9c\x18\x00\x00\x00\x17\x49\x44\x41\x54\x78\x01\x63\x98\x89\x0a" "\x18\x50\xb9\x33\x47\xf9\xa8\x01\x32\xd4\xc2\x03\x00\x33\x84\x0d" "\x02\x3a\x91\xeb\xa5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60" "\x82"; return WebKit::WebData(red_square, arraysize(red_square)); } return webkit_glue::WebKitClientImpl::loadResource(name); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// /// Generic version of the x86 CPU extension detection routine. /// /// This file is for GNU & other non-Windows compilers, see 'cpu_detect_x86_win.cpp' /// for the Microsoft compiler version. /// /// Author : Copyright (c) Olli Parviainen /// Author e-mail : oparviai 'at' iki.fi /// SoundTouch WWW: http://www.surina.net/soundtouch /// //////////////////////////////////////////////////////////////////////////////// // // Last changed : $Date$ // File revision : $Revision: 4 $ // // $Id$ // //////////////////////////////////////////////////////////////////////////////// // // License : // // SoundTouch audio processing library // Copyright (c) Olli Parviainen // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //////////////////////////////////////////////////////////////////////////////// #include <stdexcept> #include <string> #include "cpu_detect.h" #include "STTypes.h" using namespace std; #include <stdio.h> ////////////////////////////////////////////////////////////////////////////// // // processor instructions extension detection routines // ////////////////////////////////////////////////////////////////////////////// // Flag variable indicating whick ISA extensions are disabled (for debugging) static uint _dwDisabledISA = 0x00; // 0xffffffff; //<- use this to disable all extensions // Disables given set of instruction extensions. See SUPPORT_... defines. void disableExtensions(uint dwDisableMask) { _dwDisabledISA = dwDisableMask; } /// Checks which instruction set extensions are supported by the CPU. uint detectCPUextensions(void) { #if (!(ALLOW_X86_OPTIMIZATIONS) || !(__GNUC__)) return 0; // always disable extensions on non-x86 platforms. #else uint res = 0; if (_dwDisabledISA == 0xffffffff) return 0; asm volatile( "\n\txor %%esi, %%esi" // clear %%esi = result register // check if 'cpuid' instructions is available by toggling eflags bit 21 "\n\tpushf" // save eflags to stack "\n\tmovl (%%esp), %%eax" // load eax from stack (with eflags) "\n\tmovl %%eax, %%ecx" // save the original eflags values to ecx "\n\txor $0x00200000, %%eax" // toggle bit 21 "\n\tmovl %%eax, (%%esp)" // store toggled eflags to stack "\n\tpopf" // load eflags from stack "\n\tpushf" // save updated eflags to stack "\n\tmovl (%%esp), %%eax" // load eax from stack "\n\tpopf" // pop stack to restore esp "\n\txor %%edx, %%edx" // clear edx for defaulting no mmx "\n\tcmp %%ecx, %%eax" // compare to original eflags values "\n\tjz end" // jumps to 'end' if cpuid not present // cpuid instruction available, test for presence of mmx instructions "\n\tmovl $1, %%eax" "\n\tcpuid" "\n\ttest $0x00800000, %%edx" "\n\tjz end" // branch if MMX not available "\n\tor $0x01, %%esi" // otherwise add MMX support bit "\n\ttest $0x02000000, %%edx" "\n\tjz test3DNow" // branch if SSE not available "\n\tor $0x08, %%esi" // otherwise add SSE support bit "\n\ttest3DNow:" // test for precense of AMD extensions "\n\tmov $0x80000000, %%eax" "\n\tcpuid" "\n\tcmp $0x80000000, %%eax" "\n\tjbe end" // branch if no AMD extensions detected // test for precense of 3DNow! extension "\n\tmov $0x80000001, %%eax" "\n\tcpuid" "\n\ttest $0x80000000, %%edx" "\n\tjz end" // branch if 3DNow! not detected "\n\tor $0x02, %%esi" // otherwise add 3DNow support bit "\n\tend:" "\n\tmov %%esi, %0" : "=r" (res) : /* no inputs */ : "%edx", "%eax", "%ecx", "%esi" ); return res & ~_dwDisabledISA; #endif } <commit_msg>Updated cpuid logic for X86_64<commit_after>//////////////////////////////////////////////////////////////////////////////// /// /// Generic version of the x86 CPU extension detection routine. /// /// This file is for GNU & other non-Windows compilers, see 'cpu_detect_x86_win.cpp' /// for the Microsoft compiler version. /// /// Author : Copyright (c) Olli Parviainen /// Author e-mail : oparviai 'at' iki.fi /// SoundTouch WWW: http://www.surina.net/soundtouch /// //////////////////////////////////////////////////////////////////////////////// // // Last changed : $Date$ // File revision : $Revision: 4 $ // // $Id$ // //////////////////////////////////////////////////////////////////////////////// // // License : // // SoundTouch audio processing library // Copyright (c) Olli Parviainen // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //////////////////////////////////////////////////////////////////////////////// #include <stdexcept> #include <string> #include "cpu_detect.h" #include "STTypes.h" using namespace std; #include <stdio.h> ////////////////////////////////////////////////////////////////////////////// // // processor instructions extension detection routines // ////////////////////////////////////////////////////////////////////////////// // Flag variable indicating whick ISA extensions are disabled (for debugging) static uint _dwDisabledISA = 0x00; // 0xffffffff; //<- use this to disable all extensions // Disables given set of instruction extensions. See SUPPORT_... defines. void disableExtensions(uint dwDisableMask) { _dwDisabledISA = dwDisableMask; } /// Checks which instruction set extensions are supported by the CPU. uint detectCPUextensions(void) { #if (!(ALLOW_X86_OPTIMIZATIONS) || !(__GNUC__)) return 0; // always disable extensions on non-x86 platforms. #else uint res = 0; if (_dwDisabledISA == 0xffffffff) return 0; asm volatile( #ifndef __x86_64__ // Check if 'cpuid' instructions is available by toggling eflags bit 21. // Skip this for x86-64 as they always have cpuid while stack manipulation // differs from 16/32bit ISA. "\n\txor %%esi, %%esi" // clear %%esi = result register "\n\tpushf" // save eflags to stack "\n\tmovl (%%esp), %%eax" // load eax from stack (with eflags) "\n\tmovl %%eax, %%ecx" // save the original eflags values to ecx "\n\txor $0x00200000, %%eax" // toggle bit 21 "\n\tmovl %%eax, (%%esp)" // store toggled eflags to stack "\n\tpopf" // load eflags from stack "\n\tpushf" // save updated eflags to stack "\n\tmovl (%%esp), %%eax" // load eax from stack "\n\tpopf" // pop stack to restore esp "\n\txor %%edx, %%edx" // clear edx for defaulting no mmx "\n\tcmp %%ecx, %%eax" // compare to original eflags values "\n\tjz end" // jumps to 'end' if cpuid not present #endif // __x86_64__ // cpuid instruction available, test for presence of mmx instructions "\n\tmovl $1, %%eax" "\n\tcpuid" "\n\ttest $0x00800000, %%edx" "\n\tjz end" // branch if MMX not available "\n\tor $0x01, %%esi" // otherwise add MMX support bit "\n\ttest $0x02000000, %%edx" "\n\tjz test3DNow" // branch if SSE not available "\n\tor $0x08, %%esi" // otherwise add SSE support bit "\n\ttest3DNow:" // test for precense of AMD extensions "\n\tmov $0x80000000, %%eax" "\n\tcpuid" "\n\tcmp $0x80000000, %%eax" "\n\tjbe end" // branch if no AMD extensions detected // test for precense of 3DNow! extension "\n\tmov $0x80000001, %%eax" "\n\tcpuid" "\n\ttest $0x80000000, %%edx" "\n\tjz end" // branch if 3DNow! not detected "\n\tor $0x02, %%esi" // otherwise add 3DNow support bit "\n\tend:" "\n\tmov %%esi, %0" : "=r" (res) : /* no inputs */ : "%edx", "%eax", "%ecx", "%esi" ); return res & ~_dwDisabledISA; #endif } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: interceptionhelper.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:20:09 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ //_______________________________________________ // my own includes #ifndef __FRAMEWORK_DISPATCH_INTERCEPTIONHELPER_HXX_ #include <dispatch/interceptionhelper.hxx> #endif //_______________________________________________ // interface includes #ifndef _COM_SUN_STAR_FRAME_XINTERCEPTORINFO_HPP_ #include <com/sun/star/frame/XInterceptorInfo.hpp> #endif //_______________________________________________ // includes of other projects #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif //_______________________________________________ // namespace namespace framework{ //_______________________________________________ // non exported const sal_Bool InterceptionHelper::m_bPreferrFirstInterceptor = sal_True; //_______________________________________________ // non exported definitions //_______________________________________________ // declarations /*----------------------------------------------------------------------------- 31.03.2003 09:02 -----------------------------------------------------------------------------*/ DEFINE_XINTERFACE_3(InterceptionHelper , OWeakObject , DIRECT_INTERFACE(css::frame::XDispatchProvider ), DIRECT_INTERFACE(css::frame::XDispatchProviderInterception), DIRECT_INTERFACE(css::lang::XEventListener )) /*----------------------------------------------------------------------------- 31.03.2003 09:02 -----------------------------------------------------------------------------*/ InterceptionHelper::InterceptionHelper(const css::uno::Reference< css::frame::XFrame >& xOwner, const css::uno::Reference< css::frame::XDispatchProvider >& xSlave) // Init baseclasses first : ThreadHelpBase(&Application::GetSolarMutex()) , OWeakObject ( ) // Init member , m_xOwnerWeak (xOwner ) , m_xSlave (xSlave ) { } /*----------------------------------------------------------------------------- 31.03.2003 09:02 -----------------------------------------------------------------------------*/ InterceptionHelper::~InterceptionHelper() { } /*----------------------------------------------------------------------------- 31.03.2003 09:09 -----------------------------------------------------------------------------*/ css::uno::Reference< css::frame::XDispatch > SAL_CALL InterceptionHelper::queryDispatch(const css::util::URL& aURL , const ::rtl::OUString& sTargetFrameName, sal_Int32 nSearchFlags ) throw(css::uno::RuntimeException) { // SAFE { ReadGuard aReadLock(m_aLock); // a) first search an interceptor, which match to this URL by it's URL pattern registration // Note: if it return NULL - it does not mean an empty interceptor list automaticly! css::uno::Reference< css::frame::XDispatchProvider > xInterceptor; InterceptorList::const_iterator pIt = m_lInterceptionRegs.findByPattern(aURL.Complete); if (pIt != m_lInterceptionRegs.end()) xInterceptor = pIt->xInterceptor; // b) No match by registration - but a valid interceptor list. // Use first interceptor everytimes. // Note: it doesn't matter, which direction this helper implementation use to ask interceptor objects. // Using of member m_aInterceptorList will starts at the beginning everytimes. // It depends from the filling operation, in which direction it works realy! if (!xInterceptor.is() && m_lInterceptionRegs.size()>0) { pIt = m_lInterceptionRegs.begin(); xInterceptor = pIt->xInterceptor; } // c) No registered interceptor => use our direct slave. // This helper exist by design and must be valid everytimes ... // But to be more feature proof - we should check that .-) if (!xInterceptor.is() && m_xSlave.is()) xInterceptor = m_xSlave; aReadLock.unlock(); // } SAFE css::uno::Reference< css::frame::XDispatch > xReturn; if (xInterceptor.is()) xReturn = xInterceptor->queryDispatch(aURL, sTargetFrameName, nSearchFlags); return xReturn; } /*----------------------------------------------------------------------------- 31.03.2003 07:58 -----------------------------------------------------------------------------*/ css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL InterceptionHelper::queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptor ) throw(css::uno::RuntimeException) { sal_Int32 c = lDescriptor.getLength(); css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > lDispatches (c); css::uno::Reference< css::frame::XDispatch >* pDispatches = lDispatches.getArray(); const css::frame::DispatchDescriptor* pDescriptor = lDescriptor.getConstArray(); for (sal_Int32 i=0; i<c; ++i) pDispatches[i] = queryDispatch(pDescriptor[i].FeatureURL, pDescriptor[i].FrameName, pDescriptor[i].SearchFlags); return lDispatches; } /*----------------------------------------------------------------------------- 31.03.2003 10:20 -----------------------------------------------------------------------------*/ void SAL_CALL InterceptionHelper::registerDispatchProviderInterceptor(const css::uno::Reference< css::frame::XDispatchProviderInterceptor >& xInterceptor) throw(css::uno::RuntimeException) { // reject wrong calling of this interface method css::uno::Reference< css::frame::XDispatchProvider > xThis(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY); if (!xInterceptor.is()) throw css::uno::RuntimeException(DECLARE_ASCII("NULL references not allowed as in parameter"), xThis); // Fill a new info structure for new interceptor. // Save his reference and try to get an additional URL/pattern list from him. // If no list exist register these interceptor for all dispatch events with "*"! InterceptorInfo aInfo; aInfo.xInterceptor = css::uno::Reference< css::frame::XDispatchProvider >(xInterceptor, css::uno::UNO_QUERY); css::uno::Reference< css::frame::XInterceptorInfo > xInfo(xInterceptor, css::uno::UNO_QUERY); if (xInfo.is()) aInfo.lURLPattern = xInfo->getInterceptedURLs(); else { aInfo.lURLPattern.realloc(1); aInfo.lURLPattern[0] = ::rtl::OUString::createFromAscii("*"); } // SAFE { WriteGuard aWriteLock(m_aLock); // a) no interceptor at all - set this instance as master for given interceptor // and set our slave as it's slave - and put this interceptor to the list. // It's place there doesn matter. Because this list is currently empty. if (m_lInterceptionRegs.size()<1) { xInterceptor->setMasterDispatchProvider(xThis ); xInterceptor->setSlaveDispatchProvider (m_xSlave); m_lInterceptionRegs.push_back(aInfo); } // b) OK - there is at least one interceptor already registered. // It's slave and it's master must be valid references ... // because we created it. But we have to look for the static bool which // regulate direction of using of interceptor objects! // b1) If "m_bPreferrFirstInterceptor" is set to true, we have to // insert it behind any other existing interceptor - means at the end of our list. else if (m_bPreferrFirstInterceptor) { css::uno::Reference< css::frame::XDispatchProvider > xMasterD = m_lInterceptionRegs.rbegin()->xInterceptor; css::uno::Reference< css::frame::XDispatchProviderInterceptor > xMasterI (xMasterD, css::uno::UNO_QUERY); xInterceptor->setMasterDispatchProvider(xMasterD ); xInterceptor->setSlaveDispatchProvider (m_xSlave ); xMasterI->setSlaveDispatchProvider (aInfo.xInterceptor); m_lInterceptionRegs.push_back(aInfo); } // b2) If "m_bPreferrFirstInterceptor" is set to false, we have to // insert it before any other existing interceptor - means at the beginning of our list. else { css::uno::Reference< css::frame::XDispatchProvider > xSlaveD = m_lInterceptionRegs.begin()->xInterceptor; css::uno::Reference< css::frame::XDispatchProviderInterceptor > xSlaveI (xSlaveD , css::uno::UNO_QUERY); xInterceptor->setMasterDispatchProvider(xThis ); xInterceptor->setSlaveDispatchProvider (xSlaveD ); xSlaveI->setMasterDispatchProvider (aInfo.xInterceptor); m_lInterceptionRegs.push_front(aInfo); } css::uno::Reference< css::frame::XFrame > xOwner(m_xOwnerWeak.get(), css::uno::UNO_QUERY); aWriteLock.unlock(); // } SAFE // Don't forget to send a frame action event "context changed". // Any cached dispatch objects must be validated now! if (xOwner.is()) xOwner->contextChanged(); } /*----------------------------------------------------------------------------- 31.03.2003 10:27 -----------------------------------------------------------------------------*/ void SAL_CALL InterceptionHelper::releaseDispatchProviderInterceptor(const css::uno::Reference< css::frame::XDispatchProviderInterceptor >& xInterceptor) throw(css::uno::RuntimeException) { // reject wrong calling of this interface method css::uno::Reference< css::frame::XDispatchProvider > xThis(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY); if (!xInterceptor.is()) throw css::uno::RuntimeException(DECLARE_ASCII("NULL references not allowed as in parameter"), xThis); // SAFE { WriteGuard aWriteLock(m_aLock); // search this interceptor ... // If it could be located inside cache - // use it's slave/master relations to update the interception list; // set empty references for it as new master and slave; // and relase it from out cache. InterceptorList::iterator pIt = m_lInterceptionRegs.findByReference(xInterceptor); if (pIt != m_lInterceptionRegs.end()) { css::uno::Reference< css::frame::XDispatchProvider > xSlaveD (xInterceptor->getSlaveDispatchProvider() , css::uno::UNO_QUERY); css::uno::Reference< css::frame::XDispatchProvider > xMasterD (xInterceptor->getMasterDispatchProvider(), css::uno::UNO_QUERY); css::uno::Reference< css::frame::XDispatchProviderInterceptor > xSlaveI (xSlaveD , css::uno::UNO_QUERY); css::uno::Reference< css::frame::XDispatchProviderInterceptor > xMasterI (xMasterD , css::uno::UNO_QUERY); if (xMasterI.is()) xMasterI->setSlaveDispatchProvider(xSlaveD); if (xSlaveI.is()) xSlaveI->setMasterDispatchProvider(xMasterD); xInterceptor->setSlaveDispatchProvider (css::uno::Reference< css::frame::XDispatchProvider >()); xInterceptor->setMasterDispatchProvider(css::uno::Reference< css::frame::XDispatchProvider >()); m_lInterceptionRegs.erase(pIt); } css::uno::Reference< css::frame::XFrame > xOwner(m_xOwnerWeak.get(), css::uno::UNO_QUERY); aWriteLock.unlock(); // } SAFE // Don't forget to send a frame action event "context changed". // Any cached dispatch objects must be validated now! if (xOwner.is()) xOwner->contextChanged(); } /*----------------------------------------------------------------------------- 31.03.2003 10:31 -----------------------------------------------------------------------------*/ void SAL_CALL InterceptionHelper::disposing(const css::lang::EventObject& aEvent) throw(css::uno::RuntimeException) { LOG_WARNING("InterceptionHelper::disposing()", "unexpected situation") } } // namespace framework <commit_msg>INTEGRATION: CWS mbapp3 (1.3.130); FILE MERGED 2006/04/24 10:19:46 as 1.3.130.1: #i64598# destruct interception chain explicitly<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: interceptionhelper.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2006-05-08 14:43:35 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ //_______________________________________________ // my own includes #ifndef __FRAMEWORK_DISPATCH_INTERCEPTIONHELPER_HXX_ #include <dispatch/interceptionhelper.hxx> #endif //_______________________________________________ // interface includes #ifndef _COM_SUN_STAR_FRAME_XINTERCEPTORINFO_HPP_ #include <com/sun/star/frame/XInterceptorInfo.hpp> #endif //_______________________________________________ // includes of other projects #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif //_______________________________________________ // namespace namespace framework{ //_______________________________________________ // non exported const sal_Bool InterceptionHelper::m_bPreferrFirstInterceptor = sal_True; //_______________________________________________ // non exported definitions //_______________________________________________ // declarations /*----------------------------------------------------------------------------- 31.03.2003 09:02 -----------------------------------------------------------------------------*/ DEFINE_XINTERFACE_3(InterceptionHelper , OWeakObject , DIRECT_INTERFACE(css::frame::XDispatchProvider ), DIRECT_INTERFACE(css::frame::XDispatchProviderInterception), DIRECT_INTERFACE(css::lang::XEventListener )) /*----------------------------------------------------------------------------- 31.03.2003 09:02 -----------------------------------------------------------------------------*/ InterceptionHelper::InterceptionHelper(const css::uno::Reference< css::frame::XFrame >& xOwner, const css::uno::Reference< css::frame::XDispatchProvider >& xSlave) // Init baseclasses first : ThreadHelpBase(&Application::GetSolarMutex()) , OWeakObject ( ) // Init member , m_xOwnerWeak (xOwner ) , m_xSlave (xSlave ) { } /*----------------------------------------------------------------------------- 31.03.2003 09:02 -----------------------------------------------------------------------------*/ InterceptionHelper::~InterceptionHelper() { } /*----------------------------------------------------------------------------- 31.03.2003 09:09 -----------------------------------------------------------------------------*/ css::uno::Reference< css::frame::XDispatch > SAL_CALL InterceptionHelper::queryDispatch(const css::util::URL& aURL , const ::rtl::OUString& sTargetFrameName, sal_Int32 nSearchFlags ) throw(css::uno::RuntimeException) { // SAFE { ReadGuard aReadLock(m_aLock); // a) first search an interceptor, which match to this URL by it's URL pattern registration // Note: if it return NULL - it does not mean an empty interceptor list automaticly! css::uno::Reference< css::frame::XDispatchProvider > xInterceptor; InterceptorList::const_iterator pIt = m_lInterceptionRegs.findByPattern(aURL.Complete); if (pIt != m_lInterceptionRegs.end()) xInterceptor = pIt->xInterceptor; // b) No match by registration - but a valid interceptor list. // Use first interceptor everytimes. // Note: it doesn't matter, which direction this helper implementation use to ask interceptor objects. // Using of member m_aInterceptorList will starts at the beginning everytimes. // It depends from the filling operation, in which direction it works realy! if (!xInterceptor.is() && m_lInterceptionRegs.size()>0) { pIt = m_lInterceptionRegs.begin(); xInterceptor = pIt->xInterceptor; } // c) No registered interceptor => use our direct slave. // This helper exist by design and must be valid everytimes ... // But to be more feature proof - we should check that .-) if (!xInterceptor.is() && m_xSlave.is()) xInterceptor = m_xSlave; aReadLock.unlock(); // } SAFE css::uno::Reference< css::frame::XDispatch > xReturn; if (xInterceptor.is()) xReturn = xInterceptor->queryDispatch(aURL, sTargetFrameName, nSearchFlags); return xReturn; } /*----------------------------------------------------------------------------- 31.03.2003 07:58 -----------------------------------------------------------------------------*/ css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL InterceptionHelper::queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptor ) throw(css::uno::RuntimeException) { sal_Int32 c = lDescriptor.getLength(); css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > lDispatches (c); css::uno::Reference< css::frame::XDispatch >* pDispatches = lDispatches.getArray(); const css::frame::DispatchDescriptor* pDescriptor = lDescriptor.getConstArray(); for (sal_Int32 i=0; i<c; ++i) pDispatches[i] = queryDispatch(pDescriptor[i].FeatureURL, pDescriptor[i].FrameName, pDescriptor[i].SearchFlags); return lDispatches; } /*----------------------------------------------------------------------------- 31.03.2003 10:20 -----------------------------------------------------------------------------*/ void SAL_CALL InterceptionHelper::registerDispatchProviderInterceptor(const css::uno::Reference< css::frame::XDispatchProviderInterceptor >& xInterceptor) throw(css::uno::RuntimeException) { // reject wrong calling of this interface method css::uno::Reference< css::frame::XDispatchProvider > xThis(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY); if (!xInterceptor.is()) throw css::uno::RuntimeException(DECLARE_ASCII("NULL references not allowed as in parameter"), xThis); // Fill a new info structure for new interceptor. // Save his reference and try to get an additional URL/pattern list from him. // If no list exist register these interceptor for all dispatch events with "*"! InterceptorInfo aInfo; aInfo.xInterceptor = css::uno::Reference< css::frame::XDispatchProvider >(xInterceptor, css::uno::UNO_QUERY); css::uno::Reference< css::frame::XInterceptorInfo > xInfo(xInterceptor, css::uno::UNO_QUERY); if (xInfo.is()) aInfo.lURLPattern = xInfo->getInterceptedURLs(); else { aInfo.lURLPattern.realloc(1); aInfo.lURLPattern[0] = ::rtl::OUString::createFromAscii("*"); } // SAFE { WriteGuard aWriteLock(m_aLock); // a) no interceptor at all - set this instance as master for given interceptor // and set our slave as it's slave - and put this interceptor to the list. // It's place there doesn matter. Because this list is currently empty. if (m_lInterceptionRegs.size()<1) { xInterceptor->setMasterDispatchProvider(xThis ); xInterceptor->setSlaveDispatchProvider (m_xSlave); m_lInterceptionRegs.push_back(aInfo); } // b) OK - there is at least one interceptor already registered. // It's slave and it's master must be valid references ... // because we created it. But we have to look for the static bool which // regulate direction of using of interceptor objects! // b1) If "m_bPreferrFirstInterceptor" is set to true, we have to // insert it behind any other existing interceptor - means at the end of our list. else if (m_bPreferrFirstInterceptor) { css::uno::Reference< css::frame::XDispatchProvider > xMasterD = m_lInterceptionRegs.rbegin()->xInterceptor; css::uno::Reference< css::frame::XDispatchProviderInterceptor > xMasterI (xMasterD, css::uno::UNO_QUERY); xInterceptor->setMasterDispatchProvider(xMasterD ); xInterceptor->setSlaveDispatchProvider (m_xSlave ); xMasterI->setSlaveDispatchProvider (aInfo.xInterceptor); m_lInterceptionRegs.push_back(aInfo); } // b2) If "m_bPreferrFirstInterceptor" is set to false, we have to // insert it before any other existing interceptor - means at the beginning of our list. else { css::uno::Reference< css::frame::XDispatchProvider > xSlaveD = m_lInterceptionRegs.begin()->xInterceptor; css::uno::Reference< css::frame::XDispatchProviderInterceptor > xSlaveI (xSlaveD , css::uno::UNO_QUERY); xInterceptor->setMasterDispatchProvider(xThis ); xInterceptor->setSlaveDispatchProvider (xSlaveD ); xSlaveI->setMasterDispatchProvider (aInfo.xInterceptor); m_lInterceptionRegs.push_front(aInfo); } css::uno::Reference< css::frame::XFrame > xOwner(m_xOwnerWeak.get(), css::uno::UNO_QUERY); aWriteLock.unlock(); // } SAFE // Don't forget to send a frame action event "context changed". // Any cached dispatch objects must be validated now! if (xOwner.is()) xOwner->contextChanged(); } /*----------------------------------------------------------------------------- 31.03.2003 10:27 -----------------------------------------------------------------------------*/ void SAL_CALL InterceptionHelper::releaseDispatchProviderInterceptor(const css::uno::Reference< css::frame::XDispatchProviderInterceptor >& xInterceptor) throw(css::uno::RuntimeException) { // reject wrong calling of this interface method css::uno::Reference< css::frame::XDispatchProvider > xThis(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY); if (!xInterceptor.is()) throw css::uno::RuntimeException(DECLARE_ASCII("NULL references not allowed as in parameter"), xThis); // SAFE { WriteGuard aWriteLock(m_aLock); // search this interceptor ... // If it could be located inside cache - // use it's slave/master relations to update the interception list; // set empty references for it as new master and slave; // and relase it from out cache. InterceptorList::iterator pIt = m_lInterceptionRegs.findByReference(xInterceptor); if (pIt != m_lInterceptionRegs.end()) { css::uno::Reference< css::frame::XDispatchProvider > xSlaveD (xInterceptor->getSlaveDispatchProvider() , css::uno::UNO_QUERY); css::uno::Reference< css::frame::XDispatchProvider > xMasterD (xInterceptor->getMasterDispatchProvider(), css::uno::UNO_QUERY); css::uno::Reference< css::frame::XDispatchProviderInterceptor > xSlaveI (xSlaveD , css::uno::UNO_QUERY); css::uno::Reference< css::frame::XDispatchProviderInterceptor > xMasterI (xMasterD , css::uno::UNO_QUERY); if (xMasterI.is()) xMasterI->setSlaveDispatchProvider(xSlaveD); if (xSlaveI.is()) xSlaveI->setMasterDispatchProvider(xMasterD); xInterceptor->setSlaveDispatchProvider (css::uno::Reference< css::frame::XDispatchProvider >()); xInterceptor->setMasterDispatchProvider(css::uno::Reference< css::frame::XDispatchProvider >()); m_lInterceptionRegs.erase(pIt); } css::uno::Reference< css::frame::XFrame > xOwner(m_xOwnerWeak.get(), css::uno::UNO_QUERY); aWriteLock.unlock(); // } SAFE // Don't forget to send a frame action event "context changed". // Any cached dispatch objects must be validated now! if (xOwner.is()) xOwner->contextChanged(); } /*----------------------------------------------------------------------------- 31.03.2003 10:31 -----------------------------------------------------------------------------*/ #define FORCE_DESTRUCTION_OF_INTERCEPTION_CHAIN void SAL_CALL InterceptionHelper::disposing(const css::lang::EventObject& aEvent) throw(css::uno::RuntimeException) { #ifdef FORCE_DESTRUCTION_OF_INTERCEPTION_CHAIN // SAFE -> ReadGuard aReadLock(m_aLock); // check calli ... we accept such disposing call's only from our onwer frame. css::uno::Reference< css::frame::XFrame > xOwner(m_xOwnerWeak.get(), css::uno::UNO_QUERY); if (aEvent.Source != xOwner) return; // Because every interceptor hold at least one reference to us ... and we destruct this list // of interception objects ... we should hold ourself alive .-) css::uno::Reference< css::frame::XDispatchProvider > xThis(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY_THROW); // We need a full copy of all currently registered interceptor objects. // Otherwhise we cant iterate over this vector without the risk, that our iterator will be invalid. // Because this vetor will be influenced by every deregistered interceptor. InterceptionHelper::InterceptorList aCopy = m_lInterceptionRegs; aReadLock.unlock(); // <- SAFE InterceptionHelper::InterceptorList::iterator pIt; for ( pIt = aCopy.begin(); pIt != aCopy.end() ; ++pIt ) { InterceptionHelper::InterceptorInfo& rInfo = *pIt; if (rInfo.xInterceptor.is()) { css::uno::Reference< css::frame::XDispatchProviderInterceptor > xInterceptor(rInfo.xInterceptor, css::uno::UNO_QUERY_THROW); releaseDispatchProviderInterceptor(xInterceptor); rInfo.xInterceptor.clear(); } } aCopy.clear(); #if OSL_DEBUG_LEVEL > 0 // SAFE -> aReadLock.lock(); if (m_lInterceptionRegs.size() > 0) OSL_ENSURE(sal_False, "There are some pending interceptor objects, which seams to be registered during (!) the destruction of a frame."); aReadLock.unlock(); // <- SAFE #endif // ODL_DEBUG_LEVEL>0 #endif // FORCE_DESTRUCTION_OF_INTERCEPTION_CHAIN } } // namespace framework <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/system_wrappers/include/logging.h" #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/base/scoped_ptr.h" #include "webrtc/system_wrappers/include/condition_variable_wrapper.h" #include "webrtc/system_wrappers/include/critical_section_wrapper.h" #include "webrtc/system_wrappers/include/sleep.h" #include "webrtc/system_wrappers/include/trace.h" namespace webrtc { namespace { class LoggingTest : public ::testing::Test, public TraceCallback { public: virtual void Print(TraceLevel level, const char* msg, int length) { CriticalSectionScoped cs(crit_.get()); // We test the length here to ensure (with high likelihood) that only our // traces will be tested. if (level_ != kTraceNone && static_cast<int>(expected_log_.str().size()) == length - Trace::kBoilerplateLength - 1) { EXPECT_EQ(level_, level); EXPECT_EQ(expected_log_.str(), &msg[Trace::kBoilerplateLength]); level_ = kTraceNone; cv_->Wake(); } } protected: LoggingTest() : crit_(CriticalSectionWrapper::CreateCriticalSection()), cv_(ConditionVariableWrapper::CreateConditionVariable()), level_(kTraceNone), expected_log_() { } void SetUp() { Trace::CreateTrace(); Trace::SetTraceCallback(this); } void TearDown() { Trace::SetTraceCallback(NULL); Trace::ReturnTrace(); CriticalSectionScoped cs(crit_.get()); ASSERT_EQ(kTraceNone, level_) << "Print() was not called"; } rtc::scoped_ptr<CriticalSectionWrapper> crit_; rtc::scoped_ptr<ConditionVariableWrapper> cv_; TraceLevel level_ GUARDED_BY(crit_); std::ostringstream expected_log_ GUARDED_BY(crit_); }; TEST_F(LoggingTest, LogStream) { { CriticalSectionScoped cs(crit_.get()); level_ = kTraceWarning; std::string msg = "Important message"; expected_log_ << "(logging_unittest.cc:" << __LINE__ + 1 << "): " << msg; LOG(LS_WARNING) << msg; cv_->SleepCS(*crit_.get(), 2000); } } } // namespace } // namespace webrtc <commit_msg>Simplify the implementation of LoggingTest. This removes dependency on ConditionVariableWrapper and CriticalSectionWrapper which currently have a 'friend' relationship that I'd like to get rid of.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/system_wrappers/include/logging.h" #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/base/arraysize.h" #include "webrtc/base/event.h" #include "webrtc/base/scoped_ptr.h" #include "webrtc/system_wrappers/include/trace.h" namespace webrtc { namespace { const char kTestLogString[] = "Incredibly important test message!(?)"; const int kTestLevel = kTraceWarning; class LoggingTestCallback : public TraceCallback { public: LoggingTestCallback(rtc::Event* event) : event_(event) {} private: void Print(TraceLevel level, const char* msg, int length) override { if (static_cast<size_t>(length) < arraysize(kTestLogString) || level != kTestLevel) { return; } std::string msg_str(msg, length); if (msg_str.find(kTestLogString) != std::string::npos) event_->Set(); } rtc::Event* const event_; }; } // namespace TEST(LoggingTest, LogStream) { Trace::CreateTrace(); rtc::Event event(false, false); LoggingTestCallback callback(&event); Trace::SetTraceCallback(&callback); LOG(LS_WARNING) << kTestLogString; EXPECT_TRUE(event.Wait(2000)); Trace::SetTraceCallback(nullptr); Trace::ReturnTrace(); } } // namespace webrtc <|endoftext|>
<commit_before>/* * Copyright (c) 2011-2012 Stephen Williams ([email protected]) * Copyright (c) 2014 CERN / Maciej Suminski ([email protected]) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ # include "vtype.h" # include "expression.h" # include <sstream> # include <typeinfo> # include <cassert> using namespace std; int VType::decl_t::emit(ostream&out, perm_string name) const { return type->emit_decl(out, name, reg_flag); } int VType::emit_decl(ostream&out, perm_string name, bool reg_flag) const { int errors = 0; if (!reg_flag) out << "wire "; errors += emit_def(out, name); out << " "; return errors; } int VType::emit_typedef(std::ostream&, typedef_context_t&) const { return 0; } int VTypeERROR::emit_def(ostream&out, perm_string) const { out << "/* ERROR */"; return 1; } int VTypeArray::emit_def(ostream&out, perm_string name) const { int errors = 0; const VTypeArray*cur = this; while (const VTypeArray*sub = dynamic_cast<const VTypeArray*> (cur->etype_)) { cur = sub; } const VType*raw_base = cur->etype_; const VTypePrimitive*base = dynamic_cast<const VTypePrimitive*> (raw_base); stringstream buf; if (base) { assert(dimensions() == 1); base->emit_def(buf, empty_perm_string); if (signed_flag_) buf << " signed"; } else { raw_base->emit_def(buf, empty_perm_string); } string tmp(buf.str()); out << tmp.substr(0, tmp.length() - 2); // drop the empty type name (\ ) if(raw_base->can_be_packed()) { errors += emit_dimensions(out); out << " \\" << name; } else { out << "\\" << name << " "; errors += emit_dimensions(out); } return errors; } int VTypeArray::emit_typedef(std::ostream&out, typedef_context_t&ctx) const { return etype_->emit_typedef(out, ctx); } int VTypeArray::emit_dimensions(std::ostream&out) const { int errors = 0; list<const VTypeArray*> dims; const VTypeArray*cur = this; while (const VTypeArray*sub = dynamic_cast<const VTypeArray*> (cur->etype_)) { dims.push_back(cur); cur = sub; } dims.push_back(cur); while (! dims.empty()) { cur = dims.front(); dims.pop_front(); out << "["; if (cur->dimension(0).msb() && cur->dimension(0).lsb()) { // bounded array, unbounded arrays have msb() & lsb() nullified errors += cur->dimension(0).msb()->emit(out, 0, 0); out << ":"; errors += cur->dimension(0).lsb()->emit(out, 0, 0); } out << "]"; } return errors; } int VTypeEnum::emit_def(ostream&out, perm_string name) const { int errors = 0; out << "enum {"; assert(names_.size() >= 1); out << "\\" << names_[0] << " "; for (size_t idx = 1 ; idx < names_.size() ; idx += 1) out << ", \\" << names_[idx] << " "; out << "} \\" << name << " "; return errors; } int VTypePrimitive::emit_primitive_type(ostream&out) const { int errors = 0; switch (type_) { case BOOLEAN: case BIT: out << "bool"; break; case STDLOGIC: out << "logic"; break; case INTEGER: out << "bool [31:0]"; break; case REAL: out << "real"; break; case CHARACTER: out << "char"; break; default: assert(0); break; } return errors; } int VTypePrimitive::emit_def(ostream&out, perm_string name) const { int errors = 0; errors += emit_primitive_type(out); out << " \\" << name << " "; return errors; } int VTypeRange::emit_def(ostream&out, perm_string name) const { int errors = 0; out << "/* Internal error: Don't know how to emit range */"; errors += base_->emit_def(out, name); return errors; } int VTypeRecord::emit_def(ostream&out, perm_string name) const { int errors = 0; out << "struct packed {"; for (vector<element_t*>::const_iterator cur = elements_.begin() ; cur != elements_.end() ; ++cur) { perm_string element_name = (*cur)->peek_name(); const VType*element_type = (*cur)->peek_type(); element_type->emit_def(out, empty_perm_string); out << " \\" << element_name << " ; "; } out << "} \\ " << name << " "; return errors; } /* * For VTypeDef objects, use the name of the defined type as the * type. (We are defining a variable here, not the type itself.) The * emit_typedef() method was presumably called to define type already. */ int VTypeDef::emit_def(ostream&out, perm_string) const { int errors = 0; out << "\\" << name_ << " "; return errors; } int VTypeDef::emit_decl(ostream&out, perm_string name, bool reg_flag) const { int errors = 0; if (reg_flag) out << "reg "; else out << "wire "; errors += type_->emit_def(out, name); out << " \\" << name << " "; return errors; } int VTypeDef::emit_typedef(ostream&out, typedef_context_t&ctx) const { // The typedef_context_t is used by me to determine if this // typedef has already been emitted in this architecture. If // it has, then it is MARKED, give up. Otherwise, recurse the // emit_typedef to make sure all sub-types that I use have // been emitted, then emit my typedef. typedef_topo_t&flag = ctx[this]; switch (flag) { case MARKED: return 0; case PENDING: out << "typedef \\" << name_ << " ; /* typedef cycle? */" << endl; return 0; case NONE: break; } flag = PENDING; int errors = type_->emit_typedef(out, ctx); flag = MARKED; // Array types are used directly anyway and typedefs for unpacked // arrays do not work currently if(dynamic_cast<const VTypeArray*>(type_)) out << "// "; out << "typedef "; errors += type_->emit_def(out, name_); out << " ;" << endl; return errors; } <commit_msg>vhdlpp: 'integer' is emitted as 'integer' instead of 'bool [31:0]'.<commit_after>/* * Copyright (c) 2011-2012 Stephen Williams ([email protected]) * Copyright (c) 2014 CERN / Maciej Suminski ([email protected]) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ # include "vtype.h" # include "expression.h" # include <sstream> # include <typeinfo> # include <cassert> using namespace std; int VType::decl_t::emit(ostream&out, perm_string name) const { return type->emit_decl(out, name, reg_flag); } int VType::emit_decl(ostream&out, perm_string name, bool reg_flag) const { int errors = 0; if (!reg_flag) out << "wire "; errors += emit_def(out, name); out << " "; return errors; } int VType::emit_typedef(std::ostream&, typedef_context_t&) const { return 0; } int VTypeERROR::emit_def(ostream&out, perm_string) const { out << "/* ERROR */"; return 1; } int VTypeArray::emit_def(ostream&out, perm_string name) const { int errors = 0; const VTypeArray*cur = this; while (const VTypeArray*sub = dynamic_cast<const VTypeArray*> (cur->etype_)) { cur = sub; } const VType*raw_base = cur->etype_; const VTypePrimitive*base = dynamic_cast<const VTypePrimitive*> (raw_base); stringstream buf; if (base) { assert(dimensions() == 1); base->emit_def(buf, empty_perm_string); if (signed_flag_) buf << " signed"; } else { raw_base->emit_def(buf, empty_perm_string); } string tmp(buf.str()); out << tmp.substr(0, tmp.length() - 2); // drop the empty type name (\ ) if(raw_base->can_be_packed()) { errors += emit_dimensions(out); out << " \\" << name; } else { out << "\\" << name << " "; errors += emit_dimensions(out); } return errors; } int VTypeArray::emit_typedef(std::ostream&out, typedef_context_t&ctx) const { return etype_->emit_typedef(out, ctx); } int VTypeArray::emit_dimensions(std::ostream&out) const { int errors = 0; list<const VTypeArray*> dims; const VTypeArray*cur = this; while (const VTypeArray*sub = dynamic_cast<const VTypeArray*> (cur->etype_)) { dims.push_back(cur); cur = sub; } dims.push_back(cur); while (! dims.empty()) { cur = dims.front(); dims.pop_front(); out << "["; if (cur->dimension(0).msb() && cur->dimension(0).lsb()) { // bounded array, unbounded arrays have msb() & lsb() nullified errors += cur->dimension(0).msb()->emit(out, 0, 0); out << ":"; errors += cur->dimension(0).lsb()->emit(out, 0, 0); } out << "]"; } return errors; } int VTypeEnum::emit_def(ostream&out, perm_string name) const { int errors = 0; out << "enum {"; assert(names_.size() >= 1); out << "\\" << names_[0] << " "; for (size_t idx = 1 ; idx < names_.size() ; idx += 1) out << ", \\" << names_[idx] << " "; out << "} \\" << name << " "; return errors; } int VTypePrimitive::emit_primitive_type(ostream&out) const { int errors = 0; switch (type_) { case BOOLEAN: case BIT: out << "bool"; break; case STDLOGIC: out << "logic"; break; case INTEGER: out << "integer"; break; case REAL: out << "real"; break; case CHARACTER: out << "char"; break; default: assert(0); break; } return errors; } int VTypePrimitive::emit_def(ostream&out, perm_string name) const { int errors = 0; errors += emit_primitive_type(out); out << " \\" << name << " "; return errors; } int VTypeRange::emit_def(ostream&out, perm_string name) const { int errors = 0; out << "/* Internal error: Don't know how to emit range */"; errors += base_->emit_def(out, name); return errors; } int VTypeRecord::emit_def(ostream&out, perm_string name) const { int errors = 0; out << "struct packed {"; for (vector<element_t*>::const_iterator cur = elements_.begin() ; cur != elements_.end() ; ++cur) { perm_string element_name = (*cur)->peek_name(); const VType*element_type = (*cur)->peek_type(); element_type->emit_def(out, empty_perm_string); out << " \\" << element_name << " ; "; } out << "} \\ " << name << " "; return errors; } /* * For VTypeDef objects, use the name of the defined type as the * type. (We are defining a variable here, not the type itself.) The * emit_typedef() method was presumably called to define type already. */ int VTypeDef::emit_def(ostream&out, perm_string) const { int errors = 0; out << "\\" << name_ << " "; return errors; } int VTypeDef::emit_decl(ostream&out, perm_string name, bool reg_flag) const { int errors = 0; if (reg_flag) out << "reg "; else out << "wire "; errors += type_->emit_def(out, name); out << " \\" << name << " "; return errors; } int VTypeDef::emit_typedef(ostream&out, typedef_context_t&ctx) const { // The typedef_context_t is used by me to determine if this // typedef has already been emitted in this architecture. If // it has, then it is MARKED, give up. Otherwise, recurse the // emit_typedef to make sure all sub-types that I use have // been emitted, then emit my typedef. typedef_topo_t&flag = ctx[this]; switch (flag) { case MARKED: return 0; case PENDING: out << "typedef \\" << name_ << " ; /* typedef cycle? */" << endl; return 0; case NONE: break; } flag = PENDING; int errors = type_->emit_typedef(out, ctx); flag = MARKED; // Array types are used directly anyway and typedefs for unpacked // arrays do not work currently if(dynamic_cast<const VTypeArray*>(type_)) out << "// "; out << "typedef "; errors += type_->emit_def(out, name_); out << " ;" << endl; return errors; } <|endoftext|>
<commit_before>//===- lib/MC/MCMachOStreamer.cpp - Mach-O Object Output ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCAssembler.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCSection.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/ErrorHandling.h" using namespace llvm; namespace { class MCMachOStreamer : public MCStreamer { /// SymbolFlags - We store the value for the 'desc' symbol field in the lowest /// 16 bits of the implementation defined flags. enum SymbolFlags { // See <mach-o/nlist.h>. SF_DescFlagsMask = 0xFFFF, // Reference type flags. SF_ReferenceTypeMask = 0x0007, SF_ReferenceTypeUndefinedNonLazy = 0x0000, SF_ReferenceTypeUndefinedLazy = 0x0001, SF_ReferenceTypeDefined = 0x0002, SF_ReferenceTypePrivateDefined = 0x0003, SF_ReferenceTypePrivateUndefinedNonLazy = 0x0004, SF_ReferenceTypePrivateUndefinedLazy = 0x0005, // Other 'desc' flags. SF_NoDeadStrip = 0x0020, SF_WeakReference = 0x0040, SF_WeakDefinition = 0x0080 }; private: MCAssembler Assembler; MCSectionData *CurSectionData; DenseMap<const MCSection*, MCSectionData*> SectionMap; DenseMap<const MCSymbol*, MCSymbolData*> SymbolMap; private: MCFragment *getCurrentFragment() const { assert(CurSectionData && "No current section!"); if (!CurSectionData->empty()) return &CurSectionData->getFragmentList().back(); return 0; } MCSymbolData &getSymbolData(MCSymbol &Symbol) { MCSymbolData *&Entry = SymbolMap[&Symbol]; if (!Entry) Entry = new MCSymbolData(Symbol, 0, 0, &Assembler); return *Entry; } public: MCMachOStreamer(MCContext &Context, raw_ostream &_OS) : MCStreamer(Context), Assembler(_OS), CurSectionData(0) {} ~MCMachOStreamer() {} /// @name MCStreamer Interface /// @{ virtual void SwitchSection(const MCSection *Section); virtual void EmitLabel(MCSymbol *Symbol); virtual void EmitAssemblerFlag(AssemblerFlag Flag); virtual void EmitAssignment(MCSymbol *Symbol, const MCValue &Value, bool MakeAbsolute = false); virtual void EmitSymbolAttribute(MCSymbol *Symbol, SymbolAttr Attribute); virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue); virtual void EmitLocalSymbol(MCSymbol *Symbol, const MCValue &Value); virtual void EmitCommonSymbol(MCSymbol *Symbol, unsigned Size, unsigned Pow2Alignment, bool IsLocal); virtual void EmitZerofill(MCSection *Section, MCSymbol *Symbol = NULL, unsigned Size = 0, unsigned Pow2Alignment = 0); virtual void EmitBytes(const StringRef &Data); virtual void EmitValue(const MCValue &Value, unsigned Size); virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0, unsigned ValueSize = 1, unsigned MaxBytesToEmit = 0); virtual void EmitValueToOffset(const MCValue &Offset, unsigned char Value = 0); virtual void EmitInstruction(const MCInst &Inst); virtual void Finish(); /// @} }; } // end anonymous namespace. void MCMachOStreamer::SwitchSection(const MCSection *Section) { assert(Section && "Cannot switch to a null section!"); // If already in this section, then this is a noop. if (Section == CurSection) return; CurSection = Section; MCSectionData *&Entry = SectionMap[Section]; if (!Entry) Entry = new MCSectionData(*Section, &Assembler); CurSectionData = Entry; } void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) { assert(Symbol->isUndefined() && "Cannot define a symbol twice!"); // FIXME: We should also use offsets into Fill fragments. MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment()); if (!F) F = new MCDataFragment(CurSectionData); MCSymbolData &SD = getSymbolData(*Symbol); assert(!SD.getFragment() && "Unexpected fragment on symbol data!"); SD.setFragment(F); SD.setOffset(F->getContents().size()); // This causes the reference type and weak reference flags to be cleared. SD.setFlags(SD.getFlags() & ~(SF_WeakReference | SF_ReferenceTypeMask)); Symbol->setSection(*CurSection); } void MCMachOStreamer::EmitAssemblerFlag(AssemblerFlag Flag) { llvm_unreachable("FIXME: Not yet implemented!"); } void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCValue &Value, bool MakeAbsolute) { // Only absolute symbols can be redefined. assert((Symbol->isUndefined() || Symbol->isAbsolute()) && "Cannot define a symbol twice!"); llvm_unreachable("FIXME: Not yet implemented!"); } void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol, SymbolAttr Attribute) { // Indirect symbols are handled differently, to match how 'as' handles // them. This makes writing matching .o files easier. if (Attribute == MCStreamer::IndirectSymbol) { // Note that we intentionally cannot use the symbol data here; this is // important for matching the string table that 'as' generates. IndirectSymbolData ISD; ISD.Symbol = Symbol; ISD.SectionData = CurSectionData; Assembler.getIndirectSymbols().push_back(ISD); return; } // Adding a symbol attribute always introduces the symbol, note that an // important side effect of calling getSymbolData here is to register the // symbol with the assembler. MCSymbolData &SD = getSymbolData(*Symbol); // The implementation of symbol attributes is designed to match 'as', but it // leaves much to desired. It doesn't really make sense to arbitrarily add and // remove flags, but 'as' allows this (in particular, see .desc). // // In the future it might be worth trying to make these operations more well // defined. switch (Attribute) { case MCStreamer::IndirectSymbol: case MCStreamer::Hidden: case MCStreamer::Internal: case MCStreamer::Protected: case MCStreamer::Weak: assert(0 && "Invalid symbol attribute for Mach-O!"); break; case MCStreamer::Global: getSymbolData(*Symbol).setExternal(true); break; case MCStreamer::LazyReference: // FIXME: This requires -dynamic. SD.setFlags(SD.getFlags() | SF_NoDeadStrip); if (Symbol->isUndefined()) SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy); break; // Since .reference sets the no dead strip bit, it is equivalent to // .no_dead_strip in practice. case MCStreamer::Reference: case MCStreamer::NoDeadStrip: SD.setFlags(SD.getFlags() | SF_NoDeadStrip); break; case MCStreamer::PrivateExtern: SD.setExternal(true); SD.setPrivateExtern(true); break; case MCStreamer::WeakReference: // FIXME: This requires -dynamic. if (Symbol->isUndefined()) SD.setFlags(SD.getFlags() | SF_WeakReference); break; case MCStreamer::WeakDefinition: // FIXME: 'as' enforces that this is defined and global. The manual claims // it has to be in a coalesced section, but this isn't enforced. SD.setFlags(SD.getFlags() | SF_WeakDefinition); break; } } void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) { // Encode the 'desc' value into the lowest implementation defined bits. assert(DescValue == (DescValue & SF_DescFlagsMask) && "Invalid .desc value!"); getSymbolData(*Symbol).setFlags(DescValue & SF_DescFlagsMask); } void MCMachOStreamer::EmitLocalSymbol(MCSymbol *Symbol, const MCValue &Value) { llvm_unreachable("FIXME: Not yet implemented!"); } void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, unsigned Size, unsigned Pow2Alignment, bool IsLocal) { llvm_unreachable("FIXME: Not yet implemented!"); } void MCMachOStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol, unsigned Size, unsigned Pow2Alignment) { llvm_unreachable("FIXME: Not yet implemented!"); } void MCMachOStreamer::EmitBytes(const StringRef &Data) { MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment()); if (!DF) DF = new MCDataFragment(CurSectionData); DF->getContents().append(Data.begin(), Data.end()); } void MCMachOStreamer::EmitValue(const MCValue &Value, unsigned Size) { new MCFillFragment(Value, Size, 1, CurSectionData); } void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value, unsigned ValueSize, unsigned MaxBytesToEmit) { if (MaxBytesToEmit == 0) MaxBytesToEmit = ByteAlignment; new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit, CurSectionData); // Update the maximum alignment on the current section if necessary. if (ByteAlignment > CurSectionData->getAlignment()) CurSectionData->setAlignment(ByteAlignment); } void MCMachOStreamer::EmitValueToOffset(const MCValue &Offset, unsigned char Value) { new MCOrgFragment(Offset, Value, CurSectionData); } void MCMachOStreamer::EmitInstruction(const MCInst &Inst) { llvm_unreachable("FIXME: Not yet implemented!"); } void MCMachOStreamer::Finish() { Assembler.Finish(); } MCStreamer *llvm::createMachOStreamer(MCContext &Context, raw_ostream &OS) { return new MCMachOStreamer(Context, OS); } <commit_msg>llvm-mc: Add symbol entries for undefined symbols used in .fill and .org.<commit_after>//===- lib/MC/MCMachOStreamer.cpp - Mach-O Object Output ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCAssembler.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCSection.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/ErrorHandling.h" using namespace llvm; namespace { class MCMachOStreamer : public MCStreamer { /// SymbolFlags - We store the value for the 'desc' symbol field in the lowest /// 16 bits of the implementation defined flags. enum SymbolFlags { // See <mach-o/nlist.h>. SF_DescFlagsMask = 0xFFFF, // Reference type flags. SF_ReferenceTypeMask = 0x0007, SF_ReferenceTypeUndefinedNonLazy = 0x0000, SF_ReferenceTypeUndefinedLazy = 0x0001, SF_ReferenceTypeDefined = 0x0002, SF_ReferenceTypePrivateDefined = 0x0003, SF_ReferenceTypePrivateUndefinedNonLazy = 0x0004, SF_ReferenceTypePrivateUndefinedLazy = 0x0005, // Other 'desc' flags. SF_NoDeadStrip = 0x0020, SF_WeakReference = 0x0040, SF_WeakDefinition = 0x0080 }; private: MCAssembler Assembler; MCSectionData *CurSectionData; DenseMap<const MCSection*, MCSectionData*> SectionMap; DenseMap<const MCSymbol*, MCSymbolData*> SymbolMap; private: MCFragment *getCurrentFragment() const { assert(CurSectionData && "No current section!"); if (!CurSectionData->empty()) return &CurSectionData->getFragmentList().back(); return 0; } MCSymbolData &getSymbolData(MCSymbol &Symbol) { MCSymbolData *&Entry = SymbolMap[&Symbol]; if (!Entry) Entry = new MCSymbolData(Symbol, 0, 0, &Assembler); return *Entry; } public: MCMachOStreamer(MCContext &Context, raw_ostream &_OS) : MCStreamer(Context), Assembler(_OS), CurSectionData(0) {} ~MCMachOStreamer() {} const MCValue &AddValueSymbols(const MCValue &Value) { if (Value.getSymA()) getSymbolData(*const_cast<MCSymbol*>(Value.getSymA())); if (Value.getSymB()) getSymbolData(*const_cast<MCSymbol*>(Value.getSymB())); return Value; } /// @name MCStreamer Interface /// @{ virtual void SwitchSection(const MCSection *Section); virtual void EmitLabel(MCSymbol *Symbol); virtual void EmitAssemblerFlag(AssemblerFlag Flag); virtual void EmitAssignment(MCSymbol *Symbol, const MCValue &Value, bool MakeAbsolute = false); virtual void EmitSymbolAttribute(MCSymbol *Symbol, SymbolAttr Attribute); virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue); virtual void EmitLocalSymbol(MCSymbol *Symbol, const MCValue &Value); virtual void EmitCommonSymbol(MCSymbol *Symbol, unsigned Size, unsigned Pow2Alignment, bool IsLocal); virtual void EmitZerofill(MCSection *Section, MCSymbol *Symbol = NULL, unsigned Size = 0, unsigned Pow2Alignment = 0); virtual void EmitBytes(const StringRef &Data); virtual void EmitValue(const MCValue &Value, unsigned Size); virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0, unsigned ValueSize = 1, unsigned MaxBytesToEmit = 0); virtual void EmitValueToOffset(const MCValue &Offset, unsigned char Value = 0); virtual void EmitInstruction(const MCInst &Inst); virtual void Finish(); /// @} }; } // end anonymous namespace. void MCMachOStreamer::SwitchSection(const MCSection *Section) { assert(Section && "Cannot switch to a null section!"); // If already in this section, then this is a noop. if (Section == CurSection) return; CurSection = Section; MCSectionData *&Entry = SectionMap[Section]; if (!Entry) Entry = new MCSectionData(*Section, &Assembler); CurSectionData = Entry; } void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) { assert(Symbol->isUndefined() && "Cannot define a symbol twice!"); // FIXME: We should also use offsets into Fill fragments. MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment()); if (!F) F = new MCDataFragment(CurSectionData); MCSymbolData &SD = getSymbolData(*Symbol); assert(!SD.getFragment() && "Unexpected fragment on symbol data!"); SD.setFragment(F); SD.setOffset(F->getContents().size()); // This causes the reference type and weak reference flags to be cleared. SD.setFlags(SD.getFlags() & ~(SF_WeakReference | SF_ReferenceTypeMask)); Symbol->setSection(*CurSection); } void MCMachOStreamer::EmitAssemblerFlag(AssemblerFlag Flag) { llvm_unreachable("FIXME: Not yet implemented!"); } void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCValue &Value, bool MakeAbsolute) { // Only absolute symbols can be redefined. assert((Symbol->isUndefined() || Symbol->isAbsolute()) && "Cannot define a symbol twice!"); llvm_unreachable("FIXME: Not yet implemented!"); } void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol, SymbolAttr Attribute) { // Indirect symbols are handled differently, to match how 'as' handles // them. This makes writing matching .o files easier. if (Attribute == MCStreamer::IndirectSymbol) { // Note that we intentionally cannot use the symbol data here; this is // important for matching the string table that 'as' generates. IndirectSymbolData ISD; ISD.Symbol = Symbol; ISD.SectionData = CurSectionData; Assembler.getIndirectSymbols().push_back(ISD); return; } // Adding a symbol attribute always introduces the symbol, note that an // important side effect of calling getSymbolData here is to register the // symbol with the assembler. MCSymbolData &SD = getSymbolData(*Symbol); // The implementation of symbol attributes is designed to match 'as', but it // leaves much to desired. It doesn't really make sense to arbitrarily add and // remove flags, but 'as' allows this (in particular, see .desc). // // In the future it might be worth trying to make these operations more well // defined. switch (Attribute) { case MCStreamer::IndirectSymbol: case MCStreamer::Hidden: case MCStreamer::Internal: case MCStreamer::Protected: case MCStreamer::Weak: assert(0 && "Invalid symbol attribute for Mach-O!"); break; case MCStreamer::Global: getSymbolData(*Symbol).setExternal(true); break; case MCStreamer::LazyReference: // FIXME: This requires -dynamic. SD.setFlags(SD.getFlags() | SF_NoDeadStrip); if (Symbol->isUndefined()) SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy); break; // Since .reference sets the no dead strip bit, it is equivalent to // .no_dead_strip in practice. case MCStreamer::Reference: case MCStreamer::NoDeadStrip: SD.setFlags(SD.getFlags() | SF_NoDeadStrip); break; case MCStreamer::PrivateExtern: SD.setExternal(true); SD.setPrivateExtern(true); break; case MCStreamer::WeakReference: // FIXME: This requires -dynamic. if (Symbol->isUndefined()) SD.setFlags(SD.getFlags() | SF_WeakReference); break; case MCStreamer::WeakDefinition: // FIXME: 'as' enforces that this is defined and global. The manual claims // it has to be in a coalesced section, but this isn't enforced. SD.setFlags(SD.getFlags() | SF_WeakDefinition); break; } } void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) { // Encode the 'desc' value into the lowest implementation defined bits. assert(DescValue == (DescValue & SF_DescFlagsMask) && "Invalid .desc value!"); getSymbolData(*Symbol).setFlags(DescValue & SF_DescFlagsMask); } void MCMachOStreamer::EmitLocalSymbol(MCSymbol *Symbol, const MCValue &Value) { llvm_unreachable("FIXME: Not yet implemented!"); } void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, unsigned Size, unsigned Pow2Alignment, bool IsLocal) { llvm_unreachable("FIXME: Not yet implemented!"); } void MCMachOStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol, unsigned Size, unsigned Pow2Alignment) { llvm_unreachable("FIXME: Not yet implemented!"); } void MCMachOStreamer::EmitBytes(const StringRef &Data) { MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment()); if (!DF) DF = new MCDataFragment(CurSectionData); DF->getContents().append(Data.begin(), Data.end()); } void MCMachOStreamer::EmitValue(const MCValue &Value, unsigned Size) { new MCFillFragment(AddValueSymbols(Value), Size, 1, CurSectionData); } void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value, unsigned ValueSize, unsigned MaxBytesToEmit) { if (MaxBytesToEmit == 0) MaxBytesToEmit = ByteAlignment; new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit, CurSectionData); // Update the maximum alignment on the current section if necessary. if (ByteAlignment > CurSectionData->getAlignment()) CurSectionData->setAlignment(ByteAlignment); } void MCMachOStreamer::EmitValueToOffset(const MCValue &Offset, unsigned char Value) { new MCOrgFragment(AddValueSymbols(Offset), Value, CurSectionData); } void MCMachOStreamer::EmitInstruction(const MCInst &Inst) { llvm_unreachable("FIXME: Not yet implemented!"); } void MCMachOStreamer::Finish() { Assembler.Finish(); } MCStreamer *llvm::createMachOStreamer(MCContext &Context, raw_ostream &OS) { return new MCMachOStreamer(Context, OS); } <|endoftext|>
<commit_before>// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include <NDK/Canvas.hpp> #include <Nazara/Platform/Cursor.hpp> namespace Ndk { inline Canvas::Canvas(WorldHandle world, Nz::EventHandler& eventHandler, Nz::CursorControllerHandle cursorController) : m_keyboardOwner(InvalidCanvasIndex), m_hoveredWidget(InvalidCanvasIndex), m_cursorController(cursorController), m_world(std::move(world)) { m_canvas = this; m_widgetParent = nullptr; // Register ourselves as a widget to handle cursor change RegisterToCanvas(); // Connect to every meaningful event m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, this, &Canvas::OnEventKeyPressed); m_keyReleasedSlot.Connect(eventHandler.OnKeyReleased, this, &Canvas::OnEventKeyReleased); m_mouseButtonPressedSlot.Connect(eventHandler.OnMouseButtonPressed, this, &Canvas::OnEventMouseButtonPressed); m_mouseButtonReleasedSlot.Connect(eventHandler.OnMouseButtonReleased, this, &Canvas::OnEventMouseButtonRelease); m_mouseMovedSlot.Connect(eventHandler.OnMouseMoved, this, &Canvas::OnEventMouseMoved); m_mouseLeftSlot.Connect(eventHandler.OnMouseLeft, this, &Canvas::OnEventMouseLeft); m_textEnteredSlot.Connect(eventHandler.OnTextEntered, this, &Canvas::OnEventTextEntered); // Disable padding by default SetPadding(0.f, 0.f, 0.f, 0.f); } inline Canvas::~Canvas() { // Destroy children explicitly because they signal us when getting destroyed, and that can't happen after our own destruction DestroyChildren(); // Prevent our parent from trying to call us m_canvasIndex = InvalidCanvasIndex; } inline const WorldHandle& Canvas::GetWorld() const { return m_world; } inline void Canvas::ClearKeyboardOwner(std::size_t canvasIndex) { if (m_keyboardOwner == canvasIndex) SetKeyboardOwner(InvalidCanvasIndex); } inline bool Canvas::IsKeyboardOwner(std::size_t canvasIndex) const { return m_keyboardOwner == canvasIndex; } inline void Canvas::NotifyWidgetBoxUpdate(std::size_t index) { WidgetBox& entry = m_widgetBoxes[index]; Nz::Vector3f pos = entry.widget->GetPosition(); Nz::Vector2f size = entry.widget->GetContentSize(); entry.box.Set(pos.x, pos.y, pos.z, size.x, size.y, 1.f); } inline void Canvas::NotifyWidgetCursorUpdate(std::size_t index) { WidgetBox& entry = m_widgetBoxes[index]; entry.cursor = entry.widget->GetCursor(); if (m_cursorController && m_hoveredWidget == index) m_cursorController->UpdateCursor(Nz::Cursor::Get(entry.cursor)); } inline void Canvas::SetKeyboardOwner(std::size_t canvasIndex) { if (m_keyboardOwner != InvalidCanvasIndex) m_widgetBoxes[m_keyboardOwner].widget->OnFocusLost(); m_keyboardOwner = canvasIndex; if (m_keyboardOwner != InvalidCanvasIndex) m_widgetBoxes[m_keyboardOwner].widget->OnFocusReceived(); } } <commit_msg>Sdk/Canvas: Prevent OnFocusLost/OnFocusReceived when using SetFocus on an already focused widget<commit_after>// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include <NDK/Canvas.hpp> #include <Nazara/Platform/Cursor.hpp> namespace Ndk { inline Canvas::Canvas(WorldHandle world, Nz::EventHandler& eventHandler, Nz::CursorControllerHandle cursorController) : m_keyboardOwner(InvalidCanvasIndex), m_hoveredWidget(InvalidCanvasIndex), m_cursorController(cursorController), m_world(std::move(world)) { m_canvas = this; m_widgetParent = nullptr; // Register ourselves as a widget to handle cursor change RegisterToCanvas(); // Connect to every meaningful event m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, this, &Canvas::OnEventKeyPressed); m_keyReleasedSlot.Connect(eventHandler.OnKeyReleased, this, &Canvas::OnEventKeyReleased); m_mouseButtonPressedSlot.Connect(eventHandler.OnMouseButtonPressed, this, &Canvas::OnEventMouseButtonPressed); m_mouseButtonReleasedSlot.Connect(eventHandler.OnMouseButtonReleased, this, &Canvas::OnEventMouseButtonRelease); m_mouseMovedSlot.Connect(eventHandler.OnMouseMoved, this, &Canvas::OnEventMouseMoved); m_mouseLeftSlot.Connect(eventHandler.OnMouseLeft, this, &Canvas::OnEventMouseLeft); m_textEnteredSlot.Connect(eventHandler.OnTextEntered, this, &Canvas::OnEventTextEntered); // Disable padding by default SetPadding(0.f, 0.f, 0.f, 0.f); } inline Canvas::~Canvas() { // Destroy children explicitly because they signal us when getting destroyed, and that can't happen after our own destruction DestroyChildren(); // Prevent our parent from trying to call us m_canvasIndex = InvalidCanvasIndex; } inline const WorldHandle& Canvas::GetWorld() const { return m_world; } inline void Canvas::ClearKeyboardOwner(std::size_t canvasIndex) { if (m_keyboardOwner == canvasIndex) SetKeyboardOwner(InvalidCanvasIndex); } inline bool Canvas::IsKeyboardOwner(std::size_t canvasIndex) const { return m_keyboardOwner == canvasIndex; } inline void Canvas::NotifyWidgetBoxUpdate(std::size_t index) { WidgetBox& entry = m_widgetBoxes[index]; Nz::Vector3f pos = entry.widget->GetPosition(); Nz::Vector2f size = entry.widget->GetContentSize(); entry.box.Set(pos.x, pos.y, pos.z, size.x, size.y, 1.f); } inline void Canvas::NotifyWidgetCursorUpdate(std::size_t index) { WidgetBox& entry = m_widgetBoxes[index]; entry.cursor = entry.widget->GetCursor(); if (m_cursorController && m_hoveredWidget == index) m_cursorController->UpdateCursor(Nz::Cursor::Get(entry.cursor)); } inline void Canvas::SetKeyboardOwner(std::size_t canvasIndex) { if (m_keyboardOwner != canvasIndex) { if (m_keyboardOwner != InvalidCanvasIndex) m_widgetBoxes[m_keyboardOwner].widget->OnFocusLost(); m_keyboardOwner = canvasIndex; if (m_keyboardOwner != InvalidCanvasIndex) m_widgetBoxes[m_keyboardOwner].widget->OnFocusReceived(); } } } <|endoftext|>
<commit_before>/* main.cpp - platform initialization and context switching emulation Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ //This may be used to change user task stack size: //#define CONT_STACKSIZE 4096 #include <Arduino.h> extern "C" { #include "ets_sys.h" #include "os_type.h" #include "osapi.h" #include "mem.h" #include "user_interface.h" #include "cont.h" } #define LOOP_TASK_PRIORITY 0 #define LOOP_QUEUE_SIZE 1 int atexit(void (*func)()) { return 0; } extern "C" void ets_update_cpu_frequency(int freqmhz); void initVariant() __attribute__((weak)); void initVariant() { } extern void loop(); extern void setup(); void preloop_update_frequency() __attribute__((weak)); void preloop_update_frequency() { #if defined(F_CPU) && (F_CPU == 16000000L) REG_SET_BIT(0x3ff00014, BIT(0)); ets_update_cpu_frequency(160); #endif } extern void (*__init_array_start)(void); extern void (*__init_array_end)(void); static cont_t g_cont; static os_event_t g_loop_queue[LOOP_QUEUE_SIZE]; static uint32_t g_micros_at_task_start; extern "C" uint32_t esp_micros_at_task_start() { return g_micros_at_task_start; } extern "C" void abort() { while(1) { } } extern "C" void esp_yield() { cont_yield(&g_cont); } extern "C" void esp_schedule() { system_os_post(LOOP_TASK_PRIORITY, 0, 0); } extern "C" void __yield() { esp_schedule(); esp_yield(); } extern "C" void yield(void) __attribute__ ((weak, alias("__yield"))); static void loop_wrapper() { static bool setup_done = false; if(!setup_done) { setup(); setup_done = true; } preloop_update_frequency(); loop(); esp_schedule(); } static void loop_task(os_event_t *events) { g_micros_at_task_start = system_get_time(); cont_run(&g_cont, &loop_wrapper); if(cont_check(&g_cont) != 0) { ets_printf("\r\nheap collided with sketch stack\r\n"); abort(); } } static void do_global_ctors(void) { void (**p)(void); for(p = &__init_array_start; p != &__init_array_end; ++p) (*p)(); } void init_done() { do_global_ctors(); esp_schedule(); } extern "C" { void user_init(void) { uart_div_modify(0, UART_CLK_FREQ / (115200)); init(); initVariant(); cont_init(&g_cont); system_os_task(loop_task, LOOP_TASK_PRIORITY, g_loop_queue, LOOP_QUEUE_SIZE); system_init_done_cb(&init_done); } } <commit_msg>fix 160Mhz mode<commit_after>/* main.cpp - platform initialization and context switching emulation Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ //This may be used to change user task stack size: //#define CONT_STACKSIZE 4096 #include <Arduino.h> extern "C" { #include "ets_sys.h" #include "os_type.h" #include "osapi.h" #include "mem.h" #include "user_interface.h" #include "cont.h" } #define LOOP_TASK_PRIORITY 0 #define LOOP_QUEUE_SIZE 1 int atexit(void (*func)()) { return 0; } extern "C" void ets_update_cpu_frequency(int freqmhz); void initVariant() __attribute__((weak)); void initVariant() { } extern void loop(); extern void setup(); void preloop_update_frequency() __attribute__((weak)); void preloop_update_frequency() { #if defined(F_CPU) && (F_CPU == 160000000L) REG_SET_BIT(0x3ff00014, BIT(0)); ets_update_cpu_frequency(160); #endif } extern void (*__init_array_start)(void); extern void (*__init_array_end)(void); static cont_t g_cont; static os_event_t g_loop_queue[LOOP_QUEUE_SIZE]; static uint32_t g_micros_at_task_start; extern "C" uint32_t esp_micros_at_task_start() { return g_micros_at_task_start; } extern "C" void abort() { while(1) { } } extern "C" void esp_yield() { cont_yield(&g_cont); } extern "C" void esp_schedule() { system_os_post(LOOP_TASK_PRIORITY, 0, 0); } extern "C" void __yield() { esp_schedule(); esp_yield(); } extern "C" void yield(void) __attribute__ ((weak, alias("__yield"))); static void loop_wrapper() { static bool setup_done = false; if(!setup_done) { setup(); setup_done = true; } preloop_update_frequency(); loop(); esp_schedule(); } static void loop_task(os_event_t *events) { g_micros_at_task_start = system_get_time(); cont_run(&g_cont, &loop_wrapper); if(cont_check(&g_cont) != 0) { ets_printf("\r\nheap collided with sketch stack\r\n"); abort(); } } static void do_global_ctors(void) { void (**p)(void); for(p = &__init_array_start; p != &__init_array_end; ++p) (*p)(); } void init_done() { do_global_ctors(); esp_schedule(); } extern "C" { void user_init(void) { uart_div_modify(0, UART_CLK_FREQ / (115200)); init(); initVariant(); cont_init(&g_cont); system_os_task(loop_task, LOOP_TASK_PRIORITY, g_loop_queue, LOOP_QUEUE_SIZE); system_init_done_cb(&init_done); } } <|endoftext|>
<commit_before>/*++ Module Name: AlignerContext.cpp Abstract: Common parameters for running single & paired alignment. Authors: Ravi Pandya, May, 2012 Environment: ` User mode service. Revision History: Integrated from SingleAligner.cpp & PairedAligner.cpp --*/ #include "stdafx.h" #include "Compat.h" #include "options.h" #include "AlignerOptions.h" #include "AlignerContext.h" #include "AlignerStats.h" using std::max; AlignerContext::AlignerContext(AlignerExtension* i_extension) : index(NULL), parallelSamWriter(NULL), fileSplitterState(0, 0), options(NULL), stats(NULL), extension(i_extension != NULL ? i_extension : new AlignerExtension()), inputFilename(NULL), fileSplitter(NULL), samWriter(NULL) { } AlignerContext::~AlignerContext() { delete extension; } void AlignerContext::runAlignment(int argc, char **argv) { options = parseOptions(argc, argv); initialize(); extension->initialize(); if (! extension->skipAlignment()) { printStatsHeader(); do { beginIteration(); runTask(); finishIteration(); printStats(); } while (nextIteration()); } extension->finishAlignment(); } void AlignerContext::initializeThread() { stats = newStats(); // separate copy per thread stats->extra = extension->extraStats(); if (NULL != parallelSamWriter) { samWriter = parallelSamWriter->getWriterForThread(threadNum); } else { samWriter = NULL; } extension = extension->copy(); } void AlignerContext::runThread() { extension->beginThread(); runIterationThread(); samWriter->close(); extension->finishThread(); } void AlignerContext::finishThread(AlignerContext* common) { common->stats->add(stats); delete stats; stats = NULL; delete extension; extension = NULL; } void AlignerContext::initialize() { printf("Loading index from directory... "); fflush(stdout); _int64 loadStart = timeInMillis(); index = GenomeIndex::loadFromDirectory((char*) options->indexDir); if (index == NULL) { fprintf(stderr, "Index load failed, aborting.\n"); exit(1); } _int64 loadTime = timeInMillis() - loadStart; printf("%llds. %u bases, seed size %d\n", loadTime / 1000, index->getGenome()->getCountOfBases(), index->getSeedLength()); if (options->samFileTemplate != NULL && (options->maxHits.size() > 1 || options->maxDist.size() > 1 || options->numSeeds.size() > 1 || options->confDiff.size() > 1 || options->adaptiveConfDiff.size() > 1)) { fprintf(stderr, "WARNING: You gave ranges for some parameters, so SAM files will be overwritten!\n"); } confDiff_ = options->confDiff.start; maxHits_ = options->maxHits.start; maxDist_ = options->maxDist.start; numSeeds_ = options->numSeeds.start; adaptiveConfDiff_ = options->adaptiveConfDiff.start; } void AlignerContext::printStatsHeader() { printf("ConfDif\tMaxHits\tMaxDist\tMaxSeed\tConfAd\t%%Used\t%%Unique\t%%Multi\t%%!Found\t%%Error\tReads/s\n"); } void AlignerContext::beginIteration() { parallelSamWriter = NULL; // total mem in Gb if given; default 1 Gb/thread for human genome, scale down for smaller genomes size_t totalMemory = options->sortMemory > 0 ? options->sortMemory * ((size_t) 1 << 30) : options->numThreads * std::min(2 * ParallelSAMWriter::UnsortedBufferSize, (size_t) index->getGenome()->getCountOfBases() / 3); if (NULL != options->samFileTemplate) { parallelSamWriter = ParallelSAMWriter::create(options->samFileTemplate,index->getGenome(), options->numThreads, options->sortOutput, totalMemory); if (NULL == parallelSamWriter) { fprintf(stderr,"Unable to create SAM file writer. Just aligning for speed, no output will be generated.\n"); } } alignStart = timeInMillis(); fileSplitterState = RangeSplitter(QueryFileSize(options->inputFilename), options->numThreads, 15); clipping = options->clipping; totalThreads = options->numThreads; computeError = options->computeError; bindToProcessors = options->bindToProcessors; maxDist = maxDist_; maxHits = maxHits_; numSeeds = numSeeds_; confDiff = confDiff_; adaptiveConfDiff = adaptiveConfDiff_; selectivity = options->selectivity; inputFilename = options->inputFilename; inputFileIsFASTQ = options->inputFileIsFASTQ; fileSplitter = &fileSplitterState; if (stats != NULL) { delete stats; } stats = newStats(); stats->extra = extension->extraStats(); extension->beginIteration(); } void AlignerContext::finishIteration() { extension->finishIteration(); if (NULL != parallelSamWriter) { parallelSamWriter->close(); delete parallelSamWriter; parallelSamWriter = NULL; } alignTime = timeInMillis() - alignStart; } bool AlignerContext::nextIteration() { if ((adaptiveConfDiff_ += options->adaptiveConfDiff.step) > options->adaptiveConfDiff.end) { adaptiveConfDiff_ = options->adaptiveConfDiff.start; if ((numSeeds_ += options->numSeeds.step) > options->numSeeds.end) { numSeeds_ = options->numSeeds.start; if ((maxDist_ += options->maxDist.step) > options->maxDist.end) { maxDist_ = options->maxDist.start; if ((maxHits_ += options->maxHits.step) > options->maxHits.end) { maxHits_ = options->maxHits.start; if ((confDiff_ += options->confDiff.step) > options->confDiff.end) { return false; } } } } } return true; } void AlignerContext::printStats() { double usefulReads = max((double) stats->usefulReads, 1.0); char errorRate[16]; if (options->computeError) { _int64 numSingle = max(stats->singleHits, (_int64) 1); snprintf(errorRate, sizeof(errorRate), "%0.3f%%", (100.0 * stats->errors) / numSingle); } else { snprintf(errorRate, sizeof(errorRate), "-"); } printf("%d\t%d\t%d\t%d\t%d\t%0.2f%%\t%0.2f%%\t%0.2f%%\t%0.2f%%\t%s\t%.0f\n", confDiff_, maxHits_, maxDist_, numSeeds_, adaptiveConfDiff_, 100.0 * usefulReads / max(stats->totalReads, (_int64) 1), 100.0 * stats->singleHits / usefulReads, 100.0 * stats->multiHits / usefulReads, 100.0 * stats->notFound / usefulReads, errorRate, (1000.0 * usefulReads) / max(alignTime, (_int64) 1)); extension->printStats(); } <commit_msg>Windows compile fix<commit_after>/*++ Module Name: AlignerContext.cpp Abstract: Common parameters for running single & paired alignment. Authors: Ravi Pandya, May, 2012 Environment: ` User mode service. Revision History: Integrated from SingleAligner.cpp & PairedAligner.cpp --*/ #include "stdafx.h" #include "Compat.h" #include "options.h" #include "AlignerOptions.h" #include "AlignerContext.h" #include "AlignerStats.h" using std::max; using std::min; AlignerContext::AlignerContext(AlignerExtension* i_extension) : index(NULL), parallelSamWriter(NULL), fileSplitterState(0, 0), options(NULL), stats(NULL), extension(i_extension != NULL ? i_extension : new AlignerExtension()), inputFilename(NULL), fileSplitter(NULL), samWriter(NULL) { } AlignerContext::~AlignerContext() { delete extension; } void AlignerContext::runAlignment(int argc, char **argv) { options = parseOptions(argc, argv); initialize(); extension->initialize(); if (! extension->skipAlignment()) { printStatsHeader(); do { beginIteration(); runTask(); finishIteration(); printStats(); } while (nextIteration()); } extension->finishAlignment(); } void AlignerContext::initializeThread() { stats = newStats(); // separate copy per thread stats->extra = extension->extraStats(); if (NULL != parallelSamWriter) { samWriter = parallelSamWriter->getWriterForThread(threadNum); } else { samWriter = NULL; } extension = extension->copy(); } void AlignerContext::runThread() { extension->beginThread(); runIterationThread(); samWriter->close(); extension->finishThread(); } void AlignerContext::finishThread(AlignerContext* common) { common->stats->add(stats); delete stats; stats = NULL; delete extension; extension = NULL; } void AlignerContext::initialize() { printf("Loading index from directory... "); fflush(stdout); _int64 loadStart = timeInMillis(); index = GenomeIndex::loadFromDirectory((char*) options->indexDir); if (index == NULL) { fprintf(stderr, "Index load failed, aborting.\n"); exit(1); } _int64 loadTime = timeInMillis() - loadStart; printf("%llds. %u bases, seed size %d\n", loadTime / 1000, index->getGenome()->getCountOfBases(), index->getSeedLength()); if (options->samFileTemplate != NULL && (options->maxHits.size() > 1 || options->maxDist.size() > 1 || options->numSeeds.size() > 1 || options->confDiff.size() > 1 || options->adaptiveConfDiff.size() > 1)) { fprintf(stderr, "WARNING: You gave ranges for some parameters, so SAM files will be overwritten!\n"); } confDiff_ = options->confDiff.start; maxHits_ = options->maxHits.start; maxDist_ = options->maxDist.start; numSeeds_ = options->numSeeds.start; adaptiveConfDiff_ = options->adaptiveConfDiff.start; } void AlignerContext::printStatsHeader() { printf("ConfDif\tMaxHits\tMaxDist\tMaxSeed\tConfAd\t%%Used\t%%Unique\t%%Multi\t%%!Found\t%%Error\tReads/s\n"); } void AlignerContext::beginIteration() { parallelSamWriter = NULL; // total mem in Gb if given; default 1 Gb/thread for human genome, scale down for smaller genomes size_t totalMemory = options->sortMemory > 0 ? options->sortMemory * ((size_t) 1 << 30) : options->numThreads * min(2 * ParallelSAMWriter::UnsortedBufferSize, (size_t) index->getGenome()->getCountOfBases() / 3); if (NULL != options->samFileTemplate) { parallelSamWriter = ParallelSAMWriter::create(options->samFileTemplate,index->getGenome(), options->numThreads, options->sortOutput, totalMemory); if (NULL == parallelSamWriter) { fprintf(stderr,"Unable to create SAM file writer. Just aligning for speed, no output will be generated.\n"); } } alignStart = timeInMillis(); fileSplitterState = RangeSplitter(QueryFileSize(options->inputFilename), options->numThreads, 15); clipping = options->clipping; totalThreads = options->numThreads; computeError = options->computeError; bindToProcessors = options->bindToProcessors; maxDist = maxDist_; maxHits = maxHits_; numSeeds = numSeeds_; confDiff = confDiff_; adaptiveConfDiff = adaptiveConfDiff_; selectivity = options->selectivity; inputFilename = options->inputFilename; inputFileIsFASTQ = options->inputFileIsFASTQ; fileSplitter = &fileSplitterState; if (stats != NULL) { delete stats; } stats = newStats(); stats->extra = extension->extraStats(); extension->beginIteration(); } void AlignerContext::finishIteration() { extension->finishIteration(); if (NULL != parallelSamWriter) { parallelSamWriter->close(); delete parallelSamWriter; parallelSamWriter = NULL; } alignTime = timeInMillis() - alignStart; } bool AlignerContext::nextIteration() { if ((adaptiveConfDiff_ += options->adaptiveConfDiff.step) > options->adaptiveConfDiff.end) { adaptiveConfDiff_ = options->adaptiveConfDiff.start; if ((numSeeds_ += options->numSeeds.step) > options->numSeeds.end) { numSeeds_ = options->numSeeds.start; if ((maxDist_ += options->maxDist.step) > options->maxDist.end) { maxDist_ = options->maxDist.start; if ((maxHits_ += options->maxHits.step) > options->maxHits.end) { maxHits_ = options->maxHits.start; if ((confDiff_ += options->confDiff.step) > options->confDiff.end) { return false; } } } } } return true; } void AlignerContext::printStats() { double usefulReads = max((double) stats->usefulReads, 1.0); char errorRate[16]; if (options->computeError) { _int64 numSingle = max(stats->singleHits, (_int64) 1); snprintf(errorRate, sizeof(errorRate), "%0.3f%%", (100.0 * stats->errors) / numSingle); } else { snprintf(errorRate, sizeof(errorRate), "-"); } printf("%d\t%d\t%d\t%d\t%d\t%0.2f%%\t%0.2f%%\t%0.2f%%\t%0.2f%%\t%s\t%.0f\n", confDiff_, maxHits_, maxDist_, numSeeds_, adaptiveConfDiff_, 100.0 * usefulReads / max(stats->totalReads, (_int64) 1), 100.0 * stats->singleHits / usefulReads, 100.0 * stats->multiHits / usefulReads, 100.0 * stats->notFound / usefulReads, errorRate, (1000.0 * usefulReads) / max(alignTime, (_int64) 1)); extension->printStats(); } <|endoftext|>
<commit_before>//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Expression parsing implementation for C++. // //===----------------------------------------------------------------------===// #include "clang/Basic/Diagnostic.h" #include "clang/Parse/Parser.h" #include "clang/Parse/DeclSpec.h" using namespace clang; /// ParseCXXCasts - This handles the various ways to cast expressions to another /// type. /// /// postfix-expression: [C++ 5.2p1] /// 'dynamic_cast' '<' type-name '>' '(' expression ')' /// 'static_cast' '<' type-name '>' '(' expression ')' /// 'reinterpret_cast' '<' type-name '>' '(' expression ')' /// 'const_cast' '<' type-name '>' '(' expression ')' /// Parser::ExprResult Parser::ParseCXXCasts() { tok::TokenKind Kind = Tok.getKind(); const char *CastName = 0; // For error messages switch (Kind) { default: assert(0 && "Unknown C++ cast!"); abort(); case tok::kw_const_cast: CastName = "const_cast"; break; case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break; case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break; case tok::kw_static_cast: CastName = "static_cast"; break; } SourceLocation OpLoc = ConsumeToken(); SourceLocation LAngleBracketLoc = Tok.getLocation(); if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName)) return ExprResult(true); TypeTy *CastTy = ParseTypeName(); SourceLocation RAngleBracketLoc = Tok.getLocation(); if (ExpectAndConsume(tok::greater, diag::err_expected_greater)) { Diag(LAngleBracketLoc, diag::err_matching, "<"); return ExprResult(true); } SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; if (Tok.isNot(tok::l_paren)) { Diag(Tok, diag::err_expected_lparen_after, CastName); return ExprResult(true); } ExprResult Result = ParseSimpleParenExpression(RParenLoc); if (!Result.isInvalid) Result = Actions.ActOnCXXNamedCast(OpLoc, Kind, LAngleBracketLoc, CastTy, RAngleBracketLoc, LParenLoc, Result.Val, RParenLoc); return Result; } /// ParseCXXBoolLiteral - This handles the C++ Boolean literals. /// /// boolean-literal: [C++ 2.13.5] /// 'true' /// 'false' Parser::ExprResult Parser::ParseCXXBoolLiteral() { tok::TokenKind Kind = Tok.getKind(); return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind); } /// ParseThrowExpression - This handles the C++ throw expression. /// /// throw-expression: [C++ 15] /// 'throw' assignment-expression[opt] Parser::ExprResult Parser::ParseThrowExpression() { assert(Tok.is(tok::kw_throw) && "Not throw!"); SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token. // If the current token isn't the start of an assignment-expression, // then the expression is not present. This handles things like: // "C ? throw : (void)42", which is crazy but legal. switch (Tok.getKind()) { // FIXME: move this predicate somewhere common. case tok::semi: case tok::r_paren: case tok::r_square: case tok::r_brace: case tok::colon: case tok::comma: return Actions.ActOnCXXThrow(ThrowLoc); default: ExprResult Expr = ParseAssignmentExpression(); if (Expr.isInvalid) return Expr; return Actions.ActOnCXXThrow(ThrowLoc, Expr.Val); } } /// ParseCXXThis - This handles the C++ 'this' pointer. /// /// C++ 9.3.2: In the body of a non-static member function, the keyword this is /// a non-lvalue expression whose value is the address of the object for which /// the function is called. Parser::ExprResult Parser::ParseCXXThis() { assert(Tok.is(tok::kw_this) && "Not 'this'!"); SourceLocation ThisLoc = ConsumeToken(); return Actions.ActOnCXXThis(ThisLoc); } /// ParseCXXTypeConstructExpression - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). /// /// postfix-expression: [C++ 5.2p1] /// simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3] /// typename-specifier '(' expression-list[opt] ')' [TODO] /// Parser::ExprResult Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) { Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); TypeTy *TypeRep = Actions.ActOnTypeName(CurScope, DeclaratorInfo).Val; assert(Tok.is(tok::l_paren) && "Expected '('!"); SourceLocation LParenLoc = ConsumeParen(); ExprListTy Exprs; CommaLocsTy CommaLocs; if (Tok.isNot(tok::r_paren)) { if (ParseExpressionList(Exprs, CommaLocs)) { SkipUntil(tok::r_paren); return ExprResult(true); } } // Match the ')'. SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&& "Unexpected number of commas!"); return Actions.ActOnCXXTypeConstructExpr(DS.getSourceRange(), TypeRep, LParenLoc, &Exprs[0], Exprs.size(), &CommaLocs[0], RParenLoc); } /// ParseCXXCondition - if/switch/while/for condition expression. /// /// condition: /// expression /// type-specifier-seq declarator '=' assignment-expression /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt] /// '=' assignment-expression /// Parser::ExprResult Parser::ParseCXXCondition() { if (!isCXXConditionDeclaration()) return ParseExpression(); // expression SourceLocation StartLoc = Tok.getLocation(); // type-specifier-seq DeclSpec DS; ParseSpecifierQualifierList(DS); // declarator Declarator DeclaratorInfo(DS, Declarator::ConditionContext); ParseDeclarator(DeclaratorInfo); // simple-asm-expr[opt] if (Tok.is(tok::kw_asm)) { ExprResult AsmLabel = ParseSimpleAsm(); if (AsmLabel.isInvalid) { SkipUntil(tok::semi); return true; } DeclaratorInfo.setAsmLabel(AsmLabel.Val); } // If attributes are present, parse them. if (Tok.is(tok::kw___attribute)) DeclaratorInfo.AddAttributes(ParseAttributes()); // '=' assignment-expression if (Tok.isNot(tok::equal)) return Diag(Tok, diag::err_expected_equal_after_declarator); SourceLocation EqualLoc = ConsumeToken(); ExprResult AssignExpr = ParseAssignmentExpression(); if (AssignExpr.isInvalid) return true; return Actions.ActOnCXXConditionDeclarationExpr(CurScope, StartLoc, DeclaratorInfo, EqualLoc, AssignExpr.Val); } /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. /// This should only be called when the current token is known to be part of /// simple-type-specifier. /// /// simple-type-specifier: /// '::'[opt] nested-name-specifier[opt] type-name [TODO] /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO] /// char /// wchar_t /// bool /// short /// int /// long /// signed /// unsigned /// float /// double /// void /// [GNU] typeof-specifier /// [C++0x] auto [TODO] /// /// type-name: /// class-name /// enum-name /// typedef-name /// void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { DS.SetRangeStart(Tok.getLocation()); const char *PrevSpec; SourceLocation Loc = Tok.getLocation(); switch (Tok.getKind()) { default: assert(0 && "Not a simple-type-specifier token!"); abort(); // type-name case tok::identifier: { TypeTy *TypeRep = Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope); assert(TypeRep && "Identifier wasn't a type-name!"); DS.SetTypeSpecType(DeclSpec::TST_typedef, Loc, PrevSpec, TypeRep); break; } // builtin types case tok::kw_short: DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec); break; case tok::kw_long: DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec); break; case tok::kw_signed: DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec); break; case tok::kw_unsigned: DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec); break; case tok::kw_void: DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec); break; case tok::kw_char: DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec); break; case tok::kw_int: DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec); break; case tok::kw_float: DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec); break; case tok::kw_double: DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec); break; case tok::kw_wchar_t: DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec); break; case tok::kw_bool: DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec); break; // GNU typeof support. case tok::kw_typeof: ParseTypeofSpecifier(DS); DS.Finish(Diags, PP.getSourceManager(), getLang()); return; } DS.SetRangeEnd(Tok.getLocation()); ConsumeToken(); DS.Finish(Diags, PP.getSourceManager(), getLang()); } /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++ /// [dcl.name]), which is a non-empty sequence of type-specifiers, /// e.g., "const short int". Note that the DeclSpec is *not* finished /// by parsing the type-specifier-seq, because these sequences are /// typically followed by some form of declarator. Returns true and /// emits diagnostics if this is not a type-specifier-seq, false /// otherwise. /// /// type-specifier-seq: [C++ 8.1] /// type-specifier type-specifier-seq[opt] /// bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) { DS.SetRangeStart(Tok.getLocation()); const char *PrevSpec = 0; int isInvalid = 0; // Parse one or more of the type specifiers. if (!MaybeParseTypeSpecifier(DS, isInvalid, PrevSpec)) { Diag(Tok.getLocation(), diag::err_operator_missing_type_specifier); return true; } while (MaybeParseTypeSpecifier(DS, isInvalid, PrevSpec)); return false; } /// MaybeParseOperatorFunctionId - Attempts to parse a C++ overloaded /// operator name (C++ [over.oper]). If successful, returns the /// predefined identifier that corresponds to that overloaded /// operator. Otherwise, returns NULL and does not consume any tokens. /// /// operator-function-id: [C++ 13.5] /// 'operator' operator /// /// operator: one of /// new delete new[] delete[] /// + - * / % ^ & | ~ /// ! = < > += -= *= /= %= /// ^= &= |= << >> >>= <<= == != /// <= >= && || ++ -- , ->* -> /// () [] IdentifierInfo *Parser::MaybeParseOperatorFunctionId() { assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword"); OverloadedOperatorKind Op = OO_None; switch (NextToken().getKind()) { case tok::kw_new: ConsumeToken(); // 'operator' ConsumeToken(); // 'new' if (Tok.is(tok::l_square)) { ConsumeBracket(); // '[' ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); // ']' Op = OO_Array_New; } else { Op = OO_New; } return &PP.getIdentifierTable().getOverloadedOperator(Op); case tok::kw_delete: ConsumeToken(); // 'operator' ConsumeToken(); // 'delete' if (Tok.is(tok::l_square)) { ConsumeBracket(); // '[' ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); // ']' Op = OO_Array_Delete; } else { Op = OO_Delete; } return &PP.getIdentifierTable().getOverloadedOperator(Op); #define OVERLOADED_OPERATOR(Name,Spelling,Token) \ case tok::Token: Op = OO_##Name; break; #define OVERLOADED_OPERATOR_MULTI(Name,Spelling) #include "clang/Basic/OperatorKinds.def" case tok::l_paren: ConsumeToken(); // 'operator' ConsumeParen(); // '(' ExpectAndConsume(tok::r_paren, diag::err_expected_rparen); // ')' return &PP.getIdentifierTable().getOverloadedOperator(OO_Call); case tok::l_square: ConsumeToken(); // 'operator' ConsumeBracket(); // '[' ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); // ']' return &PP.getIdentifierTable().getOverloadedOperator(OO_Subscript); default: break; } if (Op == OO_None) return 0; else { ConsumeToken(); // 'operator' ConsumeAnyToken(); // the operator itself return &PP.getIdentifierTable().getOverloadedOperator(Op); } } /// ParseConversionFunctionId - Parse a C++ conversion-function-id, /// which expresses the name of a user-defined conversion operator /// (C++ [class.conv.fct]p1). Returns the type that this operator is /// specifying a conversion for, or NULL if there was an error. /// /// conversion-function-id: [C++ 12.3.2] /// operator conversion-type-id /// /// conversion-type-id: /// type-specifier-seq conversion-declarator[opt] /// /// conversion-declarator: /// ptr-operator conversion-declarator[opt] Parser::TypeTy *Parser::ParseConversionFunctionId() { assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword"); ConsumeToken(); // 'operator' // Parse the type-specifier-seq. DeclSpec DS; if (ParseCXXTypeSpecifierSeq(DS)) return 0; // Parse the conversion-declarator, which is merely a sequence of // ptr-operators. Declarator D(DS, Declarator::TypeNameContext); ParseDeclaratorInternal(D, /*PtrOperator=*/true); // Finish up the type. Action::TypeResult Result = Actions.ActOnTypeName(CurScope, D); if (Result.isInvalid) return 0; else return Result.Val; } <commit_msg>Silence a gcc warning.<commit_after>//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Expression parsing implementation for C++. // //===----------------------------------------------------------------------===// #include "clang/Basic/Diagnostic.h" #include "clang/Parse/Parser.h" #include "clang/Parse/DeclSpec.h" using namespace clang; /// ParseCXXCasts - This handles the various ways to cast expressions to another /// type. /// /// postfix-expression: [C++ 5.2p1] /// 'dynamic_cast' '<' type-name '>' '(' expression ')' /// 'static_cast' '<' type-name '>' '(' expression ')' /// 'reinterpret_cast' '<' type-name '>' '(' expression ')' /// 'const_cast' '<' type-name '>' '(' expression ')' /// Parser::ExprResult Parser::ParseCXXCasts() { tok::TokenKind Kind = Tok.getKind(); const char *CastName = 0; // For error messages switch (Kind) { default: assert(0 && "Unknown C++ cast!"); abort(); case tok::kw_const_cast: CastName = "const_cast"; break; case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break; case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break; case tok::kw_static_cast: CastName = "static_cast"; break; } SourceLocation OpLoc = ConsumeToken(); SourceLocation LAngleBracketLoc = Tok.getLocation(); if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName)) return ExprResult(true); TypeTy *CastTy = ParseTypeName(); SourceLocation RAngleBracketLoc = Tok.getLocation(); if (ExpectAndConsume(tok::greater, diag::err_expected_greater)) { Diag(LAngleBracketLoc, diag::err_matching, "<"); return ExprResult(true); } SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; if (Tok.isNot(tok::l_paren)) { Diag(Tok, diag::err_expected_lparen_after, CastName); return ExprResult(true); } ExprResult Result = ParseSimpleParenExpression(RParenLoc); if (!Result.isInvalid) Result = Actions.ActOnCXXNamedCast(OpLoc, Kind, LAngleBracketLoc, CastTy, RAngleBracketLoc, LParenLoc, Result.Val, RParenLoc); return Result; } /// ParseCXXBoolLiteral - This handles the C++ Boolean literals. /// /// boolean-literal: [C++ 2.13.5] /// 'true' /// 'false' Parser::ExprResult Parser::ParseCXXBoolLiteral() { tok::TokenKind Kind = Tok.getKind(); return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind); } /// ParseThrowExpression - This handles the C++ throw expression. /// /// throw-expression: [C++ 15] /// 'throw' assignment-expression[opt] Parser::ExprResult Parser::ParseThrowExpression() { assert(Tok.is(tok::kw_throw) && "Not throw!"); SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token. // If the current token isn't the start of an assignment-expression, // then the expression is not present. This handles things like: // "C ? throw : (void)42", which is crazy but legal. switch (Tok.getKind()) { // FIXME: move this predicate somewhere common. case tok::semi: case tok::r_paren: case tok::r_square: case tok::r_brace: case tok::colon: case tok::comma: return Actions.ActOnCXXThrow(ThrowLoc); default: ExprResult Expr = ParseAssignmentExpression(); if (Expr.isInvalid) return Expr; return Actions.ActOnCXXThrow(ThrowLoc, Expr.Val); } } /// ParseCXXThis - This handles the C++ 'this' pointer. /// /// C++ 9.3.2: In the body of a non-static member function, the keyword this is /// a non-lvalue expression whose value is the address of the object for which /// the function is called. Parser::ExprResult Parser::ParseCXXThis() { assert(Tok.is(tok::kw_this) && "Not 'this'!"); SourceLocation ThisLoc = ConsumeToken(); return Actions.ActOnCXXThis(ThisLoc); } /// ParseCXXTypeConstructExpression - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). /// /// postfix-expression: [C++ 5.2p1] /// simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3] /// typename-specifier '(' expression-list[opt] ')' [TODO] /// Parser::ExprResult Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) { Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); TypeTy *TypeRep = Actions.ActOnTypeName(CurScope, DeclaratorInfo).Val; assert(Tok.is(tok::l_paren) && "Expected '('!"); SourceLocation LParenLoc = ConsumeParen(); ExprListTy Exprs; CommaLocsTy CommaLocs; if (Tok.isNot(tok::r_paren)) { if (ParseExpressionList(Exprs, CommaLocs)) { SkipUntil(tok::r_paren); return ExprResult(true); } } // Match the ')'. SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&& "Unexpected number of commas!"); return Actions.ActOnCXXTypeConstructExpr(DS.getSourceRange(), TypeRep, LParenLoc, &Exprs[0], Exprs.size(), &CommaLocs[0], RParenLoc); } /// ParseCXXCondition - if/switch/while/for condition expression. /// /// condition: /// expression /// type-specifier-seq declarator '=' assignment-expression /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt] /// '=' assignment-expression /// Parser::ExprResult Parser::ParseCXXCondition() { if (!isCXXConditionDeclaration()) return ParseExpression(); // expression SourceLocation StartLoc = Tok.getLocation(); // type-specifier-seq DeclSpec DS; ParseSpecifierQualifierList(DS); // declarator Declarator DeclaratorInfo(DS, Declarator::ConditionContext); ParseDeclarator(DeclaratorInfo); // simple-asm-expr[opt] if (Tok.is(tok::kw_asm)) { ExprResult AsmLabel = ParseSimpleAsm(); if (AsmLabel.isInvalid) { SkipUntil(tok::semi); return true; } DeclaratorInfo.setAsmLabel(AsmLabel.Val); } // If attributes are present, parse them. if (Tok.is(tok::kw___attribute)) DeclaratorInfo.AddAttributes(ParseAttributes()); // '=' assignment-expression if (Tok.isNot(tok::equal)) return Diag(Tok, diag::err_expected_equal_after_declarator); SourceLocation EqualLoc = ConsumeToken(); ExprResult AssignExpr = ParseAssignmentExpression(); if (AssignExpr.isInvalid) return true; return Actions.ActOnCXXConditionDeclarationExpr(CurScope, StartLoc, DeclaratorInfo, EqualLoc, AssignExpr.Val); } /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. /// This should only be called when the current token is known to be part of /// simple-type-specifier. /// /// simple-type-specifier: /// '::'[opt] nested-name-specifier[opt] type-name [TODO] /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO] /// char /// wchar_t /// bool /// short /// int /// long /// signed /// unsigned /// float /// double /// void /// [GNU] typeof-specifier /// [C++0x] auto [TODO] /// /// type-name: /// class-name /// enum-name /// typedef-name /// void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { DS.SetRangeStart(Tok.getLocation()); const char *PrevSpec; SourceLocation Loc = Tok.getLocation(); switch (Tok.getKind()) { default: assert(0 && "Not a simple-type-specifier token!"); abort(); // type-name case tok::identifier: { TypeTy *TypeRep = Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope); assert(TypeRep && "Identifier wasn't a type-name!"); DS.SetTypeSpecType(DeclSpec::TST_typedef, Loc, PrevSpec, TypeRep); break; } // builtin types case tok::kw_short: DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec); break; case tok::kw_long: DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec); break; case tok::kw_signed: DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec); break; case tok::kw_unsigned: DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec); break; case tok::kw_void: DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec); break; case tok::kw_char: DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec); break; case tok::kw_int: DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec); break; case tok::kw_float: DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec); break; case tok::kw_double: DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec); break; case tok::kw_wchar_t: DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec); break; case tok::kw_bool: DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec); break; // GNU typeof support. case tok::kw_typeof: ParseTypeofSpecifier(DS); DS.Finish(Diags, PP.getSourceManager(), getLang()); return; } DS.SetRangeEnd(Tok.getLocation()); ConsumeToken(); DS.Finish(Diags, PP.getSourceManager(), getLang()); } /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++ /// [dcl.name]), which is a non-empty sequence of type-specifiers, /// e.g., "const short int". Note that the DeclSpec is *not* finished /// by parsing the type-specifier-seq, because these sequences are /// typically followed by some form of declarator. Returns true and /// emits diagnostics if this is not a type-specifier-seq, false /// otherwise. /// /// type-specifier-seq: [C++ 8.1] /// type-specifier type-specifier-seq[opt] /// bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) { DS.SetRangeStart(Tok.getLocation()); const char *PrevSpec = 0; int isInvalid = 0; // Parse one or more of the type specifiers. if (!MaybeParseTypeSpecifier(DS, isInvalid, PrevSpec)) { Diag(Tok.getLocation(), diag::err_operator_missing_type_specifier); return true; } while (MaybeParseTypeSpecifier(DS, isInvalid, PrevSpec)) ; return false; } /// MaybeParseOperatorFunctionId - Attempts to parse a C++ overloaded /// operator name (C++ [over.oper]). If successful, returns the /// predefined identifier that corresponds to that overloaded /// operator. Otherwise, returns NULL and does not consume any tokens. /// /// operator-function-id: [C++ 13.5] /// 'operator' operator /// /// operator: one of /// new delete new[] delete[] /// + - * / % ^ & | ~ /// ! = < > += -= *= /= %= /// ^= &= |= << >> >>= <<= == != /// <= >= && || ++ -- , ->* -> /// () [] IdentifierInfo *Parser::MaybeParseOperatorFunctionId() { assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword"); OverloadedOperatorKind Op = OO_None; switch (NextToken().getKind()) { case tok::kw_new: ConsumeToken(); // 'operator' ConsumeToken(); // 'new' if (Tok.is(tok::l_square)) { ConsumeBracket(); // '[' ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); // ']' Op = OO_Array_New; } else { Op = OO_New; } return &PP.getIdentifierTable().getOverloadedOperator(Op); case tok::kw_delete: ConsumeToken(); // 'operator' ConsumeToken(); // 'delete' if (Tok.is(tok::l_square)) { ConsumeBracket(); // '[' ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); // ']' Op = OO_Array_Delete; } else { Op = OO_Delete; } return &PP.getIdentifierTable().getOverloadedOperator(Op); #define OVERLOADED_OPERATOR(Name,Spelling,Token) \ case tok::Token: Op = OO_##Name; break; #define OVERLOADED_OPERATOR_MULTI(Name,Spelling) #include "clang/Basic/OperatorKinds.def" case tok::l_paren: ConsumeToken(); // 'operator' ConsumeParen(); // '(' ExpectAndConsume(tok::r_paren, diag::err_expected_rparen); // ')' return &PP.getIdentifierTable().getOverloadedOperator(OO_Call); case tok::l_square: ConsumeToken(); // 'operator' ConsumeBracket(); // '[' ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); // ']' return &PP.getIdentifierTable().getOverloadedOperator(OO_Subscript); default: break; } if (Op == OO_None) return 0; else { ConsumeToken(); // 'operator' ConsumeAnyToken(); // the operator itself return &PP.getIdentifierTable().getOverloadedOperator(Op); } } /// ParseConversionFunctionId - Parse a C++ conversion-function-id, /// which expresses the name of a user-defined conversion operator /// (C++ [class.conv.fct]p1). Returns the type that this operator is /// specifying a conversion for, or NULL if there was an error. /// /// conversion-function-id: [C++ 12.3.2] /// operator conversion-type-id /// /// conversion-type-id: /// type-specifier-seq conversion-declarator[opt] /// /// conversion-declarator: /// ptr-operator conversion-declarator[opt] Parser::TypeTy *Parser::ParseConversionFunctionId() { assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword"); ConsumeToken(); // 'operator' // Parse the type-specifier-seq. DeclSpec DS; if (ParseCXXTypeSpecifierSeq(DS)) return 0; // Parse the conversion-declarator, which is merely a sequence of // ptr-operators. Declarator D(DS, Declarator::TypeNameContext); ParseDeclaratorInternal(D, /*PtrOperator=*/true); // Finish up the type. Action::TypeResult Result = Actions.ActOnTypeName(CurScope, D); if (Result.isInvalid) return 0; else return Result.Val; } <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 - 2022 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_HOOFS_CXX_UNIQUE_PTR_INL #define IOX_HOOFS_CXX_UNIQUE_PTR_INL #include "iceoryx_hoofs/cxx/unique_ptr.hpp" namespace iox { namespace cxx { // AXIVION Next Construct AutosarC++19_03-A12.1.5 : False positive, the class doesn't require a delegating ctor template <typename T> inline unique_ptr<T>::unique_ptr(T* const object, const function<DeleterType>& deleter) noexcept : m_ptr(object) , m_deleter(deleter) { Ensures(object != nullptr); } template <typename T> inline unique_ptr<T>& unique_ptr<T>::operator=(unique_ptr&& rhs) noexcept { if (this != &rhs) { destroy(); m_ptr = rhs.m_ptr; m_deleter = std::move(rhs.m_deleter); rhs.m_ptr = nullptr; } return *this; } template <typename T> inline unique_ptr<T>::unique_ptr(unique_ptr&& rhs) noexcept : m_ptr{rhs.m_ptr} , m_deleter{std::move(rhs.m_deleter)} { rhs.m_ptr = nullptr; } template <typename T> inline unique_ptr<T>::~unique_ptr() noexcept { destroy(); } template <typename T> inline T* unique_ptr<T>::operator->() noexcept { cxx::Expects(m_ptr != nullptr); return get(); } template <typename T> inline const T* unique_ptr<T>::operator->() const noexcept { // AXIVION Next Construct AutosarC++19_03-A5.2.3, CertC++-EXP55 : Avoid code duplication // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return const_cast<unique_ptr<T>*>(this)->operator->(); } template <typename T> inline T* unique_ptr<T>::get() noexcept { return m_ptr; } template <typename T> inline const T* unique_ptr<T>::get() const noexcept { // AXIVION Next Construct AutosarC++19_03-A5.2.3, CertC++-EXP55 : Avoid code duplication // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return const_cast<unique_ptr<T>*>(this)->get(); } template <typename T> inline T* unique_ptr<T>::release(unique_ptr&& ptrToBeReleased) noexcept { // AXIVION Next Line AutosarC++19_03-A7.1.1 : Pointer is explicitly not const to adhere to return type auto* ptr = ptrToBeReleased.m_ptr; ptrToBeReleased.m_ptr = nullptr; return ptr; } template <typename T> inline void unique_ptr<T>::destroy() noexcept { if (m_ptr != nullptr) { m_deleter(m_ptr); } m_ptr = nullptr; } template <typename T> inline void unique_ptr<T>::swap(unique_ptr<T>& other) noexcept { std::swap(m_ptr, other.m_ptr); std::swap(m_deleter, other.m_deleter); } // AXIVION DISABLE STYLE AutosarC++19_03-A13.5.5 : See header template <typename T, typename U> inline bool operator==(const unique_ptr<T>& lhs, const unique_ptr<U>& rhs) noexcept { return lhs.get() == rhs.get(); } template <typename T, typename U> inline bool operator!=(const unique_ptr<T>& lhs, const unique_ptr<U>& rhs) noexcept { return !(lhs == rhs); } // AXIVION ENABLE STYLE AutosarC++19_03-A13.5.5 : See header } // namespace cxx } // namespace iox #endif // IOX_HOOFS_CXX_UNIQUE_PTR_INL <commit_msg>iox-#1391 Remove Axivion suppression by making pointer const<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 - 2022 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_HOOFS_CXX_UNIQUE_PTR_INL #define IOX_HOOFS_CXX_UNIQUE_PTR_INL #include "iceoryx_hoofs/cxx/unique_ptr.hpp" namespace iox { namespace cxx { // AXIVION Next Construct AutosarC++19_03-A12.1.5 : False positive, the class doesn't require a delegating ctor template <typename T> inline unique_ptr<T>::unique_ptr(T* const object, const function<DeleterType>& deleter) noexcept : m_ptr(object) , m_deleter(deleter) { Ensures(object != nullptr); } template <typename T> inline unique_ptr<T>& unique_ptr<T>::operator=(unique_ptr&& rhs) noexcept { if (this != &rhs) { destroy(); m_ptr = rhs.m_ptr; m_deleter = std::move(rhs.m_deleter); rhs.m_ptr = nullptr; } return *this; } template <typename T> inline unique_ptr<T>::unique_ptr(unique_ptr&& rhs) noexcept : m_ptr{rhs.m_ptr} , m_deleter{std::move(rhs.m_deleter)} { rhs.m_ptr = nullptr; } template <typename T> inline unique_ptr<T>::~unique_ptr() noexcept { destroy(); } template <typename T> inline T* unique_ptr<T>::operator->() noexcept { cxx::Expects(m_ptr != nullptr); return get(); } template <typename T> inline const T* unique_ptr<T>::operator->() const noexcept { // AXIVION Next Construct AutosarC++19_03-A5.2.3, CertC++-EXP55 : Avoid code duplication // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return const_cast<unique_ptr<T>*>(this)->operator->(); } template <typename T> inline T* unique_ptr<T>::get() noexcept { return m_ptr; } template <typename T> inline const T* unique_ptr<T>::get() const noexcept { // AXIVION Next Construct AutosarC++19_03-A5.2.3, CertC++-EXP55 : Avoid code duplication // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return const_cast<unique_ptr<T>*>(this)->get(); } template <typename T> inline T* unique_ptr<T>::release(unique_ptr&& ptrToBeReleased) noexcept { auto* const ptr = ptrToBeReleased.m_ptr; ptrToBeReleased.m_ptr = nullptr; return ptr; } template <typename T> inline void unique_ptr<T>::destroy() noexcept { if (m_ptr != nullptr) { m_deleter(m_ptr); } m_ptr = nullptr; } template <typename T> inline void unique_ptr<T>::swap(unique_ptr<T>& other) noexcept { std::swap(m_ptr, other.m_ptr); std::swap(m_deleter, other.m_deleter); } // AXIVION DISABLE STYLE AutosarC++19_03-A13.5.5 : See header template <typename T, typename U> inline bool operator==(const unique_ptr<T>& lhs, const unique_ptr<U>& rhs) noexcept { return lhs.get() == rhs.get(); } template <typename T, typename U> inline bool operator!=(const unique_ptr<T>& lhs, const unique_ptr<U>& rhs) noexcept { return !(lhs == rhs); } // AXIVION ENABLE STYLE AutosarC++19_03-A13.5.5 : See header } // namespace cxx } // namespace iox #endif // IOX_HOOFS_CXX_UNIQUE_PTR_INL <|endoftext|>
<commit_before>//===--- ParseGeneric.cpp - Swift Language Parser for Generics ------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Generic Parsing and AST Building // //===----------------------------------------------------------------------===// #include "swift/Parse/Parser.h" #include "swift/AST/DiagnosticsParse.h" #include "swift/Parse/CodeCompletionCallbacks.h" #include "swift/Parse/Lexer.h" using namespace swift; /// parseGenericParameters - Parse a sequence of generic parameters, e.g., /// < T : Comparable, U : Container> along with an optional requires clause. /// /// generic-params: /// '<' generic-param (',' generic-param)* where-clause? '>' /// /// generic-param: /// identifier /// identifier ':' type-identifier /// identifier ':' type-composition /// /// When parsing the generic parameters, this routine establishes a new scope /// and adds those parameters to the scope. ParserResult<GenericParamList> Parser::parseGenericParameters() { // Parse the opening '<'. assert(startsWithLess(Tok) && "Generic parameter list must start with '<'"); return parseGenericParameters(consumeStartingLess()); } ParserResult<GenericParamList> Parser::parseGenericParameters(SourceLoc LAngleLoc) { // Parse the generic parameter list. SmallVector<GenericTypeParamDecl *, 4> GenericParams; bool Invalid = false; do { // Note that we're parsing a declaration. StructureMarkerRAII ParsingDecl(*this, Tok.getLoc(), StructureMarkerKind::Declaration); // Parse attributes. DeclAttributes attributes; if (Tok.hasComment()) attributes.add(new (Context) RawDocCommentAttr(Tok.getCommentRange())); bool foundCCTokenInAttr; parseDeclAttributeList(attributes, foundCCTokenInAttr); // Parse the name of the parameter. Identifier Name; SourceLoc NameLoc; if (parseIdentifier(Name, NameLoc, diag::expected_generics_parameter_name)) { Invalid = true; break; } // Parse the ':' followed by a type. SmallVector<TypeLoc, 1> Inherited; if (Tok.is(tok::colon)) { (void)consumeToken(); ParserResult<TypeRepr> Ty; if (Tok.isAny(tok::identifier, tok::code_complete, tok::kw_protocol, tok::kw_Any)) { Ty = parseType(); } else if (Tok.is(tok::kw_class)) { diagnose(Tok, diag::unexpected_class_constraint); diagnose(Tok, diag::suggest_anyobject) .fixItReplace(Tok.getLoc(), "AnyObject"); consumeToken(); Invalid = true; } else { diagnose(Tok, diag::expected_generics_type_restriction, Name); Invalid = true; } if (Ty.hasCodeCompletion()) return makeParserCodeCompletionStatus(); if (Ty.isNonNull()) Inherited.push_back(Ty.get()); } // We always create generic type parameters with a depth of zero. // Semantic analysis fills in the depth when it processes the generic // parameter list. auto Param = new (Context) GenericTypeParamDecl( CurDeclContext, Name, NameLoc, GenericTypeParamDecl::InvalidDepth, GenericParams.size()); if (!Inherited.empty()) Param->setInherited(Context.AllocateCopy(Inherited)); GenericParams.push_back(Param); // Attach attributes. Param->getAttrs() = attributes; // Add this parameter to the scope. addToScope(Param); // Parse the comma, if the list continues. } while (consumeIf(tok::comma)); // Parse the optional where-clause. SourceLoc WhereLoc; SmallVector<RequirementRepr, 4> Requirements; bool FirstTypeInComplete; if (Tok.is(tok::kw_where) && parseGenericWhereClause(WhereLoc, Requirements, FirstTypeInComplete).isError()) { Invalid = true; } // Parse the closing '>'. SourceLoc RAngleLoc; if (startsWithGreater(Tok)) { RAngleLoc = consumeStartingGreater(); } else { if (!Invalid) { diagnose(Tok, diag::expected_rangle_generics_param); diagnose(LAngleLoc, diag::opening_angle); Invalid = true; } // Skip until we hit the '>'. RAngleLoc = skipUntilGreaterInTypeList(); } if (GenericParams.empty()) return nullptr; return makeParserResult(GenericParamList::create(Context, LAngleLoc, GenericParams, WhereLoc, Requirements, RAngleLoc)); } ParserResult<GenericParamList> Parser::maybeParseGenericParams() { if (!startsWithLess(Tok)) return nullptr; if (!isInSILMode()) return parseGenericParameters(); // In SIL mode, we can have multiple generic parameter lists, with the // first one being the outmost generic parameter list. GenericParamList *gpl = nullptr, *outer_gpl = nullptr; do { gpl = parseGenericParameters().getPtrOrNull(); if (!gpl) return nullptr; if (outer_gpl) gpl->setOuterParameters(outer_gpl); outer_gpl = gpl; } while (startsWithLess(Tok)); return makeParserResult(gpl); } void Parser::diagnoseWhereClauseInGenericParamList(const GenericParamList * GenericParams) { if (GenericParams == nullptr || GenericParams->getWhereLoc().isInvalid()) return; auto WhereRangeInsideBrackets = GenericParams->getWhereClauseSourceRange(); // Move everything immediately following the last generic parameter // as written all the way to the right angle bracket (">") auto LastGenericParam = GenericParams->getParams().back(); auto EndOfLastGenericParam = Lexer::getLocForEndOfToken(SourceMgr, LastGenericParam->getEndLoc()); CharSourceRange RemoveWhereRange { SourceMgr, EndOfLastGenericParam, GenericParams->getRAngleLoc() }; auto WhereCharRange = Lexer::getCharSourceRangeFromSourceRange(SourceMgr, GenericParams->getWhereClauseSourceRange()); SmallString<64> Buffer; llvm::raw_svector_ostream WhereClauseText(Buffer); WhereClauseText << SourceMgr.extractText(Tok.is(tok::kw_where) ? WhereCharRange : RemoveWhereRange); // If, for some reason, there was a where clause in both locations, we're // adding to the list of requirements, so tack on a comma here before // inserting it at the head of the later where clause. if (Tok.is(tok::kw_where)) WhereClauseText << ','; // For Swift 3, keep this warning. const auto Message = Context.isSwiftVersion3() ? diag::swift3_where_inside_brackets : diag::where_inside_brackets; auto Diag = diagnose(WhereRangeInsideBrackets.Start, Message); Diag.fixItRemoveChars(RemoveWhereRange.getStart(), RemoveWhereRange.getEnd()); if (Tok.is(tok::kw_where)) { Diag.fixItReplace(Tok.getLoc(), WhereClauseText.str()); } else { Diag.fixItInsert(Lexer::getLocForEndOfToken(SourceMgr, PreviousLoc), WhereClauseText.str()); } } /// parseGenericWhereClause - Parse a 'where' clause, which places additional /// constraints on generic parameters or types based on them. /// /// where-clause: /// 'where' requirement (',' requirement) * /// /// requirement: /// conformance-requirement /// same-type-requirement /// /// conformance-requirement: /// type-identifier ':' type-identifier /// type-identifier ':' type-composition /// /// same-type-requirement: /// type-identifier '==' type ParserStatus Parser::parseGenericWhereClause( SourceLoc &WhereLoc, SmallVectorImpl<RequirementRepr> &Requirements, bool &FirstTypeInComplete, bool AllowLayoutConstraints) { ParserStatus Status; // Parse the 'where'. WhereLoc = consumeToken(tok::kw_where); FirstTypeInComplete = false; do { // Parse the leading type-identifier. ParserResult<TypeRepr> FirstType = parseTypeIdentifier(); if (FirstType.hasCodeCompletion()) { Status.setHasCodeCompletion(); FirstTypeInComplete = true; } if (FirstType.isNull()) { Status.setIsParseError(); break; } if (Tok.is(tok::colon)) { // A conformance-requirement. SourceLoc ColonLoc = consumeToken(); if (Tok.is(tok::identifier) && getLayoutConstraint(Context.getIdentifier(Tok.getText()), Context) ->isKnownLayout()) { // Parse a layout constraint. auto LayoutName = Context.getIdentifier(Tok.getText()); auto LayoutLoc = consumeToken(); auto LayoutInfo = parseLayoutConstraint(LayoutName); if (!LayoutInfo->isKnownLayout()) { // There was a bug in the layout constraint. Status.setIsParseError(); } auto Layout = LayoutInfo; // Types in SIL mode may contain layout constraints. if (!AllowLayoutConstraints && !isInSILMode()) { diagnose(LayoutLoc, diag::layout_constraints_only_inside_specialize_attr); } else { // Add the layout requirement. Requirements.push_back(RequirementRepr::getLayoutConstraint( FirstType.get(), ColonLoc, LayoutConstraintLoc(Layout, LayoutLoc))); } } else { // Parse the protocol or composition. ParserResult<TypeRepr> Protocol = parseType(); if (Protocol.isNull()) { Status.setIsParseError(); if (Protocol.hasCodeCompletion()) Status.setHasCodeCompletion(); break; } // Add the requirement. Requirements.push_back(RequirementRepr::getTypeConstraint( FirstType.get(), ColonLoc, Protocol.get())); } } else if ((Tok.isAnyOperator() && Tok.getText() == "==") || Tok.is(tok::equal)) { // A same-type-requirement if (Tok.is(tok::equal)) { diagnose(Tok, diag::requires_single_equal) .fixItReplace(SourceRange(Tok.getLoc()), "=="); } SourceLoc EqualLoc = consumeToken(); // Parse the second type. ParserResult<TypeRepr> SecondType = parseType(); if (SecondType.isNull()) { Status.setIsParseError(); if (SecondType.hasCodeCompletion()) Status.setHasCodeCompletion(); break; } // Add the requirement Requirements.push_back(RequirementRepr::getSameType(FirstType.get(), EqualLoc, SecondType.get())); } else { diagnose(Tok, diag::expected_requirement_delim); Status.setIsParseError(); break; } // If there's a comma, keep parsing the list. } while (consumeIf(tok::comma)); if (Requirements.empty()) WhereLoc = SourceLoc(); return Status; } /// Parse a free-standing where clause attached to a declaration, adding it to /// a generic parameter list that may (or may not) already exist. ParserStatus Parser:: parseFreestandingGenericWhereClause(GenericParamList *&genericParams, WhereClauseKind kind) { assert(Tok.is(tok::kw_where) && "Shouldn't call this without a where"); // Push the generic arguments back into a local scope so that references will // find them. Scope S(this, ScopeKind::Generics); if (genericParams) for (auto pd : genericParams->getParams()) addToScope(pd); SmallVector<RequirementRepr, 4> Requirements; if (genericParams) Requirements.append(genericParams->getRequirements().begin(), genericParams->getRequirements().end()); SourceLoc WhereLoc; bool FirstTypeInComplete; auto result = parseGenericWhereClause(WhereLoc, Requirements, FirstTypeInComplete); if (result.shouldStopParsing() || Requirements.empty()) return result; if (!genericParams) diagnose(WhereLoc, diag::where_without_generic_params, unsigned(kind)); else genericParams = GenericParamList::create(Context, genericParams->getLAngleLoc(), genericParams->getParams(), WhereLoc, Requirements, genericParams->getRAngleLoc()); return ParserStatus(); } /// Parse a where clause after a protocol or associated type declaration. ParserStatus Parser::parseProtocolOrAssociatedTypeWhereClause( TrailingWhereClause *&trailingWhere, bool isProtocol) { assert(Tok.is(tok::kw_where) && "Shouldn't call this without a where"); SourceLoc whereLoc; SmallVector<RequirementRepr, 4> requirements; bool firstTypeInComplete; auto whereStatus = parseGenericWhereClause(whereLoc, requirements, firstTypeInComplete); if (whereStatus.isSuccess()) { trailingWhere = TrailingWhereClause::create(Context, whereLoc, requirements); } else if (whereStatus.hasCodeCompletion()) { return whereStatus; } return ParserStatus(); } <commit_msg>Parse: Fix a comment<commit_after>//===--- ParseGeneric.cpp - Swift Language Parser for Generics ------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Generic Parsing and AST Building // //===----------------------------------------------------------------------===// #include "swift/Parse/Parser.h" #include "swift/AST/DiagnosticsParse.h" #include "swift/Parse/CodeCompletionCallbacks.h" #include "swift/Parse/Lexer.h" using namespace swift; /// parseGenericParameters - Parse a sequence of generic parameters, e.g., /// < T : Comparable, U : Container> along with an optional requires clause. /// /// generic-params: /// '<' generic-param (',' generic-param)* where-clause? '>' /// /// generic-param: /// identifier /// identifier ':' type-identifier /// identifier ':' type-composition /// /// When parsing the generic parameters, this routine establishes a new scope /// and adds those parameters to the scope. ParserResult<GenericParamList> Parser::parseGenericParameters() { // Parse the opening '<'. assert(startsWithLess(Tok) && "Generic parameter list must start with '<'"); return parseGenericParameters(consumeStartingLess()); } ParserResult<GenericParamList> Parser::parseGenericParameters(SourceLoc LAngleLoc) { // Parse the generic parameter list. SmallVector<GenericTypeParamDecl *, 4> GenericParams; bool Invalid = false; do { // Note that we're parsing a declaration. StructureMarkerRAII ParsingDecl(*this, Tok.getLoc(), StructureMarkerKind::Declaration); // Parse attributes. DeclAttributes attributes; if (Tok.hasComment()) attributes.add(new (Context) RawDocCommentAttr(Tok.getCommentRange())); bool foundCCTokenInAttr; parseDeclAttributeList(attributes, foundCCTokenInAttr); // Parse the name of the parameter. Identifier Name; SourceLoc NameLoc; if (parseIdentifier(Name, NameLoc, diag::expected_generics_parameter_name)) { Invalid = true; break; } // Parse the ':' followed by a type. SmallVector<TypeLoc, 1> Inherited; if (Tok.is(tok::colon)) { (void)consumeToken(); ParserResult<TypeRepr> Ty; if (Tok.isAny(tok::identifier, tok::code_complete, tok::kw_protocol, tok::kw_Any)) { Ty = parseType(); } else if (Tok.is(tok::kw_class)) { diagnose(Tok, diag::unexpected_class_constraint); diagnose(Tok, diag::suggest_anyobject) .fixItReplace(Tok.getLoc(), "AnyObject"); consumeToken(); Invalid = true; } else { diagnose(Tok, diag::expected_generics_type_restriction, Name); Invalid = true; } if (Ty.hasCodeCompletion()) return makeParserCodeCompletionStatus(); if (Ty.isNonNull()) Inherited.push_back(Ty.get()); } // We always create generic type parameters with an invalid depth. // Semantic analysis fills in the depth when it processes the generic // parameter list. auto Param = new (Context) GenericTypeParamDecl( CurDeclContext, Name, NameLoc, GenericTypeParamDecl::InvalidDepth, GenericParams.size()); if (!Inherited.empty()) Param->setInherited(Context.AllocateCopy(Inherited)); GenericParams.push_back(Param); // Attach attributes. Param->getAttrs() = attributes; // Add this parameter to the scope. addToScope(Param); // Parse the comma, if the list continues. } while (consumeIf(tok::comma)); // Parse the optional where-clause. SourceLoc WhereLoc; SmallVector<RequirementRepr, 4> Requirements; bool FirstTypeInComplete; if (Tok.is(tok::kw_where) && parseGenericWhereClause(WhereLoc, Requirements, FirstTypeInComplete).isError()) { Invalid = true; } // Parse the closing '>'. SourceLoc RAngleLoc; if (startsWithGreater(Tok)) { RAngleLoc = consumeStartingGreater(); } else { if (!Invalid) { diagnose(Tok, diag::expected_rangle_generics_param); diagnose(LAngleLoc, diag::opening_angle); Invalid = true; } // Skip until we hit the '>'. RAngleLoc = skipUntilGreaterInTypeList(); } if (GenericParams.empty()) return nullptr; return makeParserResult(GenericParamList::create(Context, LAngleLoc, GenericParams, WhereLoc, Requirements, RAngleLoc)); } ParserResult<GenericParamList> Parser::maybeParseGenericParams() { if (!startsWithLess(Tok)) return nullptr; if (!isInSILMode()) return parseGenericParameters(); // In SIL mode, we can have multiple generic parameter lists, with the // first one being the outmost generic parameter list. GenericParamList *gpl = nullptr, *outer_gpl = nullptr; do { gpl = parseGenericParameters().getPtrOrNull(); if (!gpl) return nullptr; if (outer_gpl) gpl->setOuterParameters(outer_gpl); outer_gpl = gpl; } while (startsWithLess(Tok)); return makeParserResult(gpl); } void Parser::diagnoseWhereClauseInGenericParamList(const GenericParamList * GenericParams) { if (GenericParams == nullptr || GenericParams->getWhereLoc().isInvalid()) return; auto WhereRangeInsideBrackets = GenericParams->getWhereClauseSourceRange(); // Move everything immediately following the last generic parameter // as written all the way to the right angle bracket (">") auto LastGenericParam = GenericParams->getParams().back(); auto EndOfLastGenericParam = Lexer::getLocForEndOfToken(SourceMgr, LastGenericParam->getEndLoc()); CharSourceRange RemoveWhereRange { SourceMgr, EndOfLastGenericParam, GenericParams->getRAngleLoc() }; auto WhereCharRange = Lexer::getCharSourceRangeFromSourceRange(SourceMgr, GenericParams->getWhereClauseSourceRange()); SmallString<64> Buffer; llvm::raw_svector_ostream WhereClauseText(Buffer); WhereClauseText << SourceMgr.extractText(Tok.is(tok::kw_where) ? WhereCharRange : RemoveWhereRange); // If, for some reason, there was a where clause in both locations, we're // adding to the list of requirements, so tack on a comma here before // inserting it at the head of the later where clause. if (Tok.is(tok::kw_where)) WhereClauseText << ','; // For Swift 3, keep this warning. const auto Message = Context.isSwiftVersion3() ? diag::swift3_where_inside_brackets : diag::where_inside_brackets; auto Diag = diagnose(WhereRangeInsideBrackets.Start, Message); Diag.fixItRemoveChars(RemoveWhereRange.getStart(), RemoveWhereRange.getEnd()); if (Tok.is(tok::kw_where)) { Diag.fixItReplace(Tok.getLoc(), WhereClauseText.str()); } else { Diag.fixItInsert(Lexer::getLocForEndOfToken(SourceMgr, PreviousLoc), WhereClauseText.str()); } } /// parseGenericWhereClause - Parse a 'where' clause, which places additional /// constraints on generic parameters or types based on them. /// /// where-clause: /// 'where' requirement (',' requirement) * /// /// requirement: /// conformance-requirement /// same-type-requirement /// /// conformance-requirement: /// type-identifier ':' type-identifier /// type-identifier ':' type-composition /// /// same-type-requirement: /// type-identifier '==' type ParserStatus Parser::parseGenericWhereClause( SourceLoc &WhereLoc, SmallVectorImpl<RequirementRepr> &Requirements, bool &FirstTypeInComplete, bool AllowLayoutConstraints) { ParserStatus Status; // Parse the 'where'. WhereLoc = consumeToken(tok::kw_where); FirstTypeInComplete = false; do { // Parse the leading type-identifier. ParserResult<TypeRepr> FirstType = parseTypeIdentifier(); if (FirstType.hasCodeCompletion()) { Status.setHasCodeCompletion(); FirstTypeInComplete = true; } if (FirstType.isNull()) { Status.setIsParseError(); break; } if (Tok.is(tok::colon)) { // A conformance-requirement. SourceLoc ColonLoc = consumeToken(); if (Tok.is(tok::identifier) && getLayoutConstraint(Context.getIdentifier(Tok.getText()), Context) ->isKnownLayout()) { // Parse a layout constraint. auto LayoutName = Context.getIdentifier(Tok.getText()); auto LayoutLoc = consumeToken(); auto LayoutInfo = parseLayoutConstraint(LayoutName); if (!LayoutInfo->isKnownLayout()) { // There was a bug in the layout constraint. Status.setIsParseError(); } auto Layout = LayoutInfo; // Types in SIL mode may contain layout constraints. if (!AllowLayoutConstraints && !isInSILMode()) { diagnose(LayoutLoc, diag::layout_constraints_only_inside_specialize_attr); } else { // Add the layout requirement. Requirements.push_back(RequirementRepr::getLayoutConstraint( FirstType.get(), ColonLoc, LayoutConstraintLoc(Layout, LayoutLoc))); } } else { // Parse the protocol or composition. ParserResult<TypeRepr> Protocol = parseType(); if (Protocol.isNull()) { Status.setIsParseError(); if (Protocol.hasCodeCompletion()) Status.setHasCodeCompletion(); break; } // Add the requirement. Requirements.push_back(RequirementRepr::getTypeConstraint( FirstType.get(), ColonLoc, Protocol.get())); } } else if ((Tok.isAnyOperator() && Tok.getText() == "==") || Tok.is(tok::equal)) { // A same-type-requirement if (Tok.is(tok::equal)) { diagnose(Tok, diag::requires_single_equal) .fixItReplace(SourceRange(Tok.getLoc()), "=="); } SourceLoc EqualLoc = consumeToken(); // Parse the second type. ParserResult<TypeRepr> SecondType = parseType(); if (SecondType.isNull()) { Status.setIsParseError(); if (SecondType.hasCodeCompletion()) Status.setHasCodeCompletion(); break; } // Add the requirement Requirements.push_back(RequirementRepr::getSameType(FirstType.get(), EqualLoc, SecondType.get())); } else { diagnose(Tok, diag::expected_requirement_delim); Status.setIsParseError(); break; } // If there's a comma, keep parsing the list. } while (consumeIf(tok::comma)); if (Requirements.empty()) WhereLoc = SourceLoc(); return Status; } /// Parse a free-standing where clause attached to a declaration, adding it to /// a generic parameter list that may (or may not) already exist. ParserStatus Parser:: parseFreestandingGenericWhereClause(GenericParamList *&genericParams, WhereClauseKind kind) { assert(Tok.is(tok::kw_where) && "Shouldn't call this without a where"); // Push the generic arguments back into a local scope so that references will // find them. Scope S(this, ScopeKind::Generics); if (genericParams) for (auto pd : genericParams->getParams()) addToScope(pd); SmallVector<RequirementRepr, 4> Requirements; if (genericParams) Requirements.append(genericParams->getRequirements().begin(), genericParams->getRequirements().end()); SourceLoc WhereLoc; bool FirstTypeInComplete; auto result = parseGenericWhereClause(WhereLoc, Requirements, FirstTypeInComplete); if (result.shouldStopParsing() || Requirements.empty()) return result; if (!genericParams) diagnose(WhereLoc, diag::where_without_generic_params, unsigned(kind)); else genericParams = GenericParamList::create(Context, genericParams->getLAngleLoc(), genericParams->getParams(), WhereLoc, Requirements, genericParams->getRAngleLoc()); return ParserStatus(); } /// Parse a where clause after a protocol or associated type declaration. ParserStatus Parser::parseProtocolOrAssociatedTypeWhereClause( TrailingWhereClause *&trailingWhere, bool isProtocol) { assert(Tok.is(tok::kw_where) && "Shouldn't call this without a where"); SourceLoc whereLoc; SmallVector<RequirementRepr, 4> requirements; bool firstTypeInComplete; auto whereStatus = parseGenericWhereClause(whereLoc, requirements, firstTypeInComplete); if (whereStatus.isSuccess()) { trailingWhere = TrailingWhereClause::create(Context, whereLoc, requirements); } else if (whereStatus.hasCodeCompletion()) { return whereStatus; } return ParserStatus(); } <|endoftext|>
<commit_before>// This example uses an Adafruit Huzzah ESP8266 // to connect to shiftr.io. // // You can check on your device after a successful // connection here: https://shiftr.io/try. // // by Joël Gähwiler // https://github.com/256dpi/arduino-mqtt #include <WiFi.h> #include <Wire.h> #include <SPI.h> #include <Adafruit_GFX.h> #include <MQTT.h> #include "mqtt-controller.h" #include "debug.h" #include "secret.h" WiFiClient net; MQTTClient client; unsigned long lastMillis = 0; void connect() { DEBUG("MQTT: Init Started"); DEBUG("MQTT: checking WiFi..."); while (WiFi.status() != WL_CONNECTED) { delay(1000); } DEBUG("MQTT: WiFi connected"); DEBUG("MQTT: connecting..."); while (!client.connect("arduino", "try", "try")) { delay(1000); } DEBUG("MQTT: connected to MQTT server"); client.subscribe("/hello"); } void messageReceived(String &topic, String &payload) { DEBUG("incoming: " + topic + " - " + payload); } void mqtt_init() { WiFi.begin(WIFI_SSID, WIFI_PSK); // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported by Arduino. // You need to set the IP address directly. client.begin(MQTT_HOST, net); client.onMessage(messageReceived); connect(); } void mqtt_tick() { client.loop(); delay(10); // <- fixes some issues with WiFi stability if (!client.connected()) { connect(); } // publish a message roughly every second. if (millis() - lastMillis > 1000) { lastMillis = millis(); client.publish("/hello", "world"); } } <commit_msg>Add battery library<commit_after>// This example uses an Adafruit Huzzah ESP8266 // to connect to shiftr.io. // // You can check on your device after a successful // connection here: https://shiftr.io/try. // // by Joël Gähwiler // https://github.com/256dpi/arduino-mqtt #include <WiFi.h> #include <Wire.h> #include <SPI.h> #include <Adafruit_GFX.h> #include <MQTT.h> #include <Battery.h> #include "mqtt-controller.h" #include "debug.h" #include "secret.h" WiFiClient net; MQTTClient client; Battery battery(3000, 4200, A13); unsigned long lastMillis = 0; void connect() { DEBUG("MQTT: Init Started"); DEBUG("MQTT: checking WiFi..."); while (WiFi.status() != WL_CONNECTED) { delay(1000); } DEBUG("MQTT: WiFi connected"); DEBUG("MQTT: connecting..."); while (!client.connect("arduino", "try", "try")) { delay(1000); } DEBUG("MQTT: connected to MQTT server"); DEBUG("BATTERY: Setting Up..."); battery.begin(3300, 2.0, &sigmoidal); // TODO something to identify we booted client.publish("/hello", ""); } void messageReceived(String &topic, String &payload) { DEBUG("incoming: " + topic + " - " + payload); } void mqtt_init() { WiFi.begin(WIFI_SSID, WIFI_PSK); // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported by Arduino. // You need to set the IP address directly. client.begin(MQTT_HOST, net); client.onMessage(messageReceived); connect(); } void mqtt_tick() { client.loop(); delay(10); // <- fixes some issues with WiFi stability if (!client.connected()) { connect(); } // publish a message roughly every second. if (millis() - lastMillis > 1000) { lastMillis = millis(); client.publish("/hello", "world"); } } <|endoftext|>
<commit_before>//=========================================== // Lumina-DE source code // Copyright (c) 2014, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "ScriptDialog.h" #include "ui_ScriptDialog.h" //=========== // PUBLIC //=========== ScriptDialog::ScriptDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ScriptDialog){ ui->setupUi(this); ok = false; connect(ui->line_name, SIGNAL(textEdited(QString)), this, SLOT(checkItems()) ); connect(ui->line_exec, SIGNAL(textEdited(QString)), this, SLOT(checkItems()) ); connect(ui->line_icon, SIGNAL(textEdited(QString)), this, SLOT(checkItems()) ); checkItems(true); } ScriptDialog::~ScriptDialog(){ } //Main interaction functions bool ScriptDialog::isValid(){ return ok; } QString ScriptDialog::icon(){ return ui->line_icon->text(); } QString ScriptDialog::name(){ return ui->line_name->text(); } QString ScriptDialog::command(){ return ui->line_exec->text(); } //============== // PRIVATE SLOTS //============== void ScriptDialog::on_pushApply_clicked(){ ok = true; this->close(); } void ScriptDialog::on_pushCancel_clicked(){ ok = false; this->close(); } void ScriptDialog::on_tool_getexec_clicked(){ QString file = QFileDialog::getOpenFileName( this, tr("Select a menu script"), QDir::homePath() ); if(file.isEmpty()){ return; } //cancelled ui->line_exec->setText(file); checkItems(); } void ScriptDialog::on_tool_geticon_clicked(){ QString file = QFileDialog::getOpenFileName( this, tr("Select an icon file"), QDir::homePath() ); if(file.isEmpty()){ return; } //cancelled ui->line_icon->setText(file); checkItems(); } void ScriptDialog::checkItems(bool firstrun){ if(firstrun){ ui->line_name->setFocus(); ui->label_sample->setPixmap( LXDG::findIcon("text-x-script","").pixmap(32,32) ); ui->tool_geticon->setIcon( LXDG::findIcon("system-search","") ); ui->tool_getexec->setIcon( LXDG::findIcon("system-search","") ); } //Update the icon sample if needed if(icon()!=ui->label_sample->whatsThis()){ ui->label_sample->setPixmap( LXDG::findIcon(icon(),"text-x-script").pixmap(32,32) ); ui->label_sample->setWhatsThis(icon()); } bool good = true; if(name().isEmpty()){ good = false; ui->line_name->setStyleSheet("color: red;"); } else{ ui->line_name->setStyleSheet(""); } QString cmd = command().section(" ",0,0).simplified(); if( cmd.isEmpty() || !LUtils::isValidBinary(cmd) ){ good = false; ui->line_exec->setStyleSheet("color: red;"); } else{ ui->line_exec->setStyleSheet(""); } ui->pushApply->setEnabled(good); } <commit_msg>Ensure that lumina-config defaults to looking in the system-installed scripts directory for menu scripts.<commit_after>//=========================================== // Lumina-DE source code // Copyright (c) 2014, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "ScriptDialog.h" #include "ui_ScriptDialog.h" //=========== // PUBLIC //=========== ScriptDialog::ScriptDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ScriptDialog){ ui->setupUi(this); ok = false; connect(ui->line_name, SIGNAL(textEdited(QString)), this, SLOT(checkItems()) ); connect(ui->line_exec, SIGNAL(textEdited(QString)), this, SLOT(checkItems()) ); connect(ui->line_icon, SIGNAL(textEdited(QString)), this, SLOT(checkItems()) ); checkItems(true); } ScriptDialog::~ScriptDialog(){ } //Main interaction functions bool ScriptDialog::isValid(){ return ok; } QString ScriptDialog::icon(){ return ui->line_icon->text(); } QString ScriptDialog::name(){ return ui->line_name->text(); } QString ScriptDialog::command(){ return ui->line_exec->text(); } //============== // PRIVATE SLOTS //============== void ScriptDialog::on_pushApply_clicked(){ ok = true; this->close(); } void ScriptDialog::on_pushCancel_clicked(){ ok = false; this->close(); } void ScriptDialog::on_tool_getexec_clicked(){ QString file = QFileDialog::getOpenFileName( this, tr("Select a menu script"), LOS::LuminaShare()+"/menu-scripts/" ); if(file.isEmpty()){ return; } //cancelled ui->line_exec->setText(file); checkItems(); } void ScriptDialog::on_tool_geticon_clicked(){ QString file = QFileDialog::getOpenFileName( this, tr("Select an icon file"), QDir::homePath() ); if(file.isEmpty()){ return; } //cancelled ui->line_icon->setText(file); checkItems(); } void ScriptDialog::checkItems(bool firstrun){ if(firstrun){ ui->line_name->setFocus(); ui->label_sample->setPixmap( LXDG::findIcon("text-x-script","").pixmap(32,32) ); ui->tool_geticon->setIcon( LXDG::findIcon("system-search","") ); ui->tool_getexec->setIcon( LXDG::findIcon("system-search","") ); } //Update the icon sample if needed if(icon()!=ui->label_sample->whatsThis()){ ui->label_sample->setPixmap( LXDG::findIcon(icon(),"text-x-script").pixmap(32,32) ); ui->label_sample->setWhatsThis(icon()); } bool good = true; if(name().isEmpty()){ good = false; ui->line_name->setStyleSheet("color: red;"); } else{ ui->line_name->setStyleSheet(""); } QString cmd = command().section(" ",0,0).simplified(); if( cmd.isEmpty() || !LUtils::isValidBinary(cmd) ){ good = false; ui->line_exec->setStyleSheet("color: red;"); } else{ ui->line_exec->setStyleSheet(""); } ui->pushApply->setEnabled(good); } <|endoftext|>
<commit_before>/* Copyright (c) 2010-2017, Delft University of Technology * All rigths reserved * * This file is part of the Tudat. Redistribution and use in source and * binary forms, with or without modification, are permitted exclusively * under the terms of the Modified BSD license. You should have received * a copy of the license with this file. If not, please or visit: * http://tudat.tudelft.nl/LICENSE. */ #define BOOST_TEST_MAIN #include "Tudat/JsonInterface/UnitTests/unitTestSupport.h" #include "Tudat/JsonInterface/Support/valueAccess.h" #include "Tudat/JsonInterface/Support/valueConversions.h" #include "Tudat/JsonInterface/Support/deserialization.h" namespace tudat { namespace unit_tests { #define INPUT( filename ) \ ( json_interface::inputDirectory( ) / boost::filesystem::path( __FILE__ ).stem( ) / filename ).string( ) BOOST_AUTO_TEST_SUITE( test_json_deserialization ) // Test 1: value access BOOST_AUTO_TEST_CASE( test_json_valueAccess ) { using namespace json_interface; const nlohmann::json dog = parseJSONFile( INPUT( "valueAccess" ) ); // Numbers BOOST_CHECK_EQUAL( getValue< unsigned int >( dog, "age" ), 11 ); BOOST_CHECK_EQUAL( getValue< int >( dog, "age" ), 11 ); BOOST_CHECK_EQUAL( getValue< double >( dog, "mass" ), 19.5 ); BOOST_CHECK_EQUAL( getValue< float >( dog, "mass" ), 19.5 ); BOOST_CHECK_EQUAL( getValue< long double >( dog, "mass" ), 19.5 ); // Strings BOOST_CHECK_EQUAL( getValue< std::string >( dog, "name" ), "Bumper" ); // Arrays const std::vector< std::string > hobbies = { "eat", "sleep" }; const std::string hobbiesKey = "hobbies"; BOOST_CHECK( getValue< std::vector< std::string > >( dog, hobbiesKey ) == hobbies ); BOOST_CHECK_EQUAL( getValue< std::string >( dog, hobbiesKey / 0 ), hobbies.at( 0 ) ); BOOST_CHECK_EQUAL( getValue< std::string >( dog, hobbiesKey / 1 ), hobbies.at( 1 ) ); // Context: one level const nlohmann::json enemy = getValue< std::vector< nlohmann::json > >( dog, "enemies" ).front( ); BOOST_CHECK_EQUAL( getRootObject( enemy ), dog ); BOOST_CHECK_EQUAL( getValue< double >( enemy, "mass" ), 2.6 ); BOOST_CHECK_EQUAL( getValue< double >( enemy, SpecialKeys::up / SpecialKeys::up / "mass" ), 19.5 ); BOOST_CHECK_EQUAL( getValue< double >( enemy, SpecialKeys::root / "mass" ), 19.5 ); // Context: several levels const nlohmann::json valencia = getValue< nlohmann::json >( enemy, std::string( "mother" ) / "birthplace" / "city" ); BOOST_CHECK_EQUAL( valencia.at( "name" ), "Valencia" ); BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::root / "mass" ), 19.5 ); BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up / SpecialKeys::up / SpecialKeys::up / SpecialKeys::up / SpecialKeys::up / "mass" ), 19.5 ); BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up / "continent" / "temperatureRange" / 0 ), -15 ); BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up / "continent" / "temperatureRange" / 1 ), 45 ); // Eigen const Eigen::Matrix3d matrix = getValue< Eigen::Matrix3d >( dog, "orientation" ); const Eigen::Matrix3d matrix2 = ( Eigen::Matrix3d( ) << 1.0, 0.0, 0.0, 0.0, 2.0, 1.0, 0.0, 3.0, -1.0 ).finished( ); BOOST_CHECK_EQUAL( matrix, matrix2 ); // Map with non-char keys const std::map< double, std::string > food = getValue< std::map< double, std::string > >( dog, "food" ); const std::map< double, std::string > food2 = { { 7, "feed" }, { 12, "meat" }, { 15, "feed" }, { 19, "feed" } }; BOOST_CHECK( food == food2 ); } // Test 2: modular BOOST_AUTO_TEST_CASE( test_json_modular ) { using namespace json_interface; const nlohmann::json modular = getDeserializedJSON( getPathForJSONFile( INPUT( "modular" ) ) ); nlohmann::json simulation; simulation[ "bodies" ] = R"( { "Earth": { "useDefaultSettings": true }, "satellite": { "mass": 500 } } )"_json; simulation[ "propagators" ] = R"( [ { "centralBodies": [ "Earth" ], "bodiesToPropagate": [ "satellite" ] } ] )"_json; simulation[ "integrator" ] = R"( { "type": "rungeKutta4", "stepSize": 30 } )"_json; simulation[ "export" ] = R"( [ { "variables": [ { "type": "independent" } ] }, { "variables": [ { "body": "satellite", "dependentVariableType": "relativePosition", "relatieToBody": "Earth" }, { "body": "satellite", "dependentVariableType": "relativeVelocity", "relatieToBody": "Earth" } ] } ] )"_json; simulation[ "export" ][ 0 ][ "file" ] = ( boost::filesystem::path( "export" ) / ".." / "outputs" / "epochs.txt" ).string( ); simulation[ "export" ][ 1 ][ "file" ] = ( boost::filesystem::path( "export" ) / ".." / "states.txt" ).string( ); BOOST_CHECK_EQUAL( modular, simulation ); } // Test 3: mergeable BOOST_AUTO_TEST_CASE( test_json_mergeable ) { using namespace json_interface; using namespace boost::filesystem; const nlohmann::json merged1 = getDeserializedJSON( getPathForJSONFile( INPUT( ( path( "mergeable" ) / "inputs" / "merge1" ).string( ) ) ) ); const nlohmann::json manual1 = R"( { "type": "rungeKutta4", "stepSize": 20 } )"_json; BOOST_CHECK_EQUAL( merged1, manual1 ); const nlohmann::json merged2 = getDeserializedJSON( getPathForJSONFile( INPUT( ( path( "mergeable" ) / "inputs" / "merge2" ).string( ) ) ) ); const nlohmann::json manual2 = R"( { "integrator": { "type": "rungeKutta4", "stepSize": 20, "initialTimes": [ 0, 86400 ] } } )"_json; BOOST_CHECK_EQUAL( merged2, manual2 ); const nlohmann::json merged3 = getDeserializedJSON( getPathForJSONFile( INPUT( ( path( "mergeable" ) / "inputs" / "merge3" ).string( ) ) ) ); const nlohmann::json manual3 = R"( { "integrator": { "type": "rungeKutta4", "stepSize": 20, "initialTimes": [ 0, 43200, 86400 ] }, "spice": { "useStandardKernels": true, "preloadEpehemeris": false } } )"_json; BOOST_CHECK_EQUAL( merged3, manual3 ); } BOOST_AUTO_TEST_SUITE_END( ) } // namespace unit_tests } // namespace tudat <commit_msg>Fix path difference in unit test for windows.<commit_after>/* Copyright (c) 2010-2017, Delft University of Technology * All rigths reserved * * This file is part of the Tudat. Redistribution and use in source and * binary forms, with or without modification, are permitted exclusively * under the terms of the Modified BSD license. You should have received * a copy of the license with this file. If not, please or visit: * http://tudat.tudelft.nl/LICENSE. */ #define BOOST_TEST_MAIN #include "Tudat/JsonInterface/UnitTests/unitTestSupport.h" #include "Tudat/JsonInterface/Support/valueAccess.h" #include "Tudat/JsonInterface/Support/valueConversions.h" #include "Tudat/JsonInterface/Support/deserialization.h" namespace tudat { namespace unit_tests { #define INPUT( filename ) \ ( json_interface::inputDirectory( ) / boost::filesystem::path( __FILE__ ).stem( ) / filename ).string( ) BOOST_AUTO_TEST_SUITE( test_json_deserialization ) // Test 1: value access BOOST_AUTO_TEST_CASE( test_json_valueAccess ) { using namespace json_interface; const nlohmann::json dog = parseJSONFile( INPUT( "valueAccess" ) ); // Numbers BOOST_CHECK_EQUAL( getValue< unsigned int >( dog, "age" ), 11 ); BOOST_CHECK_EQUAL( getValue< int >( dog, "age" ), 11 ); BOOST_CHECK_EQUAL( getValue< double >( dog, "mass" ), 19.5 ); BOOST_CHECK_EQUAL( getValue< float >( dog, "mass" ), 19.5 ); BOOST_CHECK_EQUAL( getValue< long double >( dog, "mass" ), 19.5 ); // Strings BOOST_CHECK_EQUAL( getValue< std::string >( dog, "name" ), "Bumper" ); // Arrays const std::vector< std::string > hobbies = { "eat", "sleep" }; const std::string hobbiesKey = "hobbies"; BOOST_CHECK( getValue< std::vector< std::string > >( dog, hobbiesKey ) == hobbies ); BOOST_CHECK_EQUAL( getValue< std::string >( dog, hobbiesKey / 0 ), hobbies.at( 0 ) ); BOOST_CHECK_EQUAL( getValue< std::string >( dog, hobbiesKey / 1 ), hobbies.at( 1 ) ); // Context: one level const nlohmann::json enemy = getValue< std::vector< nlohmann::json > >( dog, "enemies" ).front( ); BOOST_CHECK_EQUAL( getRootObject( enemy ), dog ); BOOST_CHECK_EQUAL( getValue< double >( enemy, "mass" ), 2.6 ); BOOST_CHECK_EQUAL( getValue< double >( enemy, SpecialKeys::up / SpecialKeys::up / "mass" ), 19.5 ); BOOST_CHECK_EQUAL( getValue< double >( enemy, SpecialKeys::root / "mass" ), 19.5 ); // Context: several levels const nlohmann::json valencia = getValue< nlohmann::json >( enemy, std::string( "mother" ) / "birthplace" / "city" ); BOOST_CHECK_EQUAL( valencia.at( "name" ), "Valencia" ); BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::root / "mass" ), 19.5 ); BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up / SpecialKeys::up / SpecialKeys::up / SpecialKeys::up / SpecialKeys::up / "mass" ), 19.5 ); BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up / "continent" / "temperatureRange" / 0 ), -15 ); BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up / "continent" / "temperatureRange" / 1 ), 45 ); // Eigen const Eigen::Matrix3d matrix = getValue< Eigen::Matrix3d >( dog, "orientation" ); const Eigen::Matrix3d matrix2 = ( Eigen::Matrix3d( ) << 1.0, 0.0, 0.0, 0.0, 2.0, 1.0, 0.0, 3.0, -1.0 ).finished( ); BOOST_CHECK_EQUAL( matrix, matrix2 ); // Map with non-char keys const std::map< double, std::string > food = getValue< std::map< double, std::string > >( dog, "food" ); const std::map< double, std::string > food2 = { { 7, "feed" }, { 12, "meat" }, { 15, "feed" }, { 19, "feed" } }; BOOST_CHECK( food == food2 ); } // Test 2: modular BOOST_AUTO_TEST_CASE( test_json_modular ) { using namespace json_interface; const nlohmann::json modular = getDeserializedJSON( getPathForJSONFile( INPUT( "modular" ) ) ); nlohmann::json simulation; simulation[ "bodies" ] = R"( { "Earth": { "useDefaultSettings": true }, "satellite": { "mass": 500 } } )"_json; simulation[ "propagators" ] = R"( [ { "centralBodies": [ "Earth" ], "bodiesToPropagate": [ "satellite" ] } ] )"_json; simulation[ "integrator" ] = R"( { "type": "rungeKutta4", "stepSize": 30 } )"_json; simulation[ "export" ] = R"( [ { "variables": [ { "type": "independent" } ] }, { "variables": [ { "body": "satellite", "dependentVariableType": "relativePosition", "relatieToBody": "Earth" }, { "body": "satellite", "dependentVariableType": "relativeVelocity", "relatieToBody": "Earth" } ] } ] )"_json; simulation[ "export" ][ 0 ][ "file" ] = ( boost::filesystem::path( "export" ) / "../outputs/epochs.txt" ).string( ); simulation[ "export" ][ 1 ][ "file" ] = ( boost::filesystem::path( "export" ) / "../states.txt" ).string( ); BOOST_CHECK_EQUAL( modular, simulation ); } // Test 3: mergeable BOOST_AUTO_TEST_CASE( test_json_mergeable ) { using namespace json_interface; using namespace boost::filesystem; const nlohmann::json merged1 = getDeserializedJSON( getPathForJSONFile( INPUT( ( path( "mergeable" ) / "inputs" / "merge1" ).string( ) ) ) ); const nlohmann::json manual1 = R"( { "type": "rungeKutta4", "stepSize": 20 } )"_json; BOOST_CHECK_EQUAL( merged1, manual1 ); const nlohmann::json merged2 = getDeserializedJSON( getPathForJSONFile( INPUT( ( path( "mergeable" ) / "inputs" / "merge2" ).string( ) ) ) ); const nlohmann::json manual2 = R"( { "integrator": { "type": "rungeKutta4", "stepSize": 20, "initialTimes": [ 0, 86400 ] } } )"_json; BOOST_CHECK_EQUAL( merged2, manual2 ); const nlohmann::json merged3 = getDeserializedJSON( getPathForJSONFile( INPUT( ( path( "mergeable" ) / "inputs" / "merge3" ).string( ) ) ) ); const nlohmann::json manual3 = R"( { "integrator": { "type": "rungeKutta4", "stepSize": 20, "initialTimes": [ 0, 43200, 86400 ] }, "spice": { "useStandardKernels": true, "preloadEpehemeris": false } } )"_json; BOOST_CHECK_EQUAL( merged3, manual3 ); } BOOST_AUTO_TEST_SUITE_END( ) } // namespace unit_tests } // namespace tudat <|endoftext|>
<commit_before>/* * Author: Brendan Le Foll <[email protected]> * Copyright (c) 2014 Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "gpio.h" #include "types.hpp" #include <stdexcept> #if defined(SWIGJAVASCRIPT) #if NODE_MODULE_VERSION >= 0x000D #include <uv.h> #endif #endif namespace mraa { // These enums must match the enums in gpio.h /** * Gpio Output modes */ typedef enum { MODE_STRONG = 0, /**< Default. Strong High and Low */ MODE_PULLUP = 1, /**< Interupt on rising & falling */ MODE_PULLDOWN = 2, /**< Interupt on rising only */ MODE_HIZ = 3 /**< Interupt on falling only */ } Mode; /** * Gpio Direction options */ typedef enum { DIR_OUT = 0, /**< Output. A Mode can also be set */ DIR_IN = 1, /**< Input */ DIR_OUT_HIGH = 2, /**< Output. Init High */ DIR_OUT_LOW = 3 /**< Output. Init Low */ } Dir; /** * Gpio Edge types for interupts */ typedef enum { EDGE_NONE = 0, /**< No interrupt on Gpio */ EDGE_BOTH = 1, /**< Interupt on rising & falling */ EDGE_RISING = 2, /**< Interupt on rising only */ EDGE_FALLING = 3 /**< Interupt on falling only */ } Edge; #if defined(SWIGJAVA) class IsrCallback { public: virtual ~IsrCallback() { } virtual void run() { /* empty, overloaded in Java*/ } private: }; void generic_isr_callback(void* data) { IsrCallback* callback = (IsrCallback*) data; callback->run(); } #endif /** * @brief API to General Purpose IO * * This file defines the gpio interface for libmraa * * @snippet Blink-IO.cpp Interesting */ class Gpio { public: /** * Instanciates a Gpio object * * @param pin pin number to use * @param owner (optional) Set pin owner, default behaviour is to 'own' * the pin if we exported it. This means we will close it on destruct. * Otherwise it will get left open. This is only valid in sysfs use * cases * @param raw (optional) Raw pins will use gpiolibs pin numbering from * the kernel module. Note that you will not get any muxers set up for * you so this may not always work as expected. */ Gpio(int pin, bool owner = true, bool raw = false) { if (raw) { m_gpio = mraa_gpio_init_raw(pin); } else { m_gpio = mraa_gpio_init(pin); } if (m_gpio == NULL) { throw std::invalid_argument("Invalid GPIO pin specified"); } if (!owner) { mraa_gpio_owner(m_gpio, 0); } } /** * Gpio object destructor, this will only unexport the gpio if we where * the owner */ ~Gpio() { mraa_gpio_close(m_gpio); } /** * Set the edge mode for ISR * * @param mode The edge mode to set * @return Result of operation */ Result edge(Edge mode) { return (Result) mraa_gpio_edge_mode(m_gpio, (mraa_gpio_edge_t) mode); } #if defined(SWIGPYTHON) Result isr(Edge mode, PyObject* pyfunc, PyObject* args) { return (Result) mraa_gpio_isr(m_gpio, (mraa_gpio_edge_t) mode, (void (*) (void*)) pyfunc, (void*) args); } #elif defined(SWIGJAVASCRIPT) static void v8isr(uv_work_t* req, int status) { mraa::Gpio* This = (mraa::Gpio*) req->data; int argc = 1; v8::Local<v8::Value> argv[] = { SWIGV8_INTEGER_NEW(-1) }; #if NODE_MODULE_VERSION >= 0x000D v8::Local<v8::Function> f = v8::Local<v8::Function>::New(v8::Isolate::GetCurrent(), This->m_v8isr); f->Call(SWIGV8_CURRENT_CONTEXT()->Global(), argc, argv); #else This->m_v8isr->Call(SWIGV8_CURRENT_CONTEXT()->Global(), argc, argv); #endif delete req; } static void nop(uv_work_t* req) { // Do nothing. } static void uvwork(void* ctx) { uv_work_t* req = new uv_work_t; req->data = ctx; uv_queue_work(uv_default_loop(), req, nop, v8isr); } Result isr(Edge mode, v8::Handle<v8::Function> func) { #if NODE_MODULE_VERSION >= 0x000D m_v8isr.Reset(v8::Isolate::GetCurrent(), func); #else m_v8isr = v8::Persistent<v8::Function>::New(func); #endif return (Result) mraa_gpio_isr(m_gpio, (mraa_gpio_edge_t) mode, &uvwork, this); } #elif defined(SWIGJAVA) Result isr(Edge mode, IsrCallback* cb, void* args) { return (Result) mraa_gpio_isr(m_gpio, (mraa_gpio_edge_t) mode, generic_isr_callback, cb); } #else /** * Sets a callback to be called when pin value changes * * @param mode The edge mode to set * @param fptr Function pointer to function to be called when interupt is * triggered * @param args Arguments passed to the interrupt handler (fptr) * @return Result of operation */ Result isr(Edge mode, void (*fptr)(void*), void* args) { return (Result) mraa_gpio_isr(m_gpio, (mraa_gpio_edge_t) mode, fptr, args); } #endif /** * Exits callback - this call will not kill the isr thread immediatly * but only when it is out of it's critical section * * @return Result of operation */ Result isrExit() { #if defined(SWIGJAVASCRIPT) #if NODE_MODULE_VERSION >= 0x000D m_v8isr.Reset(); #else m_v8isr.Dispose(); m_v8isr.Clear(); #endif #endif return (Result) mraa_gpio_isr_exit(m_gpio); } /** * Change Gpio mode * * @param mode The mode to change the gpio into * @return Result of operation */ Result mode(Mode mode) { return (Result )mraa_gpio_mode(m_gpio, (mraa_gpio_mode_t) mode); } /** * Change Gpio direction * * @param dir The direction to change the gpio into * @return Result of operation */ Result dir(Dir dir) { return (Result )mraa_gpio_dir(m_gpio, (mraa_gpio_dir_t) dir); } /** * Read value from Gpio * * @return Gpio value */ int read() { return mraa_gpio_read(m_gpio); } /** * Write value to Gpio * * @param value Value to write to Gpio * @return Result of operation */ Result write(int value) { return (Result) mraa_gpio_write(m_gpio, value); } /** * Enable use of mmap i/o if available. * * @param enable true to use mmap * @return Result of operation */ Result useMmap(bool enable) { return (Result) mraa_gpio_use_mmaped(m_gpio, (mraa_boolean_t) enable); } /** * Get pin number of Gpio. If raw param is True will return the * number as used within sysfs. Invalid will return -1. * * @param raw (optional) get the raw gpio number. * @return Pin number */ int getPin(bool raw = false) { if (raw) { return mraa_gpio_get_pin_raw(m_gpio); } return mraa_gpio_get_pin(m_gpio); } private: mraa_gpio_context m_gpio; #if defined(SWIGJAVASCRIPT) v8::Persistent<v8::Function> m_v8isr; #endif }; } <commit_msg>gpio.hpp: remove unused args parameter from Java isr method<commit_after>/* * Author: Brendan Le Foll <[email protected]> * Copyright (c) 2014 Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "gpio.h" #include "types.hpp" #include <stdexcept> #if defined(SWIGJAVASCRIPT) #if NODE_MODULE_VERSION >= 0x000D #include <uv.h> #endif #endif namespace mraa { // These enums must match the enums in gpio.h /** * Gpio Output modes */ typedef enum { MODE_STRONG = 0, /**< Default. Strong High and Low */ MODE_PULLUP = 1, /**< Interupt on rising & falling */ MODE_PULLDOWN = 2, /**< Interupt on rising only */ MODE_HIZ = 3 /**< Interupt on falling only */ } Mode; /** * Gpio Direction options */ typedef enum { DIR_OUT = 0, /**< Output. A Mode can also be set */ DIR_IN = 1, /**< Input */ DIR_OUT_HIGH = 2, /**< Output. Init High */ DIR_OUT_LOW = 3 /**< Output. Init Low */ } Dir; /** * Gpio Edge types for interupts */ typedef enum { EDGE_NONE = 0, /**< No interrupt on Gpio */ EDGE_BOTH = 1, /**< Interupt on rising & falling */ EDGE_RISING = 2, /**< Interupt on rising only */ EDGE_FALLING = 3 /**< Interupt on falling only */ } Edge; #if defined(SWIGJAVA) class IsrCallback { friend class Gpio; public: virtual ~IsrCallback() { } virtual void run() { /* empty, overloaded in Java*/ } protected: static void generic_isr_callback(void* data) { IsrCallback* callback = (IsrCallback*) data; callback->run(); } }; #endif /** * @brief API to General Purpose IO * * This file defines the gpio interface for libmraa * * @snippet Blink-IO.cpp Interesting */ class Gpio { public: /** * Instanciates a Gpio object * * @param pin pin number to use * @param owner (optional) Set pin owner, default behaviour is to 'own' * the pin if we exported it. This means we will close it on destruct. * Otherwise it will get left open. This is only valid in sysfs use * cases * @param raw (optional) Raw pins will use gpiolibs pin numbering from * the kernel module. Note that you will not get any muxers set up for * you so this may not always work as expected. */ Gpio(int pin, bool owner = true, bool raw = false) { if (raw) { m_gpio = mraa_gpio_init_raw(pin); } else { m_gpio = mraa_gpio_init(pin); } if (m_gpio == NULL) { throw std::invalid_argument("Invalid GPIO pin specified"); } if (!owner) { mraa_gpio_owner(m_gpio, 0); } } /** * Gpio object destructor, this will only unexport the gpio if we where * the owner */ ~Gpio() { mraa_gpio_close(m_gpio); } /** * Set the edge mode for ISR * * @param mode The edge mode to set * @return Result of operation */ Result edge(Edge mode) { return (Result) mraa_gpio_edge_mode(m_gpio, (mraa_gpio_edge_t) mode); } #if defined(SWIGPYTHON) Result isr(Edge mode, PyObject* pyfunc, PyObject* args) { return (Result) mraa_gpio_isr(m_gpio, (mraa_gpio_edge_t) mode, (void (*) (void*)) pyfunc, (void*) args); } #elif defined(SWIGJAVASCRIPT) static void v8isr(uv_work_t* req, int status) { mraa::Gpio* This = (mraa::Gpio*) req->data; int argc = 1; v8::Local<v8::Value> argv[] = { SWIGV8_INTEGER_NEW(-1) }; #if NODE_MODULE_VERSION >= 0x000D v8::Local<v8::Function> f = v8::Local<v8::Function>::New(v8::Isolate::GetCurrent(), This->m_v8isr); f->Call(SWIGV8_CURRENT_CONTEXT()->Global(), argc, argv); #else This->m_v8isr->Call(SWIGV8_CURRENT_CONTEXT()->Global(), argc, argv); #endif delete req; } static void nop(uv_work_t* req) { // Do nothing. } static void uvwork(void* ctx) { uv_work_t* req = new uv_work_t; req->data = ctx; uv_queue_work(uv_default_loop(), req, nop, v8isr); } Result isr(Edge mode, v8::Handle<v8::Function> func) { #if NODE_MODULE_VERSION >= 0x000D m_v8isr.Reset(v8::Isolate::GetCurrent(), func); #else m_v8isr = v8::Persistent<v8::Function>::New(func); #endif return (Result) mraa_gpio_isr(m_gpio, (mraa_gpio_edge_t) mode, &uvwork, this); } #elif defined(SWIGJAVA) Result isr(Edge mode, IsrCallback* cb) { return (Result) mraa_gpio_isr(m_gpio, (mraa_gpio_edge_t) mode, &IsrCallback::generic_isr_callback, cb); } #else /** * Sets a callback to be called when pin value changes * * @param mode The edge mode to set * @param fptr Function pointer to function to be called when interupt is * triggered * @param args Arguments passed to the interrupt handler (fptr) * @return Result of operation */ Result isr(Edge mode, void (*fptr)(void*), void* args) { return (Result) mraa_gpio_isr(m_gpio, (mraa_gpio_edge_t) mode, fptr, args); } #endif /** * Exits callback - this call will not kill the isr thread immediatly * but only when it is out of it's critical section * * @return Result of operation */ Result isrExit() { #if defined(SWIGJAVASCRIPT) #if NODE_MODULE_VERSION >= 0x000D m_v8isr.Reset(); #else m_v8isr.Dispose(); m_v8isr.Clear(); #endif #endif return (Result) mraa_gpio_isr_exit(m_gpio); } /** * Change Gpio mode * * @param mode The mode to change the gpio into * @return Result of operation */ Result mode(Mode mode) { return (Result )mraa_gpio_mode(m_gpio, (mraa_gpio_mode_t) mode); } /** * Change Gpio direction * * @param dir The direction to change the gpio into * @return Result of operation */ Result dir(Dir dir) { return (Result )mraa_gpio_dir(m_gpio, (mraa_gpio_dir_t) dir); } /** * Read value from Gpio * * @return Gpio value */ int read() { return mraa_gpio_read(m_gpio); } /** * Write value to Gpio * * @param value Value to write to Gpio * @return Result of operation */ Result write(int value) { return (Result) mraa_gpio_write(m_gpio, value); } /** * Enable use of mmap i/o if available. * * @param enable true to use mmap * @return Result of operation */ Result useMmap(bool enable) { return (Result) mraa_gpio_use_mmaped(m_gpio, (mraa_boolean_t) enable); } /** * Get pin number of Gpio. If raw param is True will return the * number as used within sysfs. Invalid will return -1. * * @param raw (optional) get the raw gpio number. * @return Pin number */ int getPin(bool raw = false) { if (raw) { return mraa_gpio_get_pin_raw(m_gpio); } return mraa_gpio_get_pin(m_gpio); } private: mraa_gpio_context m_gpio; #if defined(SWIGJAVASCRIPT) v8::Persistent<v8::Function> m_v8isr; #endif }; } <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef NET_INET4_HPP #define NET_INET4_HPP #include <kernel/syscalls.hpp> // panic() #include <hw/devices.hpp> // 107: auto& eth0 = Dev::eth(0); #include <hw/nic.hpp> #include "inet.hpp" #include "ethernet.hpp" #include "ip4/arp.hpp" #include "ip4/ip4.hpp" #include "ip4/udp.hpp" #include "ip4/icmpv4.hpp" #include "dns/client.hpp" #include "tcp/tcp.hpp" #include <vector> namespace net { class DHClient; /** A complete IP4 network stack */ class Inet4 : public Inet<Ethernet, IP4>{ public: using dhcp_timeout_func = delegate<void(bool timed_out)>; virtual std::string ifname() const override { return nic_.ifname(); } Ethernet::addr link_addr() override { return eth_.mac(); } IP4::addr ip_addr() override { return ip4_addr_; } IP4::addr netmask() override { return netmask_; } IP4::addr router() override { return router_; } Ethernet& link() override { return eth_; } IP4& ip_obj() override { return ip4_; } /** Get the TCP-object belonging to this stack */ TCP& tcp() override { return tcp_; } /** Get the UDP-object belonging to this stack */ UDP& udp() override { return udp_; } /** Get the DHCP client (if any) */ auto dhclient() { return dhcp_; } /** Create a Packet, with a preallocated buffer. @param size : the "size" reported by the allocated packet. */ virtual Packet_ptr create_packet(size_t size) override { // get buffer (as packet + data) auto* ptr = (Packet*) bufstore_.get_buffer(); // place packet at front of buffer new (ptr) Packet(nic_.bufsize(), size, delegate<void(void*)>::from<BufferStore, &BufferStore::release> (&bufstore_)); // regular shared_ptr that calls delete on Packet return std::shared_ptr<Packet>(ptr); } /** MTU retreived from Nic on construction */ virtual uint16_t MTU() const override { return MTU_; } /** * @func a delegate that provides a hostname and its address, which is 0 if the * name @hostname was not found. Note: Test with INADDR_ANY for a 0-address. **/ virtual void resolve(const std::string& hostname, resolve_func<IP4> func) override { dns.resolve(this->dns_server, hostname, func); } virtual void set_router(IP4::addr gateway) override { this->router_ = gateway; } virtual void set_dns_server(IP4::addr server) override { this->dns_server = server; } /** * @brief Try to negotiate DHCP * @details Initialize DHClient if not present and tries to negotitate dhcp. * Also takes an optional timeout parameter and optional timeout function. * * @param timeout number of seconds before request should timeout * @param dhcp_timeout_func DHCP timeout handler */ void negotiate_dhcp(double timeout = 10.0, dhcp_timeout_func = nullptr); // handler called after the network successfully, or // unsuccessfully negotiated with DHCP-server // the timeout parameter indicates whether dhcp negotitation failed void on_config(dhcp_timeout_func handler); /** We don't want to copy or move an IP-stack. It's tied to a device. */ Inet4(Inet4&) = delete; Inet4(Inet4&&) = delete; Inet4& operator=(Inet4) = delete; Inet4 operator=(Inet4&&) = delete; virtual void network_config(IP4::addr addr, IP4::addr nmask, IP4::addr router, IP4::addr dns = IP4::INADDR_ANY) override { this->ip4_addr_ = addr; this->netmask_ = nmask; this->router_ = router; this->dns_server = (dns == IP4::INADDR_ANY) ? router : dns; INFO("Inet4", "Network configured"); INFO2("IP: \t\t%s", ip4_addr_.str().c_str()); INFO2("Netmask: \t%s", netmask_.str().c_str()); INFO2("Gateway: \t%s", router_.str().c_str()); INFO2("DNS Server: \t%s", dns_server.str().c_str()); } // register a callback for receiving signal on free packet-buffers virtual void on_transmit_queue_available(transmit_avail_delg del) override { tqa.push_back(del); } virtual size_t transmit_queue_available() override { return nic_.transmit_queue_available(); } virtual size_t buffers_available() override { return nic_.buffers_available(); } /** Return the stack on the given Nic */ template <int N> static auto& stack() { static Inet4 inet{hw::Devices::nic(N)}; return inet; } /** Static IP config */ template <int N> static auto& ifconfig( IP4::addr addr, IP4::addr nmask, IP4::addr router, IP4::addr dns = IP4::INADDR_ANY) { stack<N>().network_config(addr, nmask, router, dns); return stack<N>(); } /** DHCP config */ template <int N> static auto& ifconfig(double timeout = 10.0, dhcp_timeout_func on_timeout = nullptr) { stack<N>().negotiate_dhcp(timeout, on_timeout); return stack<N>(); } private: /** Initialize with ANY_ADDR */ Inet4(hw::Nic& nic); void process_sendq(size_t); // delegates registered to get signalled about free packets std::vector<transmit_avail_delg> tqa; IP4::addr ip4_addr_; IP4::addr netmask_; IP4::addr router_; IP4::addr dns_server; // This is the actual stack hw::Nic& nic_; Ethernet eth_; Arp arp_; IP4 ip4_; ICMPv4 icmp_; UDP udp_; TCP tcp_; // we need this to store the cache per-stack DNSClient dns; std::shared_ptr<net::DHClient> dhcp_{}; BufferStore& bufstore_; const uint16_t MTU_; }; } #endif <commit_msg>inet4: stack is returned with auto&&<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef NET_INET4_HPP #define NET_INET4_HPP #include <kernel/syscalls.hpp> // panic() #include <hw/devices.hpp> // 107: auto& eth0 = Dev::eth(0); #include <hw/nic.hpp> #include "inet.hpp" #include "ethernet.hpp" #include "ip4/arp.hpp" #include "ip4/ip4.hpp" #include "ip4/udp.hpp" #include "ip4/icmpv4.hpp" #include "dns/client.hpp" #include "tcp/tcp.hpp" #include <vector> namespace net { class DHClient; /** A complete IP4 network stack */ class Inet4 : public Inet<Ethernet, IP4>{ public: using dhcp_timeout_func = delegate<void(bool timed_out)>; virtual std::string ifname() const override { return nic_.ifname(); } Ethernet::addr link_addr() override { return eth_.mac(); } IP4::addr ip_addr() override { return ip4_addr_; } IP4::addr netmask() override { return netmask_; } IP4::addr router() override { return router_; } Ethernet& link() override { return eth_; } IP4& ip_obj() override { return ip4_; } /** Get the TCP-object belonging to this stack */ TCP& tcp() override { return tcp_; } /** Get the UDP-object belonging to this stack */ UDP& udp() override { return udp_; } /** Get the DHCP client (if any) */ auto dhclient() { return dhcp_; } /** Create a Packet, with a preallocated buffer. @param size : the "size" reported by the allocated packet. */ virtual Packet_ptr create_packet(size_t size) override { // get buffer (as packet + data) auto* ptr = (Packet*) bufstore_.get_buffer(); // place packet at front of buffer new (ptr) Packet(nic_.bufsize(), size, delegate<void(void*)>::from<BufferStore, &BufferStore::release> (&bufstore_)); // regular shared_ptr that calls delete on Packet return std::shared_ptr<Packet>(ptr); } /** MTU retreived from Nic on construction */ virtual uint16_t MTU() const override { return MTU_; } /** * @func a delegate that provides a hostname and its address, which is 0 if the * name @hostname was not found. Note: Test with INADDR_ANY for a 0-address. **/ virtual void resolve(const std::string& hostname, resolve_func<IP4> func) override { dns.resolve(this->dns_server, hostname, func); } virtual void set_router(IP4::addr gateway) override { this->router_ = gateway; } virtual void set_dns_server(IP4::addr server) override { this->dns_server = server; } /** * @brief Try to negotiate DHCP * @details Initialize DHClient if not present and tries to negotitate dhcp. * Also takes an optional timeout parameter and optional timeout function. * * @param timeout number of seconds before request should timeout * @param dhcp_timeout_func DHCP timeout handler */ void negotiate_dhcp(double timeout = 10.0, dhcp_timeout_func = nullptr); // handler called after the network successfully, or // unsuccessfully negotiated with DHCP-server // the timeout parameter indicates whether dhcp negotitation failed void on_config(dhcp_timeout_func handler); /** We don't want to copy or move an IP-stack. It's tied to a device. */ Inet4(Inet4&) = delete; Inet4(Inet4&&) = delete; Inet4& operator=(Inet4) = delete; Inet4 operator=(Inet4&&) = delete; virtual void network_config(IP4::addr addr, IP4::addr nmask, IP4::addr router, IP4::addr dns = IP4::INADDR_ANY) override { this->ip4_addr_ = addr; this->netmask_ = nmask; this->router_ = router; this->dns_server = (dns == IP4::INADDR_ANY) ? router : dns; INFO("Inet4", "Network configured"); INFO2("IP: \t\t%s", ip4_addr_.str().c_str()); INFO2("Netmask: \t%s", netmask_.str().c_str()); INFO2("Gateway: \t%s", router_.str().c_str()); INFO2("DNS Server: \t%s", dns_server.str().c_str()); } // register a callback for receiving signal on free packet-buffers virtual void on_transmit_queue_available(transmit_avail_delg del) override { tqa.push_back(del); } virtual size_t transmit_queue_available() override { return nic_.transmit_queue_available(); } virtual size_t buffers_available() override { return nic_.buffers_available(); } /** Return the stack on the given Nic */ template <int N> static auto&& stack() { static Inet4 inet{hw::Devices::nic(N)}; return inet; } /** Static IP config */ template <int N> static auto&& ifconfig( IP4::addr addr, IP4::addr nmask, IP4::addr router, IP4::addr dns = IP4::INADDR_ANY) { stack<N>().network_config(addr, nmask, router, dns); return stack<N>(); } /** DHCP config */ template <int N> static auto& ifconfig(double timeout = 10.0, dhcp_timeout_func on_timeout = nullptr) { stack<N>().negotiate_dhcp(timeout, on_timeout); return stack<N>(); } private: /** Initialize with ANY_ADDR */ Inet4(hw::Nic& nic); void process_sendq(size_t); // delegates registered to get signalled about free packets std::vector<transmit_avail_delg> tqa; IP4::addr ip4_addr_; IP4::addr netmask_; IP4::addr router_; IP4::addr dns_server; // This is the actual stack hw::Nic& nic_; Ethernet eth_; Arp arp_; IP4 ip4_; ICMPv4 icmp_; UDP udp_; TCP tcp_; // we need this to store the cache per-stack DNSClient dns; std::shared_ptr<net::DHClient> dhcp_{}; BufferStore& bufstore_; const uint16_t MTU_; }; } #endif <|endoftext|>
<commit_before>/* * ModSecurity, http://www.modsecurity.org/ * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * You may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address [email protected]. * */ #include "actions/set_var.h" #include <iostream> #include <string> #include "modsecurity/assay.h" #include "src/rule.h" #include "src/macro_expansion.h" #include "src/utils.h" namespace ModSecurity { namespace actions { SetVar::SetVar(std::string action) : Action(action, RunTimeOnlyIfMatchKind) { } bool SetVar::init(std::string *error) { size_t pos; if (action.at(0) == '\'' && action.size() > 3) { action.erase(0, 1); action.pop_back(); } // Resolv operation operation = setToOne; pos = action.find("="); if (pos != std::string::npos) { operation = setOperation; } pos = action.find("=+"); if (pos != std::string::npos) { operation = sumAndSetOperation; } pos = action.find("=-"); if (pos != std::string::npos) { operation = substractAndSetOperation; } // Collection name pos = action.find("."); if (pos != std::string::npos) { collectionName = std::string(action, 0, pos); collectionName = toupper(collectionName); } else { error->assign("Missing the collection and/or variable name"); return false; } // Variable name if (operation == setToOne) { variableName = std::string(action, pos + 1, action.length() - (pos + 1)); } else { size_t pos2 = action.find("="); variableName = std::string(action, pos + 1, pos2 - (pos + 1)); if (pos2 + 2 > action.length()) { error->assign("Something wrong with the input format"); return false; } if (operation == setOperation) { predicate = std::string(action, pos2 + 1, action.length() - (pos2)); } else { predicate = std::string(action, pos2 + 2, action.length() - (pos2 + 1)); } } if (collectionName.empty() || variableName.empty()) { error->assign("Something wrong with the input format"); return false; } return true; } void SetVar::dump() { std::cout << " Operation: " << std::to_string(operation) << std::endl; std::cout << "Collection: " << collectionName << std::endl; std::cout << " Variable: " << variableName << std::endl; std::cout << " Predicate: " << predicate << std::endl; } bool SetVar::evaluate(Rule *rule, Assay *assay) { std::string targetValue; variableName = MacroExpansion::expand(variableName, assay); int value = 0; try { std::string *resolvedValue = assay->resolve_variable_first(collectionName, variableName); if (resolvedValue == NULL) { value = 0; } else { value = stoi(*resolvedValue); } } catch (...) { value = 0; } std::string resolvedPre = MacroExpansion::expand(predicate, assay); if (operation == setOperation) { targetValue = resolvedPre; } else { int pre = 0; try { pre = stoi(resolvedPre); } catch (...) { pre = 0; } switch (operation) { case sumAndSetOperation: targetValue = std::to_string(value + pre); break; case substractAndSetOperation: targetValue = std::to_string(value - pre); break; case setToOne: targetValue = std::string("1"); break; } } #ifndef NO_LOGS assay->debug(8, "Saving variable: " + collectionName + ":" + \ variableName + " with value: " + targetValue); #endif assay->setCollection(collectionName, variableName, targetValue); return true; } } // namespace actions } // namespace ModSecurity <commit_msg>Performance improvement of setVar action<commit_after>/* * ModSecurity, http://www.modsecurity.org/ * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * You may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address [email protected]. * */ #include "actions/set_var.h" #include <iostream> #include <string> #include "modsecurity/assay.h" #include "src/rule.h" #include "src/macro_expansion.h" #include "src/utils.h" namespace ModSecurity { namespace actions { SetVar::SetVar(std::string action) : Action(action, RunTimeOnlyIfMatchKind) { } bool SetVar::init(std::string *error) { size_t pos; if (action.at(0) == '\'' && action.size() > 3) { action.erase(0, 1); action.pop_back(); } // Resolv operation operation = setToOne; pos = action.find("="); if (pos != std::string::npos) { operation = setOperation; } pos = action.find("=+"); if (pos != std::string::npos) { operation = sumAndSetOperation; } pos = action.find("=-"); if (pos != std::string::npos) { operation = substractAndSetOperation; } // Collection name pos = action.find("."); if (pos != std::string::npos) { collectionName = std::string(action, 0, pos); collectionName = toupper(collectionName); } else { error->assign("Missing the collection and/or variable name"); return false; } // Variable name if (operation == setToOne) { variableName = std::string(action, pos + 1, action.length() - (pos + 1)); } else { size_t pos2 = action.find("="); variableName = std::string(action, pos + 1, pos2 - (pos + 1)); if (pos2 + 2 > action.length()) { error->assign("Something wrong with the input format"); return false; } if (operation == setOperation) { predicate = std::string(action, pos2 + 1, action.length() - (pos2)); } else { predicate = std::string(action, pos2 + 2, action.length() - (pos2 + 1)); } } if (collectionName.empty() || variableName.empty()) { error->assign("Something wrong with the input format"); return false; } return true; } void SetVar::dump() { std::cout << " Operation: " << std::to_string(operation) << std::endl; std::cout << "Collection: " << collectionName << std::endl; std::cout << " Variable: " << variableName << std::endl; std::cout << " Predicate: " << predicate << std::endl; } bool SetVar::evaluate(Rule *rule, Assay *assay) { std::string targetValue; int value = 0; std::string variableNameExpanded = MacroExpansion::expand(variableName, assay); std::string resolvedPre = MacroExpansion::expand(predicate, assay); if (operation == setOperation) { targetValue = resolvedPre; } else if (operation == setToOne) { targetValue = std::string("1"); } else { int pre = 0; try { pre = stoi(resolvedPre); } catch (...) { pre = 0; } try { std::string *resolvedValue = assay->resolve_variable_first(collectionName, variableNameExpanded); if (resolvedValue == NULL) { value = 0; } else { value = stoi(*resolvedValue); } } catch (...) { value = 0; } switch (operation) { case sumAndSetOperation: targetValue = std::to_string(value + pre); break; case substractAndSetOperation: targetValue = std::to_string(value - pre); break; } } #ifndef NO_LOGS assay->debug(8, "Saving variable: " + collectionName + ":" + \ variableNameExpanded + " with value: " + targetValue); #endif assay->setCollection(collectionName, variableNameExpanded, targetValue); return true; } } // namespace actions } // namespace ModSecurity <|endoftext|>
<commit_before>#ifndef TOPAZ_ALGO_CONTAINER_HPP #define TOPAZ_ALGO_CONTAINER_HPP #include <cstddef> namespace tz::algo { template<typename StandardContainer> constexpr std::size_t sizeof_element(const StandardContainer& container); template<typename StandardContainer> constexpr std::size_t sizeof_element(); } #include "algo/container.inl" #endif // TOPAZ_ALGO_CONTAINER_HPP<commit_msg>* Better documentation for tz::algo container functions.<commit_after>#ifndef TOPAZ_ALGO_CONTAINER_HPP #define TOPAZ_ALGO_CONTAINER_HPP #include <cstddef> namespace tz::algo { /** * \addtogroup tz_algo Topaz Algorithms Library (tz::algo) * Contains common algorithms used in Topaz modules that aren't available in the C++ standard library. * @{ */ /** * Retrieve the size of an element in the given standard container. * Precondition: StandardContainer must define the member alias 'value_type'. Otherwise, usage will fail to compile. * @tparam StandardContainer Type representing a standard container. Examples: std::vector<int>, tz::mem::UniformPool<float>. * @param container Unused container value. Only pass a parameter if you wish for type deduction to take place. * @return Size of an element in the container, in bytes. For example: for StandardContainer std::vector<int>, expect this to return sizeof(int). */ template<typename StandardContainer> constexpr std::size_t sizeof_element(const StandardContainer& container); /** * Retrieve the size of an element in the given standard container. * Precondition: StandardContainer must define the member alias 'value_type'. Otherwise, usage will fail to compile. * Note: As this has no parameters, the type cannot be deduced. You must explicitly state the type to use this overload. If you wish to utilise type deduction, see sizeof_element(const StandardContainer&). * @tparam StandardContainer Type representing a standard container. Examples: std::vector<int>, tz::mem::UniformPool<float>. * @return Size of an element in the container, in bytes. For example: for StandardContainer std::vector<int>, expect this to return sizeof(int). */ template<typename StandardContainer> constexpr std::size_t sizeof_element(); /** * @} */ } #include "algo/container.inl" #endif // TOPAZ_ALGO_CONTAINER_HPP<|endoftext|>
<commit_before>/// /// @file cmdoptions.cpp /// @brief Parse command-line options for the primecount console /// (terminal) application. /// /// Copyright (C) 2017 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include "cmdoptions.hpp" #include <primecount-internal.hpp> #include <int128_t.hpp> #include <stdint.h> #include <vector> #include <string> #include <map> #include <exception> #include <cstdlib> #include <cstddef> using std::string; namespace primecount { void help(); void version(); bool test(); /// Command-line options std::map<string, OptionValues> optionMap = { { "-a", OPTION_ALPHA }, { "--alpha", OPTION_ALPHA }, { "-d", OPTION_DELEGLISE_RIVAT }, { "--deleglise_rivat", OPTION_DELEGLISE_RIVAT }, { "--deleglise_rivat1", OPTION_DELEGLISE_RIVAT1 }, { "--deleglise_rivat2", OPTION_DELEGLISE_RIVAT2 }, { "--deleglise_rivat_parallel1", OPTION_DELEGLISE_RIVAT_PARALLEL1 }, { "--deleglise_rivat_parallel2", OPTION_DELEGLISE_RIVAT_PARALLEL2 }, { "--deleglise_rivat_parallel3", OPTION_DELEGLISE_RIVAT_PARALLEL3 }, { "-h", OPTION_HELP }, { "--help", OPTION_HELP }, { "--legendre", OPTION_LEGENDRE }, { "--lehmer", OPTION_LEHMER }, { "-l", OPTION_LMO }, { "--lmo", OPTION_LMO }, { "--lmo1", OPTION_LMO1 }, { "--lmo2", OPTION_LMO2 }, { "--lmo3", OPTION_LMO3 }, { "--lmo4", OPTION_LMO4 }, { "--lmo5", OPTION_LMO5 }, { "--lmo_parallel1", OPTION_LMO_PARALLEL1 }, { "--lmo_parallel2", OPTION_LMO_PARALLEL2 }, { "--lmo_parallel3", OPTION_LMO_PARALLEL3 }, { "--Li", OPTION_LI }, { "--Li_inverse", OPTION_LIINV }, { "-m", OPTION_MEISSEL }, { "--meissel", OPTION_MEISSEL }, { "-n", OPTION_NTHPRIME }, { "--nthprime", OPTION_NTHPRIME }, { "--number", OPTION_NUMBER }, { "--P2", OPTION_P2 }, { "--pi", OPTION_PI }, { "-p", OPTION_PRIMESIEVE }, { "--primesieve", OPTION_PRIMESIEVE }, { "--S1", OPTION_S1 }, { "--S2_easy", OPTION_S2_EASY }, { "--S2_hard", OPTION_S2_HARD }, { "--S2_trivial", OPTION_S2_TRIVIAL }, { "-s", OPTION_STATUS }, { "--status", OPTION_STATUS }, { "--test", OPTION_TEST }, { "--time", OPTION_TIME }, { "-t", OPTION_THREADS }, { "--threads", OPTION_THREADS }, { "-v", OPTION_VERSION }, { "--version", OPTION_VERSION } }; /// e.g. id = "--threads", value = "4" struct Option { string id; string value; template <typename T> T getValue() const { return (T) to_maxint(value); } }; /// e.g. "--threads=8" -> { id = "--threads", value = "8" } Option makeOption(const string& str) { Option option; size_t delimiter = string::npos; if (optionMap.count(str) == 0) delimiter = str.find_first_of("=0123456789"); if (delimiter == string::npos) option.id = str; else { option.id = str.substr(0, delimiter); option.value = str.substr(delimiter + (str.at(delimiter) == '=' ? 1 : 0)); } if (option.id.empty() && !option.value.empty()) option.id = "--number"; if (optionMap.count(option.id) == 0) option.id = "--help"; return option; } PrimeCountOptions parseOptions(int argc, char** argv) { PrimeCountOptions pco; std::vector<maxint_t> numbers; try { // iterate over the command-line options for (int i = 1; i < argc; i++) { Option option = makeOption(argv[i]); switch (optionMap[option.id]) { case OPTION_ALPHA: set_alpha(std::stod(option.value)); break; case OPTION_NUMBER: numbers.push_back(option.getValue<maxint_t>()); break; case OPTION_THREADS: pco.threads = option.getValue<int>(); break; case OPTION_HELP: help(); break; case OPTION_STATUS: set_print_status(true); if (!option.value.empty()) set_status_precision(option.getValue<int>()); pco.time = true; break; case OPTION_TIME: pco.time = true; break; case OPTION_TEST: if (test()) exit(0); exit(1); case OPTION_VERSION: version(); break; default: pco.option = optionMap[option.id]; } } } catch (std::exception&) { help(); } if (numbers.size() == 1) pco.x = numbers[0]; else help(); return pco; } } // namespace <commit_msg>Use 2 spaces instead of 4<commit_after>/// /// @file cmdoptions.cpp /// @brief Parse command-line options for the primecount console /// (terminal) application. /// /// Copyright (C) 2017 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include "cmdoptions.hpp" #include <primecount-internal.hpp> #include <int128_t.hpp> #include <stdint.h> #include <vector> #include <string> #include <map> #include <exception> #include <cstdlib> #include <cstddef> using std::string; namespace primecount { void help(); void version(); bool test(); /// Command-line options std::map<string, OptionValues> optionMap = { { "-a", OPTION_ALPHA }, { "--alpha", OPTION_ALPHA }, { "-d", OPTION_DELEGLISE_RIVAT }, { "--deleglise_rivat", OPTION_DELEGLISE_RIVAT }, { "--deleglise_rivat1", OPTION_DELEGLISE_RIVAT1 }, { "--deleglise_rivat2", OPTION_DELEGLISE_RIVAT2 }, { "--deleglise_rivat_parallel1", OPTION_DELEGLISE_RIVAT_PARALLEL1 }, { "--deleglise_rivat_parallel2", OPTION_DELEGLISE_RIVAT_PARALLEL2 }, { "--deleglise_rivat_parallel3", OPTION_DELEGLISE_RIVAT_PARALLEL3 }, { "-h", OPTION_HELP }, { "--help", OPTION_HELP }, { "--legendre", OPTION_LEGENDRE }, { "--lehmer", OPTION_LEHMER }, { "-l", OPTION_LMO }, { "--lmo", OPTION_LMO }, { "--lmo1", OPTION_LMO1 }, { "--lmo2", OPTION_LMO2 }, { "--lmo3", OPTION_LMO3 }, { "--lmo4", OPTION_LMO4 }, { "--lmo5", OPTION_LMO5 }, { "--lmo_parallel1", OPTION_LMO_PARALLEL1 }, { "--lmo_parallel2", OPTION_LMO_PARALLEL2 }, { "--lmo_parallel3", OPTION_LMO_PARALLEL3 }, { "--Li", OPTION_LI }, { "--Li_inverse", OPTION_LIINV }, { "-m", OPTION_MEISSEL }, { "--meissel", OPTION_MEISSEL }, { "-n", OPTION_NTHPRIME }, { "--nthprime", OPTION_NTHPRIME }, { "--number", OPTION_NUMBER }, { "--P2", OPTION_P2 }, { "--pi", OPTION_PI }, { "-p", OPTION_PRIMESIEVE }, { "--primesieve", OPTION_PRIMESIEVE }, { "--S1", OPTION_S1 }, { "--S2_easy", OPTION_S2_EASY }, { "--S2_hard", OPTION_S2_HARD }, { "--S2_trivial", OPTION_S2_TRIVIAL }, { "-s", OPTION_STATUS }, { "--status", OPTION_STATUS }, { "--test", OPTION_TEST }, { "--time", OPTION_TIME }, { "-t", OPTION_THREADS }, { "--threads", OPTION_THREADS }, { "-v", OPTION_VERSION }, { "--version", OPTION_VERSION } }; /// e.g. id = "--threads", value = "4" struct Option { string id; string value; template <typename T> T getValue() const { return (T) to_maxint(value); } }; /// e.g. "--threads=8" -> { id = "--threads", value = "8" } Option makeOption(const string& str) { Option option; size_t delimiter = string::npos; if (optionMap.count(str) == 0) delimiter = str.find_first_of("=0123456789"); if (delimiter == string::npos) option.id = str; else { option.id = str.substr(0, delimiter); option.value = str.substr(delimiter + (str.at(delimiter) == '=' ? 1 : 0)); } if (option.id.empty() && !option.value.empty()) option.id = "--number"; if (optionMap.count(option.id) == 0) option.id = "--help"; return option; } PrimeCountOptions parseOptions(int argc, char** argv) { PrimeCountOptions pco; std::vector<maxint_t> numbers; try { // iterate over the command-line options for (int i = 1; i < argc; i++) { Option option = makeOption(argv[i]); switch (optionMap[option.id]) { case OPTION_ALPHA: set_alpha(std::stod(option.value)); break; case OPTION_NUMBER: numbers.push_back(option.getValue<maxint_t>()); break; case OPTION_THREADS: pco.threads = option.getValue<int>(); break; case OPTION_HELP: help(); break; case OPTION_STATUS: set_print_status(true); if (!option.value.empty()) set_status_precision(option.getValue<int>()); pco.time = true; break; case OPTION_TIME: pco.time = true; break; case OPTION_TEST: if (test()) exit(0); exit(1); case OPTION_VERSION: version(); break; default: pco.option = optionMap[option.id]; } } } catch (std::exception&) { help(); } if (numbers.size() == 1) pco.x = numbers[0]; else help(); return pco; } } // namespace <|endoftext|>
<commit_before>//===-- sanitizer_symbolizer_test.cc --------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Tests for sanitizer_symbolizer.h and sanitizer_symbolizer_internal.h // //===----------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_allocator_internal.h" #include "sanitizer_common/sanitizer_symbolizer_internal.h" #include "gtest/gtest.h" namespace __sanitizer { TEST(Symbolizer, ExtractToken) { char *token; const char *rest; rest = ExtractToken("a;b;c", ";", &token); EXPECT_STREQ("a", token); EXPECT_STREQ("b;c", rest); InternalFree(token); rest = ExtractToken("aaa-bbb.ccc", ";.-*", &token); EXPECT_STREQ("aaa", token); EXPECT_STREQ("bbb.ccc", rest); InternalFree(token); } TEST(Symbolizer, ExtractInt) { int token; const char *rest = ExtractInt("123,456;789", ";,", &token); EXPECT_EQ(123, token); EXPECT_STREQ("456;789", rest); } TEST(Symbolizer, ExtractUptr) { uptr token; const char *rest = ExtractUptr("123,456;789", ";,", &token); EXPECT_EQ(123U, token); EXPECT_STREQ("456;789", rest); } TEST(Symbolizer, ExtractTokenUpToDelimiter) { char *token; const char *rest = ExtractTokenUpToDelimiter("aaa-+-bbb-+-ccc", "-+-", &token); EXPECT_STREQ("aaa", token); EXPECT_STREQ("bbb-+-ccc", rest); InternalFree(token); } #if !SANITIZER_WINDOWS TEST(Symbolizer, DemangleSwiftAndCXX) { // Swift names are not demangled in default llvm build because Swift // runtime is not linked in. EXPECT_STREQ("_TtSd", DemangleSwiftAndCXX("_TtSd")); // Check that the rest demangles properly. EXPECT_STREQ("f1(char*, int)", DemangleSwiftAndCXX("_Z2f1Pci")); EXPECT_STREQ("foo", DemangleSwiftAndCXX("foo")); EXPECT_STREQ("", DemangleSwiftAndCXX("")); } #endif } // namespace __sanitizer <commit_msg>XFAIL one sanitizer symbolizer test for FreeBSD<commit_after>//===-- sanitizer_symbolizer_test.cc --------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Tests for sanitizer_symbolizer.h and sanitizer_symbolizer_internal.h // //===----------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_allocator_internal.h" #include "sanitizer_common/sanitizer_symbolizer_internal.h" #include "gtest/gtest.h" namespace __sanitizer { TEST(Symbolizer, ExtractToken) { char *token; const char *rest; rest = ExtractToken("a;b;c", ";", &token); EXPECT_STREQ("a", token); EXPECT_STREQ("b;c", rest); InternalFree(token); rest = ExtractToken("aaa-bbb.ccc", ";.-*", &token); EXPECT_STREQ("aaa", token); EXPECT_STREQ("bbb.ccc", rest); InternalFree(token); } TEST(Symbolizer, ExtractInt) { int token; const char *rest = ExtractInt("123,456;789", ";,", &token); EXPECT_EQ(123, token); EXPECT_STREQ("456;789", rest); } TEST(Symbolizer, ExtractUptr) { uptr token; const char *rest = ExtractUptr("123,456;789", ";,", &token); EXPECT_EQ(123U, token); EXPECT_STREQ("456;789", rest); } TEST(Symbolizer, ExtractTokenUpToDelimiter) { char *token; const char *rest = ExtractTokenUpToDelimiter("aaa-+-bbb-+-ccc", "-+-", &token); EXPECT_STREQ("aaa", token); EXPECT_STREQ("bbb-+-ccc", rest); InternalFree(token); } #if !SANITIZER_WINDOWS TEST(Symbolizer, DemangleSwiftAndCXX) { // Swift names are not demangled in default llvm build because Swift // runtime is not linked in. EXPECT_STREQ("_TtSd", DemangleSwiftAndCXX("_TtSd")); // Check that the rest demangles properly. EXPECT_STREQ("f1(char*, int)", DemangleSwiftAndCXX("_Z2f1Pci")); #if !SANITIZER_FREEBSD // QoI issue with libcxxrt on FreeBSD EXPECT_STREQ("foo", DemangleSwiftAndCXX("foo")); #endif EXPECT_STREQ("", DemangleSwiftAndCXX("")); } #endif } // namespace __sanitizer <|endoftext|>
<commit_before>//===-- Support/FoldingSet.cpp - Uniquing Hash Set --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by James M. Laskey and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a hash set that can be used to remove duplication of // nodes in a graph. This code was originally created by Chris Lattner for use // with SelectionDAGCSEMap, but was isolated to provide use across the llvm code // set. // //===----------------------------------------------------------------------===// #include "llvm/ADT/FoldingSet.h" #include "llvm/Support/MathExtras.h" #include <cassert> using namespace llvm; //===----------------------------------------------------------------------===// // FoldingSetImpl::NodeID Implementation /// Add* - Add various data types to Bit data. /// void FoldingSetImpl::NodeID::AddPointer(const void *Ptr) { // Note: this adds pointers to the hash using sizes and endianness that // depend on the host. It doesn't matter however, because hashing on // pointer values in inherently unstable. Nothing should depend on the // ordering of nodes in the folding set. intptr_t PtrI = (intptr_t)Ptr; Bits.push_back(unsigned(PtrI)); if (sizeof(intptr_t) > sizeof(unsigned)) Bits.push_back(unsigned(uint64_t(PtrI) >> 32)); } void FoldingSetImpl::NodeID::AddInteger(signed I) { Bits.push_back(I); } void FoldingSetImpl::NodeID::AddInteger(unsigned I) { Bits.push_back(I); } void FoldingSetImpl::NodeID::AddInteger(int64_t I) { AddInteger((uint64_t)I); } void FoldingSetImpl::NodeID::AddInteger(uint64_t I) { Bits.push_back(unsigned(I)); // If the integer is small, encode it just as 32-bits. if ((uint64_t)(int)I != I) Bits.push_back(unsigned(I >> 32)); } void FoldingSetImpl::NodeID::AddFloat(float F) { Bits.push_back(FloatToBits(F)); } void FoldingSetImpl::NodeID::AddDouble(double D) { AddInteger(DoubleToBits(D)); } void FoldingSetImpl::NodeID::AddAPFloat(const APFloat& apf) { APInt api = apf.convertToAPInt(); const uint64_t *p = api.getRawData(); for (unsigned i=0; i<api.getNumWords(); i++) AddInteger(*p++); } void FoldingSetImpl::NodeID::AddString(const std::string &String) { unsigned Size = String.size(); Bits.push_back(Size); if (!Size) return; unsigned Units = Size / 4; unsigned Pos = 0; const unsigned *Base = (const unsigned *)String.data(); // If the string is aligned do a bulk transfer. if (!((intptr_t)Base & 3)) { Bits.append(Base, Base + Units); Pos = (Units + 1) * 4; } else { // Otherwise do it the hard way. for ( Pos += 4; Pos <= Size; Pos += 4) { unsigned V = ((unsigned char)String[Pos - 4] << 24) | ((unsigned char)String[Pos - 3] << 16) | ((unsigned char)String[Pos - 2] << 8) | (unsigned char)String[Pos - 1]; Bits.push_back(V); } } // With the leftover bits. unsigned V = 0; // Pos will have overshot size by 4 - #bytes left over. switch (Pos - Size) { case 1: V = (V << 8) | (unsigned char)String[Size - 3]; // Fall thru. case 2: V = (V << 8) | (unsigned char)String[Size - 2]; // Fall thru. case 3: V = (V << 8) | (unsigned char)String[Size - 1]; break; default: return; // Nothing left. } Bits.push_back(V); } /// ComputeHash - Compute a strong hash value for this NodeID, used to /// lookup the node in the FoldingSetImpl. unsigned FoldingSetImpl::NodeID::ComputeHash() const { // This is adapted from SuperFastHash by Paul Hsieh. unsigned Hash = Bits.size(); for (const unsigned *BP = &Bits[0], *E = BP+Bits.size(); BP != E; ++BP) { unsigned Data = *BP; Hash += Data & 0xFFFF; unsigned Tmp = ((Data >> 16) << 11) ^ Hash; Hash = (Hash << 16) ^ Tmp; Hash += Hash >> 11; } // Force "avalanching" of final 127 bits. Hash ^= Hash << 3; Hash += Hash >> 5; Hash ^= Hash << 4; Hash += Hash >> 17; Hash ^= Hash << 25; Hash += Hash >> 6; return Hash; } /// operator== - Used to compare two nodes to each other. /// bool FoldingSetImpl::NodeID::operator==(const FoldingSetImpl::NodeID &RHS)const{ if (Bits.size() != RHS.Bits.size()) return false; return memcmp(&Bits[0], &RHS.Bits[0], Bits.size()*sizeof(Bits[0])) == 0; } //===----------------------------------------------------------------------===// /// Helper functions for FoldingSetImpl. /// GetNextPtr - In order to save space, each bucket is a /// singly-linked-list. In order to make deletion more efficient, we make /// the list circular, so we can delete a node without computing its hash. /// The problem with this is that the start of the hash buckets are not /// Nodes. If NextInBucketPtr is a bucket pointer, this method returns null: /// use GetBucketPtr when this happens. static FoldingSetImpl::Node *GetNextPtr(void *NextInBucketPtr, void **Buckets, unsigned NumBuckets) { if (NextInBucketPtr >= Buckets && NextInBucketPtr < Buckets + NumBuckets) return 0; return static_cast<FoldingSetImpl::Node*>(NextInBucketPtr); } /// GetBucketPtr - Provides a casting of a bucket pointer for isNode /// testing. static void **GetBucketPtr(void *NextInBucketPtr) { return static_cast<void**>(NextInBucketPtr); } /// GetBucketFor - Hash the specified node ID and return the hash bucket for /// the specified ID. static void **GetBucketFor(const FoldingSetImpl::NodeID &ID, void **Buckets, unsigned NumBuckets) { // NumBuckets is always a power of 2. unsigned BucketNum = ID.ComputeHash() & (NumBuckets-1); return Buckets + BucketNum; } //===----------------------------------------------------------------------===// // FoldingSetImpl Implementation FoldingSetImpl::FoldingSetImpl(unsigned Log2InitSize) : NumNodes(0) { assert(5 < Log2InitSize && Log2InitSize < 32 && "Initial hash table size out of range"); NumBuckets = 1 << Log2InitSize; Buckets = new void*[NumBuckets]; memset(Buckets, 0, NumBuckets*sizeof(void*)); } FoldingSetImpl::~FoldingSetImpl() { delete [] Buckets; } /// GrowHashTable - Double the size of the hash table and rehash everything. /// void FoldingSetImpl::GrowHashTable() { void **OldBuckets = Buckets; unsigned OldNumBuckets = NumBuckets; NumBuckets <<= 1; // Reset the node count to zero: we're going to reinsert everything. NumNodes = 0; // Clear out new buckets. Buckets = new void*[NumBuckets]; memset(Buckets, 0, NumBuckets*sizeof(void*)); // Walk the old buckets, rehashing nodes into their new place. for (unsigned i = 0; i != OldNumBuckets; ++i) { void *Probe = OldBuckets[i]; if (!Probe) continue; while (Node *NodeInBucket = GetNextPtr(Probe, OldBuckets, OldNumBuckets)) { // Figure out the next link, remove NodeInBucket from the old link. Probe = NodeInBucket->getNextInBucket(); NodeInBucket->SetNextInBucket(0); // Insert the node into the new bucket, after recomputing the hash. NodeID ID; GetNodeProfile(ID, NodeInBucket); InsertNode(NodeInBucket, GetBucketFor(ID, Buckets, NumBuckets)); } } delete[] OldBuckets; } /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists, /// return it. If not, return the insertion token that will make insertion /// faster. FoldingSetImpl::Node *FoldingSetImpl::FindNodeOrInsertPos(const NodeID &ID, void *&InsertPos) { void **Bucket = GetBucketFor(ID, Buckets, NumBuckets); void *Probe = *Bucket; InsertPos = 0; while (Node *NodeInBucket = GetNextPtr(Probe, Buckets, NumBuckets)) { NodeID OtherID; GetNodeProfile(OtherID, NodeInBucket); if (OtherID == ID) return NodeInBucket; Probe = NodeInBucket->getNextInBucket(); } // Didn't find the node, return null with the bucket as the InsertPos. InsertPos = Bucket; return 0; } /// InsertNode - Insert the specified node into the folding set, knowing that it /// is not already in the map. InsertPos must be obtained from /// FindNodeOrInsertPos. void FoldingSetImpl::InsertNode(Node *N, void *InsertPos) { assert(N->getNextInBucket() == 0); // Do we need to grow the hashtable? if (NumNodes+1 > NumBuckets*2) { GrowHashTable(); NodeID ID; GetNodeProfile(ID, N); InsertPos = GetBucketFor(ID, Buckets, NumBuckets); } ++NumNodes; /// The insert position is actually a bucket pointer. void **Bucket = static_cast<void**>(InsertPos); void *Next = *Bucket; // If this is the first insertion into this bucket, its next pointer will be // null. Pretend as if it pointed to itself. if (Next == 0) Next = Bucket; // Set the node's next pointer, and make the bucket point to the node. N->SetNextInBucket(Next); *Bucket = N; } /// RemoveNode - Remove a node from the folding set, returning true if one was /// removed or false if the node was not in the folding set. bool FoldingSetImpl::RemoveNode(Node *N) { // Because each bucket is a circular list, we don't need to compute N's hash // to remove it. void *Ptr = N->getNextInBucket(); if (Ptr == 0) return false; // Not in folding set. --NumNodes; N->SetNextInBucket(0); // Remember what N originally pointed to, either a bucket or another node. void *NodeNextPtr = Ptr; // Chase around the list until we find the node (or bucket) which points to N. while (true) { if (Node *NodeInBucket = GetNextPtr(Ptr, Buckets, NumBuckets)) { // Advance pointer. Ptr = NodeInBucket->getNextInBucket(); // We found a node that points to N, change it to point to N's next node, // removing N from the list. if (Ptr == N) { NodeInBucket->SetNextInBucket(NodeNextPtr); return true; } } else { void **Bucket = GetBucketPtr(Ptr); Ptr = *Bucket; // If we found that the bucket points to N, update the bucket to point to // whatever is next. if (Ptr == N) { *Bucket = NodeNextPtr; return true; } } } } /// GetOrInsertNode - If there is an existing simple Node exactly /// equal to the specified node, return it. Otherwise, insert 'N' and it /// instead. FoldingSetImpl::Node *FoldingSetImpl::GetOrInsertNode(FoldingSetImpl::Node *N) { NodeID ID; GetNodeProfile(ID, N); void *IP; if (Node *E = FindNodeOrInsertPos(ID, IP)) return E; InsertNode(N, IP); return N; } <commit_msg>Simplify implementation of the FoldingSet circular list, a necessary step to giving it iterators.<commit_after>//===-- Support/FoldingSet.cpp - Uniquing Hash Set --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by James M. Laskey and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a hash set that can be used to remove duplication of // nodes in a graph. This code was originally created by Chris Lattner for use // with SelectionDAGCSEMap, but was isolated to provide use across the llvm code // set. // //===----------------------------------------------------------------------===// #include "llvm/ADT/FoldingSet.h" #include "llvm/Support/MathExtras.h" #include <cassert> using namespace llvm; //===----------------------------------------------------------------------===// // FoldingSetImpl::NodeID Implementation /// Add* - Add various data types to Bit data. /// void FoldingSetImpl::NodeID::AddPointer(const void *Ptr) { // Note: this adds pointers to the hash using sizes and endianness that // depend on the host. It doesn't matter however, because hashing on // pointer values in inherently unstable. Nothing should depend on the // ordering of nodes in the folding set. intptr_t PtrI = (intptr_t)Ptr; Bits.push_back(unsigned(PtrI)); if (sizeof(intptr_t) > sizeof(unsigned)) Bits.push_back(unsigned(uint64_t(PtrI) >> 32)); } void FoldingSetImpl::NodeID::AddInteger(signed I) { Bits.push_back(I); } void FoldingSetImpl::NodeID::AddInteger(unsigned I) { Bits.push_back(I); } void FoldingSetImpl::NodeID::AddInteger(int64_t I) { AddInteger((uint64_t)I); } void FoldingSetImpl::NodeID::AddInteger(uint64_t I) { Bits.push_back(unsigned(I)); // If the integer is small, encode it just as 32-bits. if ((uint64_t)(int)I != I) Bits.push_back(unsigned(I >> 32)); } void FoldingSetImpl::NodeID::AddFloat(float F) { Bits.push_back(FloatToBits(F)); } void FoldingSetImpl::NodeID::AddDouble(double D) { AddInteger(DoubleToBits(D)); } void FoldingSetImpl::NodeID::AddAPFloat(const APFloat& apf) { APInt api = apf.convertToAPInt(); const uint64_t *p = api.getRawData(); for (unsigned i=0; i<api.getNumWords(); i++) AddInteger(*p++); } void FoldingSetImpl::NodeID::AddString(const std::string &String) { unsigned Size = String.size(); Bits.push_back(Size); if (!Size) return; unsigned Units = Size / 4; unsigned Pos = 0; const unsigned *Base = (const unsigned *)String.data(); // If the string is aligned do a bulk transfer. if (!((intptr_t)Base & 3)) { Bits.append(Base, Base + Units); Pos = (Units + 1) * 4; } else { // Otherwise do it the hard way. for ( Pos += 4; Pos <= Size; Pos += 4) { unsigned V = ((unsigned char)String[Pos - 4] << 24) | ((unsigned char)String[Pos - 3] << 16) | ((unsigned char)String[Pos - 2] << 8) | (unsigned char)String[Pos - 1]; Bits.push_back(V); } } // With the leftover bits. unsigned V = 0; // Pos will have overshot size by 4 - #bytes left over. switch (Pos - Size) { case 1: V = (V << 8) | (unsigned char)String[Size - 3]; // Fall thru. case 2: V = (V << 8) | (unsigned char)String[Size - 2]; // Fall thru. case 3: V = (V << 8) | (unsigned char)String[Size - 1]; break; default: return; // Nothing left. } Bits.push_back(V); } /// ComputeHash - Compute a strong hash value for this NodeID, used to /// lookup the node in the FoldingSetImpl. unsigned FoldingSetImpl::NodeID::ComputeHash() const { // This is adapted from SuperFastHash by Paul Hsieh. unsigned Hash = Bits.size(); for (const unsigned *BP = &Bits[0], *E = BP+Bits.size(); BP != E; ++BP) { unsigned Data = *BP; Hash += Data & 0xFFFF; unsigned Tmp = ((Data >> 16) << 11) ^ Hash; Hash = (Hash << 16) ^ Tmp; Hash += Hash >> 11; } // Force "avalanching" of final 127 bits. Hash ^= Hash << 3; Hash += Hash >> 5; Hash ^= Hash << 4; Hash += Hash >> 17; Hash ^= Hash << 25; Hash += Hash >> 6; return Hash; } /// operator== - Used to compare two nodes to each other. /// bool FoldingSetImpl::NodeID::operator==(const FoldingSetImpl::NodeID &RHS)const{ if (Bits.size() != RHS.Bits.size()) return false; return memcmp(&Bits[0], &RHS.Bits[0], Bits.size()*sizeof(Bits[0])) == 0; } //===----------------------------------------------------------------------===// /// Helper functions for FoldingSetImpl. /// GetNextPtr - In order to save space, each bucket is a /// singly-linked-list. In order to make deletion more efficient, we make /// the list circular, so we can delete a node without computing its hash. /// The problem with this is that the start of the hash buckets are not /// Nodes. If NextInBucketPtr is a bucket pointer, this method returns null: /// use GetBucketPtr when this happens. static FoldingSetImpl::Node *GetNextPtr(void *NextInBucketPtr) { // The low bit is set if this is the pointer back to the bucket. if (reinterpret_cast<intptr_t>(NextInBucketPtr) & 1) return 0; return static_cast<FoldingSetImpl::Node*>(NextInBucketPtr); } /// GetBucketPtr - Provides a casting of a bucket pointer for isNode /// testing. static void **GetBucketPtr(void *NextInBucketPtr) { intptr_t Ptr = reinterpret_cast<intptr_t>(NextInBucketPtr); return reinterpret_cast<void**>(Ptr & ~intptr_t(1)); } /// GetBucketFor - Hash the specified node ID and return the hash bucket for /// the specified ID. static void **GetBucketFor(const FoldingSetImpl::NodeID &ID, void **Buckets, unsigned NumBuckets) { // NumBuckets is always a power of 2. unsigned BucketNum = ID.ComputeHash() & (NumBuckets-1); return Buckets + BucketNum; } //===----------------------------------------------------------------------===// // FoldingSetImpl Implementation FoldingSetImpl::FoldingSetImpl(unsigned Log2InitSize) : NumNodes(0) { assert(5 < Log2InitSize && Log2InitSize < 32 && "Initial hash table size out of range"); NumBuckets = 1 << Log2InitSize; Buckets = new void*[NumBuckets+1]; memset(Buckets, 0, NumBuckets*sizeof(void*)); // Set the very last bucket to be a non-null "pointer". Buckets[NumBuckets] = reinterpret_cast<void*>(-2); } FoldingSetImpl::~FoldingSetImpl() { delete [] Buckets; } /// GrowHashTable - Double the size of the hash table and rehash everything. /// void FoldingSetImpl::GrowHashTable() { void **OldBuckets = Buckets; unsigned OldNumBuckets = NumBuckets; NumBuckets <<= 1; // Reset the node count to zero: we're going to reinsert everything. NumNodes = 0; // Clear out new buckets. Buckets = new void*[NumBuckets+1]; memset(Buckets, 0, NumBuckets*sizeof(void*)); // Set the very last bucket to be a non-null "pointer". Buckets[NumBuckets] = reinterpret_cast<void*>(-1); // Walk the old buckets, rehashing nodes into their new place. for (unsigned i = 0; i != OldNumBuckets; ++i) { void *Probe = OldBuckets[i]; if (!Probe) continue; while (Node *NodeInBucket = GetNextPtr(Probe)) { // Figure out the next link, remove NodeInBucket from the old link. Probe = NodeInBucket->getNextInBucket(); NodeInBucket->SetNextInBucket(0); // Insert the node into the new bucket, after recomputing the hash. NodeID ID; GetNodeProfile(ID, NodeInBucket); InsertNode(NodeInBucket, GetBucketFor(ID, Buckets, NumBuckets)); } } delete[] OldBuckets; } /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists, /// return it. If not, return the insertion token that will make insertion /// faster. FoldingSetImpl::Node *FoldingSetImpl::FindNodeOrInsertPos(const NodeID &ID, void *&InsertPos) { void **Bucket = GetBucketFor(ID, Buckets, NumBuckets); void *Probe = *Bucket; InsertPos = 0; while (Node *NodeInBucket = GetNextPtr(Probe)) { NodeID OtherID; GetNodeProfile(OtherID, NodeInBucket); if (OtherID == ID) return NodeInBucket; Probe = NodeInBucket->getNextInBucket(); } // Didn't find the node, return null with the bucket as the InsertPos. InsertPos = Bucket; return 0; } /// InsertNode - Insert the specified node into the folding set, knowing that it /// is not already in the map. InsertPos must be obtained from /// FindNodeOrInsertPos. void FoldingSetImpl::InsertNode(Node *N, void *InsertPos) { assert(N->getNextInBucket() == 0); // Do we need to grow the hashtable? if (NumNodes+1 > NumBuckets*2) { GrowHashTable(); NodeID ID; GetNodeProfile(ID, N); InsertPos = GetBucketFor(ID, Buckets, NumBuckets); } ++NumNodes; /// The insert position is actually a bucket pointer. void **Bucket = static_cast<void**>(InsertPos); void *Next = *Bucket; // If this is the first insertion into this bucket, its next pointer will be // null. Pretend as if it pointed to itself, setting the low bit to indicate // that it is a pointer to the bucket. if (Next == 0) Next = reinterpret_cast<void*>(reinterpret_cast<intptr_t>(Bucket)|1); // Set the node's next pointer, and make the bucket point to the node. N->SetNextInBucket(Next); *Bucket = N; } /// RemoveNode - Remove a node from the folding set, returning true if one was /// removed or false if the node was not in the folding set. bool FoldingSetImpl::RemoveNode(Node *N) { // Because each bucket is a circular list, we don't need to compute N's hash // to remove it. void *Ptr = N->getNextInBucket(); if (Ptr == 0) return false; // Not in folding set. --NumNodes; N->SetNextInBucket(0); // Remember what N originally pointed to, either a bucket or another node. void *NodeNextPtr = Ptr; // Chase around the list until we find the node (or bucket) which points to N. while (true) { if (Node *NodeInBucket = GetNextPtr(Ptr)) { // Advance pointer. Ptr = NodeInBucket->getNextInBucket(); // We found a node that points to N, change it to point to N's next node, // removing N from the list. if (Ptr == N) { NodeInBucket->SetNextInBucket(NodeNextPtr); return true; } } else { void **Bucket = GetBucketPtr(Ptr); Ptr = *Bucket; // If we found that the bucket points to N, update the bucket to point to // whatever is next. if (Ptr == N) { *Bucket = NodeNextPtr; return true; } } } } /// GetOrInsertNode - If there is an existing simple Node exactly /// equal to the specified node, return it. Otherwise, insert 'N' and it /// instead. FoldingSetImpl::Node *FoldingSetImpl::GetOrInsertNode(FoldingSetImpl::Node *N) { NodeID ID; GetNodeProfile(ID, N); void *IP; if (Node *E = FindNodeOrInsertPos(ID, IP)) return E; InsertNode(N, IP); return N; } <|endoftext|>
<commit_before>#include <OGDT/Exception.h> #include <cstdio> // printf #include <sstream> // ostringstream #define EXP_SIZE 1024 #ifdef WIN32 #define TLS __declspec( thread ) #else #define TLS __thread #endif TLS char exp_buf[EXP_SIZE]; using namespace OGDT; using namespace std; Exception::Exception (const char* what) throw () { snprintf (exp_buf, EXP_SIZE, what); } Exception::Exception (const std::ostringstream& what) throw () { snprintf (exp_buf, EXP_SIZE, what.str().c_str()); } Exception::Exception (const char* file, int line, const char* what) throw () { snprintf (exp_buf, EXP_SIZE, "File: %s, line: %d: %s", file, line, what); } Exception::Exception (const char* file, int line, const std::ostringstream& what) throw () { snprintf (exp_buf, EXP_SIZE, "File: %s, line: %d: %s", file, line, what.str().c_str()); } const char* Exception::what () const throw () { return exp_buf; } <commit_msg>Fixed snprintf on Windows<commit_after>#include <OGDT/Exception.h> #include <cstdio> #include <sstream> #ifdef _MSC_VER #define snprintf _snprintf #endif #define EXP_SIZE 1024 #ifdef WIN32 #define TLS __declspec( thread ) #else #define TLS __thread #endif TLS char exp_buf[EXP_SIZE]; using namespace OGDT; using namespace std; Exception::Exception (const char* what) throw () { snprintf (exp_buf, EXP_SIZE, what); } Exception::Exception (const std::ostringstream& what) throw () { snprintf (exp_buf, EXP_SIZE, what.str().c_str()); } Exception::Exception (const char* file, int line, const char* what) throw () { snprintf (exp_buf, EXP_SIZE, "File: %s, line: %d: %s", file, line, what); } Exception::Exception (const char* file, int line, const std::ostringstream& what) throw () { snprintf (exp_buf, EXP_SIZE, "File: %s, line: %d: %s", file, line, what.str().c_str()); } const char* Exception::what () const throw () { return exp_buf; } <|endoftext|>
<commit_before>/* * Copyright (c) 2007 The Hewlett-Packard Development Company * All rights reserved. * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #include "arch/x86/system.hh" #include "arch/x86/bios/intelmp.hh" #include "arch/x86/bios/smbios.hh" #include "arch/x86/isa_traits.hh" #include "base/loader/object_file.hh" #include "cpu/thread_context.hh" #include "params/X86System.hh" using namespace LittleEndianGuest; using namespace X86ISA; X86System::X86System(Params *p) : System(p), smbiosTable(p->smbios_table), mpFloatingPointer(p->intel_mp_pointer), mpConfigTable(p->intel_mp_table), rsdp(p->acpi_description_table_pointer) { } void X86ISA::installSegDesc(ThreadContext *tc, SegmentRegIndex seg, SegDescriptor desc, bool longmode) { uint64_t base = desc.baseLow + (desc.baseHigh << 24); bool honorBase = !longmode || seg == SEGMENT_REG_FS || seg == SEGMENT_REG_GS || seg == SEGMENT_REG_TSL || seg == SYS_SEGMENT_REG_TR; uint64_t limit = desc.limitLow | (desc.limitHigh << 16); SegAttr attr = 0; attr.dpl = desc.dpl; attr.unusable = 0; attr.defaultSize = desc.d; attr.longMode = desc.l; attr.avl = desc.avl; attr.granularity = desc.g; attr.present = desc.p; attr.system = desc.s; attr.type = desc.type; if (desc.s) { if (desc.type.codeOrData) { // Code segment attr.expandDown = 0; attr.readable = desc.type.r; attr.writable = 0; } else { // Data segment attr.expandDown = desc.type.e; attr.readable = 1; attr.writable = desc.type.w; } } else { attr.readable = 1; attr.writable = 1; attr.expandDown = 0; } tc->setMiscReg(MISCREG_SEG_BASE(seg), base); tc->setMiscReg(MISCREG_SEG_EFF_BASE(seg), honorBase ? base : 0); tc->setMiscReg(MISCREG_SEG_LIMIT(seg), limit); tc->setMiscReg(MISCREG_SEG_ATTR(seg), (MiscReg)attr); } void X86System::initState() { System::initState(); if (!kernel) fatal("No kernel to load.\n"); if (kernel->getArch() == ObjectFile::I386) fatal("Loading a 32 bit x86 kernel is not supported.\n"); ThreadContext *tc = threadContexts[0]; // This is the boot strap processor (BSP). Initialize it to look like // the boot loader has just turned control over to the 64 bit OS. We // won't actually set up real mode or legacy protected mode descriptor // tables because we aren't executing any code that would require // them. We do, however toggle the control bits in the correct order // while allowing consistency checks and the underlying mechansims // just to be safe. const int NumPDTs = 4; const Addr PageMapLevel4 = 0x70000; const Addr PageDirPtrTable = 0x71000; const Addr PageDirTable[NumPDTs] = {0x72000, 0x73000, 0x74000, 0x75000}; const Addr GDTBase = 0x76000; const int PML4Bits = 9; const int PDPTBits = 9; const int PDTBits = 9; /* * Set up the gdt. */ uint8_t numGDTEntries = 0; // Place holder at selector 0 uint64_t nullDescriptor = 0; physProxy.writeBlob(GDTBase + numGDTEntries * 8, (uint8_t *)(&nullDescriptor), 8); numGDTEntries++; SegDescriptor initDesc = 0; initDesc.type.codeOrData = 0; // code or data type initDesc.type.c = 0; // conforming initDesc.type.r = 1; // readable initDesc.dpl = 0; // privilege initDesc.p = 1; // present initDesc.l = 1; // longmode - 64 bit initDesc.d = 0; // operand size initDesc.g = 1; // granularity initDesc.s = 1; // system segment initDesc.limitHigh = 0xFFFF; initDesc.limitLow = 0xF; initDesc.baseHigh = 0x0; initDesc.baseLow = 0x0; //64 bit code segment SegDescriptor csDesc = initDesc; csDesc.type.codeOrData = 1; csDesc.dpl = 0; //Because we're dealing with a pointer and I don't think it's //guaranteed that there isn't anything in a nonvirtual class between //it's beginning in memory and it's actual data, we'll use an //intermediary. uint64_t csDescVal = csDesc; physProxy.writeBlob(GDTBase + numGDTEntries * 8, (uint8_t *)(&csDescVal), 8); numGDTEntries++; SegSelector cs = 0; cs.si = numGDTEntries - 1; tc->setMiscReg(MISCREG_CS, (MiscReg)cs); //32 bit data segment SegDescriptor dsDesc = initDesc; uint64_t dsDescVal = dsDesc; physProxy.writeBlob(GDTBase + numGDTEntries * 8, (uint8_t *)(&dsDescVal), 8); numGDTEntries++; SegSelector ds = 0; ds.si = numGDTEntries - 1; tc->setMiscReg(MISCREG_DS, (MiscReg)ds); tc->setMiscReg(MISCREG_ES, (MiscReg)ds); tc->setMiscReg(MISCREG_FS, (MiscReg)ds); tc->setMiscReg(MISCREG_GS, (MiscReg)ds); tc->setMiscReg(MISCREG_SS, (MiscReg)ds); tc->setMiscReg(MISCREG_TSL, 0); tc->setMiscReg(MISCREG_TSG_BASE, GDTBase); tc->setMiscReg(MISCREG_TSG_LIMIT, 8 * numGDTEntries - 1); SegDescriptor tssDesc = initDesc; uint64_t tssDescVal = tssDesc; physProxy.writeBlob(GDTBase + numGDTEntries * 8, (uint8_t *)(&tssDescVal), 8); numGDTEntries++; SegSelector tss = 0; tss.si = numGDTEntries - 1; tc->setMiscReg(MISCREG_TR, (MiscReg)tss); installSegDesc(tc, SYS_SEGMENT_REG_TR, tssDesc, true); /* * Identity map the first 4GB of memory. In order to map this region * of memory in long mode, there needs to be one actual page map level * 4 entry which points to one page directory pointer table which * points to 4 different page directory tables which are full of two * megabyte pages. All of the other entries in valid tables are set * to indicate that they don't pertain to anything valid and will * cause a fault if used. */ // Put valid values in all of the various table entries which indicate // that those entries don't point to further tables or pages. Then // set the values of those entries which are needed. // Page Map Level 4 // read/write, user, not present uint64_t pml4e = X86ISA::htog(0x6); for (int offset = 0; offset < (1 << PML4Bits) * 8; offset += 8) { physProxy.writeBlob(PageMapLevel4 + offset, (uint8_t *)(&pml4e), 8); } // Point to the only PDPT pml4e = X86ISA::htog(0x7 | PageDirPtrTable); physProxy.writeBlob(PageMapLevel4, (uint8_t *)(&pml4e), 8); // Page Directory Pointer Table // read/write, user, not present uint64_t pdpe = X86ISA::htog(0x6); for (int offset = 0; offset < (1 << PDPTBits) * 8; offset += 8) { physProxy.writeBlob(PageDirPtrTable + offset, (uint8_t *)(&pdpe), 8); } // Point to the PDTs for (int table = 0; table < NumPDTs; table++) { pdpe = X86ISA::htog(0x7 | PageDirTable[table]); physProxy.writeBlob(PageDirPtrTable + table * 8, (uint8_t *)(&pdpe), 8); } // Page Directory Tables Addr base = 0; const Addr pageSize = 2 << 20; for (int table = 0; table < NumPDTs; table++) { for (int offset = 0; offset < (1 << PDTBits) * 8; offset += 8) { // read/write, user, present, 4MB uint64_t pdte = X86ISA::htog(0x87 | base); physProxy.writeBlob(PageDirTable[table] + offset, (uint8_t *)(&pdte), 8); base += pageSize; } } /* * Transition from real mode all the way up to Long mode */ CR0 cr0 = tc->readMiscRegNoEffect(MISCREG_CR0); //Turn off paging. cr0.pg = 0; tc->setMiscReg(MISCREG_CR0, cr0); //Turn on protected mode. cr0.pe = 1; tc->setMiscReg(MISCREG_CR0, cr0); CR4 cr4 = tc->readMiscRegNoEffect(MISCREG_CR4); //Turn on pae. cr4.pae = 1; tc->setMiscReg(MISCREG_CR4, cr4); //Point to the page tables. tc->setMiscReg(MISCREG_CR3, PageMapLevel4); Efer efer = tc->readMiscRegNoEffect(MISCREG_EFER); //Enable long mode. efer.lme = 1; tc->setMiscReg(MISCREG_EFER, efer); //Start using longmode segments. installSegDesc(tc, SEGMENT_REG_CS, csDesc, true); installSegDesc(tc, SEGMENT_REG_DS, dsDesc, true); installSegDesc(tc, SEGMENT_REG_ES, dsDesc, true); installSegDesc(tc, SEGMENT_REG_FS, dsDesc, true); installSegDesc(tc, SEGMENT_REG_GS, dsDesc, true); installSegDesc(tc, SEGMENT_REG_SS, dsDesc, true); //Activate long mode. cr0.pg = 1; tc->setMiscReg(MISCREG_CR0, cr0); tc->pcState(tc->getSystemPtr()->kernelEntry); // We should now be in long mode. Yay! Addr ebdaPos = 0xF0000; Addr fixed, table; //Write out the SMBios/DMI table writeOutSMBiosTable(ebdaPos, fixed, table); ebdaPos += (fixed + table); ebdaPos = roundUp(ebdaPos, 16); //Write out the Intel MP Specification configuration table writeOutMPTable(ebdaPos, fixed, table); ebdaPos += (fixed + table); } void X86System::writeOutSMBiosTable(Addr header, Addr &headerSize, Addr &structSize, Addr table) { // If the table location isn't specified, just put it after the header. // The header size as of the 2.5 SMBios specification is 0x1F bytes if (!table) table = header + 0x1F; smbiosTable->setTableAddr(table); smbiosTable->writeOut(physProxy, header, headerSize, structSize); // Do some bounds checking to make sure we at least didn't step on // ourselves. assert(header > table || header + headerSize <= table); assert(table > header || table + structSize <= header); } void X86System::writeOutMPTable(Addr fp, Addr &fpSize, Addr &tableSize, Addr table) { // If the table location isn't specified and it exists, just put // it after the floating pointer. The fp size as of the 1.4 Intel MP // specification is 0x10 bytes. if (mpConfigTable) { if (!table) table = fp + 0x10; mpFloatingPointer->setTableAddr(table); } fpSize = mpFloatingPointer->writeOut(physProxy, fp); if (mpConfigTable) tableSize = mpConfigTable->writeOut(physProxy, table); else tableSize = 0; // Do some bounds checking to make sure we at least didn't step on // ourselves and the fp structure was the size we thought it was. assert(fp > table || fp + fpSize <= table); assert(table > fp || table + tableSize <= fp); assert(fpSize == 0x10); } X86System::~X86System() { delete smbiosTable; } X86System * X86SystemParams::create() { return new X86System(this); } <commit_msg>arch-x86: Granularity bit and segment limit<commit_after>/* * Copyright (c) 2007 The Hewlett-Packard Development Company * Copyright (c) 2018 TU Dresden * All rights reserved. * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black * Maximilian Stein */ #include "arch/x86/system.hh" #include "arch/x86/bios/intelmp.hh" #include "arch/x86/bios/smbios.hh" #include "arch/x86/isa_traits.hh" #include "base/loader/object_file.hh" #include "cpu/thread_context.hh" #include "params/X86System.hh" using namespace LittleEndianGuest; using namespace X86ISA; X86System::X86System(Params *p) : System(p), smbiosTable(p->smbios_table), mpFloatingPointer(p->intel_mp_pointer), mpConfigTable(p->intel_mp_table), rsdp(p->acpi_description_table_pointer) { } void X86ISA::installSegDesc(ThreadContext *tc, SegmentRegIndex seg, SegDescriptor desc, bool longmode) { uint64_t base = desc.baseLow + (desc.baseHigh << 24); bool honorBase = !longmode || seg == SEGMENT_REG_FS || seg == SEGMENT_REG_GS || seg == SEGMENT_REG_TSL || seg == SYS_SEGMENT_REG_TR; uint64_t limit = desc.limitLow | (desc.limitHigh << 16); if (desc.g) limit = (limit << 12) | mask(12); SegAttr attr = 0; attr.dpl = desc.dpl; attr.unusable = 0; attr.defaultSize = desc.d; attr.longMode = desc.l; attr.avl = desc.avl; attr.granularity = desc.g; attr.present = desc.p; attr.system = desc.s; attr.type = desc.type; if (desc.s) { if (desc.type.codeOrData) { // Code segment attr.expandDown = 0; attr.readable = desc.type.r; attr.writable = 0; } else { // Data segment attr.expandDown = desc.type.e; attr.readable = 1; attr.writable = desc.type.w; } } else { attr.readable = 1; attr.writable = 1; attr.expandDown = 0; } tc->setMiscReg(MISCREG_SEG_BASE(seg), base); tc->setMiscReg(MISCREG_SEG_EFF_BASE(seg), honorBase ? base : 0); tc->setMiscReg(MISCREG_SEG_LIMIT(seg), limit); tc->setMiscReg(MISCREG_SEG_ATTR(seg), (MiscReg)attr); } void X86System::initState() { System::initState(); if (!kernel) fatal("No kernel to load.\n"); if (kernel->getArch() == ObjectFile::I386) fatal("Loading a 32 bit x86 kernel is not supported.\n"); ThreadContext *tc = threadContexts[0]; // This is the boot strap processor (BSP). Initialize it to look like // the boot loader has just turned control over to the 64 bit OS. We // won't actually set up real mode or legacy protected mode descriptor // tables because we aren't executing any code that would require // them. We do, however toggle the control bits in the correct order // while allowing consistency checks and the underlying mechansims // just to be safe. const int NumPDTs = 4; const Addr PageMapLevel4 = 0x70000; const Addr PageDirPtrTable = 0x71000; const Addr PageDirTable[NumPDTs] = {0x72000, 0x73000, 0x74000, 0x75000}; const Addr GDTBase = 0x76000; const int PML4Bits = 9; const int PDPTBits = 9; const int PDTBits = 9; /* * Set up the gdt. */ uint8_t numGDTEntries = 0; // Place holder at selector 0 uint64_t nullDescriptor = 0; physProxy.writeBlob(GDTBase + numGDTEntries * 8, (uint8_t *)(&nullDescriptor), 8); numGDTEntries++; SegDescriptor initDesc = 0; initDesc.type.codeOrData = 0; // code or data type initDesc.type.c = 0; // conforming initDesc.type.r = 1; // readable initDesc.dpl = 0; // privilege initDesc.p = 1; // present initDesc.l = 1; // longmode - 64 bit initDesc.d = 0; // operand size initDesc.g = 1; // granularity initDesc.s = 1; // system segment initDesc.limitHigh = 0xF; initDesc.limitLow = 0xFFFF; initDesc.baseHigh = 0x0; initDesc.baseLow = 0x0; //64 bit code segment SegDescriptor csDesc = initDesc; csDesc.type.codeOrData = 1; csDesc.dpl = 0; //Because we're dealing with a pointer and I don't think it's //guaranteed that there isn't anything in a nonvirtual class between //it's beginning in memory and it's actual data, we'll use an //intermediary. uint64_t csDescVal = csDesc; physProxy.writeBlob(GDTBase + numGDTEntries * 8, (uint8_t *)(&csDescVal), 8); numGDTEntries++; SegSelector cs = 0; cs.si = numGDTEntries - 1; tc->setMiscReg(MISCREG_CS, (MiscReg)cs); //32 bit data segment SegDescriptor dsDesc = initDesc; uint64_t dsDescVal = dsDesc; physProxy.writeBlob(GDTBase + numGDTEntries * 8, (uint8_t *)(&dsDescVal), 8); numGDTEntries++; SegSelector ds = 0; ds.si = numGDTEntries - 1; tc->setMiscReg(MISCREG_DS, (MiscReg)ds); tc->setMiscReg(MISCREG_ES, (MiscReg)ds); tc->setMiscReg(MISCREG_FS, (MiscReg)ds); tc->setMiscReg(MISCREG_GS, (MiscReg)ds); tc->setMiscReg(MISCREG_SS, (MiscReg)ds); tc->setMiscReg(MISCREG_TSL, 0); tc->setMiscReg(MISCREG_TSG_BASE, GDTBase); tc->setMiscReg(MISCREG_TSG_LIMIT, 8 * numGDTEntries - 1); SegDescriptor tssDesc = initDesc; uint64_t tssDescVal = tssDesc; physProxy.writeBlob(GDTBase + numGDTEntries * 8, (uint8_t *)(&tssDescVal), 8); numGDTEntries++; SegSelector tss = 0; tss.si = numGDTEntries - 1; tc->setMiscReg(MISCREG_TR, (MiscReg)tss); installSegDesc(tc, SYS_SEGMENT_REG_TR, tssDesc, true); /* * Identity map the first 4GB of memory. In order to map this region * of memory in long mode, there needs to be one actual page map level * 4 entry which points to one page directory pointer table which * points to 4 different page directory tables which are full of two * megabyte pages. All of the other entries in valid tables are set * to indicate that they don't pertain to anything valid and will * cause a fault if used. */ // Put valid values in all of the various table entries which indicate // that those entries don't point to further tables or pages. Then // set the values of those entries which are needed. // Page Map Level 4 // read/write, user, not present uint64_t pml4e = X86ISA::htog(0x6); for (int offset = 0; offset < (1 << PML4Bits) * 8; offset += 8) { physProxy.writeBlob(PageMapLevel4 + offset, (uint8_t *)(&pml4e), 8); } // Point to the only PDPT pml4e = X86ISA::htog(0x7 | PageDirPtrTable); physProxy.writeBlob(PageMapLevel4, (uint8_t *)(&pml4e), 8); // Page Directory Pointer Table // read/write, user, not present uint64_t pdpe = X86ISA::htog(0x6); for (int offset = 0; offset < (1 << PDPTBits) * 8; offset += 8) { physProxy.writeBlob(PageDirPtrTable + offset, (uint8_t *)(&pdpe), 8); } // Point to the PDTs for (int table = 0; table < NumPDTs; table++) { pdpe = X86ISA::htog(0x7 | PageDirTable[table]); physProxy.writeBlob(PageDirPtrTable + table * 8, (uint8_t *)(&pdpe), 8); } // Page Directory Tables Addr base = 0; const Addr pageSize = 2 << 20; for (int table = 0; table < NumPDTs; table++) { for (int offset = 0; offset < (1 << PDTBits) * 8; offset += 8) { // read/write, user, present, 4MB uint64_t pdte = X86ISA::htog(0x87 | base); physProxy.writeBlob(PageDirTable[table] + offset, (uint8_t *)(&pdte), 8); base += pageSize; } } /* * Transition from real mode all the way up to Long mode */ CR0 cr0 = tc->readMiscRegNoEffect(MISCREG_CR0); //Turn off paging. cr0.pg = 0; tc->setMiscReg(MISCREG_CR0, cr0); //Turn on protected mode. cr0.pe = 1; tc->setMiscReg(MISCREG_CR0, cr0); CR4 cr4 = tc->readMiscRegNoEffect(MISCREG_CR4); //Turn on pae. cr4.pae = 1; tc->setMiscReg(MISCREG_CR4, cr4); //Point to the page tables. tc->setMiscReg(MISCREG_CR3, PageMapLevel4); Efer efer = tc->readMiscRegNoEffect(MISCREG_EFER); //Enable long mode. efer.lme = 1; tc->setMiscReg(MISCREG_EFER, efer); //Start using longmode segments. installSegDesc(tc, SEGMENT_REG_CS, csDesc, true); installSegDesc(tc, SEGMENT_REG_DS, dsDesc, true); installSegDesc(tc, SEGMENT_REG_ES, dsDesc, true); installSegDesc(tc, SEGMENT_REG_FS, dsDesc, true); installSegDesc(tc, SEGMENT_REG_GS, dsDesc, true); installSegDesc(tc, SEGMENT_REG_SS, dsDesc, true); //Activate long mode. cr0.pg = 1; tc->setMiscReg(MISCREG_CR0, cr0); tc->pcState(tc->getSystemPtr()->kernelEntry); // We should now be in long mode. Yay! Addr ebdaPos = 0xF0000; Addr fixed, table; //Write out the SMBios/DMI table writeOutSMBiosTable(ebdaPos, fixed, table); ebdaPos += (fixed + table); ebdaPos = roundUp(ebdaPos, 16); //Write out the Intel MP Specification configuration table writeOutMPTable(ebdaPos, fixed, table); ebdaPos += (fixed + table); } void X86System::writeOutSMBiosTable(Addr header, Addr &headerSize, Addr &structSize, Addr table) { // If the table location isn't specified, just put it after the header. // The header size as of the 2.5 SMBios specification is 0x1F bytes if (!table) table = header + 0x1F; smbiosTable->setTableAddr(table); smbiosTable->writeOut(physProxy, header, headerSize, structSize); // Do some bounds checking to make sure we at least didn't step on // ourselves. assert(header > table || header + headerSize <= table); assert(table > header || table + structSize <= header); } void X86System::writeOutMPTable(Addr fp, Addr &fpSize, Addr &tableSize, Addr table) { // If the table location isn't specified and it exists, just put // it after the floating pointer. The fp size as of the 1.4 Intel MP // specification is 0x10 bytes. if (mpConfigTable) { if (!table) table = fp + 0x10; mpFloatingPointer->setTableAddr(table); } fpSize = mpFloatingPointer->writeOut(physProxy, fp); if (mpConfigTable) tableSize = mpConfigTable->writeOut(physProxy, table); else tableSize = 0; // Do some bounds checking to make sure we at least didn't step on // ourselves and the fp structure was the size we thought it was. assert(fp > table || fp + fpSize <= table); assert(table > fp || table + tableSize <= fp); assert(fpSize == 0x10); } X86System::~X86System() { delete smbiosTable; } X86System * X86SystemParams::create() { return new X86System(this); } <|endoftext|>
<commit_before>/* * Copyright 2011 Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 */ #include "calendarcontroller.h" #include "calendardbsingleton.h" #include <stdlib.h> #include <exception> #include <alarm.h> #include <icalformat.h> #include <QDebug> using namespace std; CalendarController::CalendarController(QObject *parent) : QObject(parent) { setUpCalendars(); } //Destructor CalendarController::~CalendarController() { } bool CalendarController::setUpCalendars() { bool setUpStatus=true; try { CalendarDBSingleton::instance(); calendar = CalendarDBSingleton::calendarP(); storage = CalendarDBSingleton::StoragePTR(); //This part of code is to support multiple calendars notebook = storage->defaultNotebook().data(); if(notebook->color().isEmpty()) { notebook->setColor("Blue"); } if(notebook->description().isEmpty()){ notebook->setDescription("Default Calendar"); } nUid = notebook->uid(); storage->loadNotebookIncidences(notebook->uid()); } catch (exception &e) { setUpStatus=false; qDebug()<<e.what(); } return setUpStatus; } /** * This method adds the Event to the database * @param eventIO, The IncidenceIO object which has all the * details the user enters on the New Event form. * @return returns true if added successfully, else false */ bool CalendarController :: addModifyEvent(int actionType,QObject* eventIOObj) { bool success=true; IncidenceIO eventIO(*(IncidenceIO*)(eventIOObj)); try { KCalCore::Event::Ptr coreEvent; if(actionType == EAddEvent) { coreEvent = KCalCore::Event::Ptr(new KCalCore::Event()); } else if(actionType == EModifyEvent) { coreEvent = KCalCore::Event::Ptr(calendar->event(eventIO.getUid())); } if(coreEvent.isNull()) { return false; } coreEvent->setSummary(eventIO.getSummary()); coreEvent->setDescription(eventIO.getDescription()); coreEvent->setLocation(eventIO.getLocation()); //handle Event time handleEventTime(coreEvent,eventIO); //handle repeat handleRepeat(coreEvent,eventIO); //handle alarm processing if(eventIO.getAlarmType()!= ENoAlarm) { coreEvent->clearAlarms(); KCalCore::Alarm::Ptr eventAlarm(coreEvent->newAlarm()); handleAlarm(eventIO,eventAlarm); } if(actionType == EAddEvent) { calendar->addEvent(coreEvent,notebook->uid()); } else if(actionType == EModifyEvent) { coreEvent->setRevision(coreEvent->revision()+1); } storage->save(); } catch (exception &e) { success = false; qDebug()<< e.what(); } return success; } /** * This method deletes the event from the Calendar and the Storage * @param eventUid the unique identifier of the Event * @return true of deleted successfully,else false */ bool CalendarController::deleteEvent(QString eventUid) { bool deleted = true; try { storage->loadNotebookIncidences(nUid); KCalCore::Event::Ptr coreEvent = KCalCore::Event::Ptr(calendar->event(eventUid)); if(!coreEvent.isNull()) { deleted = calendar->deleteEvent(coreEvent); } storage->save(); }catch(exception &e){ deleted = false; qDebug()<< e.what(); } return deleted; } /** * Method to set the recurrence of the event. This method is called by addEvent method * @param coreEvent, event whose recurrence has to be set * @param eventIO, the IO object from the UI */ void CalendarController::handleRepeat(KCalCore::Event::Ptr coreEventPtr,const IncidenceIO& eventIO) { try { if(eventIO.getRepeatType()==ENoRepeat){ /*eventRecurrence->setDaily(1); eventRecurrence->setDuration(1); if(eventIO.isAllDay()) { eventRecurrence->setEndDateTime(eventIO.getStartDateTime()); } else { eventRecurrence->setEndDateTime(eventIO.getEndDateTime()); }*/ } else { KCalCore::Recurrence *eventRecurrence = coreEventPtr->recurrence(); switch(eventIO.getRepeatType()) { case EEveryDay: { eventRecurrence->setDaily(1); break; } case EEveryWeek: { eventRecurrence->setWeekly(1); break; } case EEvery2Weeks: { eventRecurrence->setWeekly(2,EMonday); break; } case EEveryMonth: { eventRecurrence->setMonthly(1); break; } case EEveryYear: { eventRecurrence->setYearly(1); break; } case EOtherRepeat: { qDebug()<<"Not Sure At this moment"; eventRecurrence->setWeekly(1); break; } default: { eventRecurrence->clear(); break; } }//end of switch if(eventIO.getRepeatEndType() == UtilMethods::EForNTimes) { eventRecurrence->setDuration(eventIO.getRepeatCount()); } else if(eventIO.getRepeatEndType() == UtilMethods::EAfterDate) { eventRecurrence->setEndDateTime(eventIO.getRepeatEndDateTime()); } }//end of else } catch (exception &e) { qDebug()<<e.what(); } return; } /** * This method handles allday flag in an event */ //Might need some additional processing. //So put the logic seperately into a method instead of cluttering the addEvent method void CalendarController::handleEventTime(KCalCore::Event::Ptr coreEventPtr,const IncidenceIO& eventIO) { try{ coreEventPtr->setDtStart(eventIO.getStartDateTime()); if(eventIO.isAllDay()) { coreEventPtr->setAllDay(true); if(coreEventPtr->hasEndDate()) { coreEventPtr->setDtEnd(eventIO.getStartDateTime());} } else { coreEventPtr->setAllDay(false); coreEventPtr->setDtEnd(eventIO.getEndDateTime()); } } catch(exception &e) { qDebug()<<e.what(); } return; } /** * This method handles setting alarm in an event * @param eventIO, the IncidenceIO object from the UI * @param eventAlarm, the KCalCore::Alarm object with its parent set */ void CalendarController::handleAlarm(const IncidenceIO& eventIO,KCalCore::Alarm::Ptr eventAlarm) { try{ eventAlarm->setText(eventIO.getSummary()); eventAlarm->setDisplayAlarm(eventIO.getSummary()); eventAlarm->setEnabled(true); switch(eventIO.getAlarmType()) { case E10MinB4: default: //snooze with 5min interval eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration( -60*10 ) ); break; case E15MinB4: { eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration( -60*15 ) ); break; } case E30MinB4: { eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration( -60*30 ) ); break; } case E1HrB4: { eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration( -60*60 ) ); break; } case E2HrsB4: { eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration( -60*120 ) ); break; } case E1DayB4: { eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration(-1,KCalCore::Duration::Days) ); break; } case E2DaysB4: { eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration(-2,KCalCore::Duration::Days) ); break; } case E1WeekB4: { eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration(-7,KCalCore::Duration::Days) ); break; } case EOtherAlarm: { qDebug()<<"Not Sure At this moment"; eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration( -60*15 ) ); break; } }//end of switch qDebug()<<"Exiting handleAlarm\n"; } catch(exception &e) { qDebug()<<e.what(); } return; } QList<IncidenceIO> CalendarController::getEventsFromDB(int listType,KDateTime startDate, KDateTime endDate,const QString uid) { QList<IncidenceIO> eventIOList; try { KCalCore::Event::List eventList; if(listType == EAll) { eventList = calendar->rawEvents(KCalCore::EventSortStartDate, KCalCore::SortDirectionAscending); } else if(listType == EDayList) { eventList = calendar->rawEventsForDate(startDate.date(),KDateTime::Spec(KDateTime::LocalZone),KCalCore::EventSortStartDate,KCalCore::SortDirectionAscending); } else if(listType == EMonthList) { eventList = calendar->rawEvents(startDate.date(),endDate.date(),KDateTime::Spec(KDateTime::LocalZone)); } else if(listType == EByUid) { KCalCore::Event::Ptr eventPtr = calendar->event(uid); eventList.append(eventPtr); } for(int i=0;i<eventList.count();i++) { IncidenceIO eventIO; KCalCore::Event *event = eventList.at(i).data(); eventIO.setType(EEvent); eventIO.setUid(event->uid()); eventIO.setDescription(event->description()); eventIO.setSummary(event->summary()); eventIO.setLocation(event->location()); eventIO.setStartDateTime(event->dtStart().toLocalZone()); if(event->allDay() || (event->dtStart().time() == event->dtEnd().time())) { eventIO.setAllDay(true); } else { eventIO.setAllDay(false); eventIO.setEndDateTime(event->dtEnd().toLocalZone()); } if ( event->hasEnabledAlarms() ) { KCalCore::Alarm::List alarmList = event->alarms(); if ( alarmList.count() > 0 ) { KCalCore::Alarm::Ptr ptr = alarmList.at(0); KCalCore::Alarm* eventAlarm = ptr.data(); eventIO.setAlarmDateTime(eventAlarm->time().toLocalZone()); if(eventAlarm->startOffset().asSeconds()==(-60*10)) eventIO.setAlarmType(E10MinB4); else if(eventAlarm->startOffset().asSeconds()==(-60*15)) eventIO.setAlarmType(E15MinB4); else if (eventAlarm->startOffset().asSeconds()==(-60*30)) eventIO.setAlarmType(E30MinB4); else if(eventAlarm->startOffset().asSeconds()==(-60*60)) eventIO.setAlarmType(E1HrB4); else if(eventAlarm->startOffset().asSeconds()==(-60*120)) eventIO.setAlarmType(E2HrsB4); else if(eventAlarm->startOffset().asDays()==(-1)) eventIO.setAlarmType(E1DayB4); else if(eventAlarm->startOffset().asDays()==(-2)) eventIO.setAlarmType(E2DaysB4); else if(eventAlarm->startOffset().asDays()==(-7)) eventIO.setAlarmType(E1WeekB4); else eventIO.setAlarmType(EOtherAlarm); } } else { eventIO.setAlarmType(ENoAlarm); } if(event->hasRecurrenceId()) qDebug() <<"Recurrence Id="<< event->recurrenceId().toString(KDateTime::LocalDate).toStdString().c_str()<<"\n\n"; if(event->recurrence()->recurrenceType()==KCalCore::Recurrence::rNone) { eventIO.setRepeatType(ENoRepeat); } else { if(event->recurrence()->recurrenceType()==KCalCore::Recurrence::rDaily) eventIO.setRepeatType(EEveryDay); else if((event->recurrence()->recurrenceType()==KCalCore::Recurrence::rWeekly) && (event->recurrence()->frequency()!=2)) eventIO.setRepeatType(EEveryWeek); else if((event->recurrence()->recurrenceType()==KCalCore::Recurrence::rWeekly) && (event->recurrence()->frequency()==2)) eventIO.setRepeatType(EEvery2Weeks); else if(event->recurrence()->recurrenceType()==KCalCore::Recurrence::rMonthlyDay) eventIO.setRepeatType(EEveryMonth); else if(event->recurrence()->recurrenceType()==KCalCore::Recurrence::rYearlyDay) eventIO.setRepeatType(EEveryYear); else eventIO.setRepeatType(EOtherRepeat); if(event->recurrence()->duration() > 0) { eventIO.setRepeatEndType(UtilMethods::EForNTimes); eventIO.setRepeatCount(event->recurrence()->duration()); } else if(event->recurrence()->endDateTime()>=event->recurrence()->startDateTime()) { eventIO.setRepeatEndType(UtilMethods::EAfterDate); eventIO.setRepeatCount(0); eventIO.setRepeatEndDateTime(event->recurrence()->endDateTime().toLocalZone()); } } eventIO.setTimeZoneOffset(event->dtStart().utcOffset()); eventIO.setTimeZoneName(event->dtStart().timeZone().name()); eventIOList.append(eventIO); } } catch(exception &e) { qDebug()<<e.what(); } return eventIOList; } QObject* CalendarController::getEventForEdit(const QString uid) { QList<IncidenceIO> listIO = getEventsFromDB(EByUid,KDateTime::currentDateTime(KDateTime::OffsetFromUTC), KDateTime::currentDateTime(KDateTime::OffsetFromUTC),uid); IncidenceIO* objIO = new IncidenceIO(listIO.at(0)); objIO->printIncidence(); return objIO; } QDateTime CalendarController::getEventPositonInView(const QString uid) { QList<IncidenceIO> listIO = getEventsFromDB(EByUid,KDateTime::currentDateTime(KDateTime::OffsetFromUTC), KDateTime::currentDateTime(KDateTime::OffsetFromUTC),uid); IncidenceIO objIO = listIO.at(0); return objIO.getStartDateTime().dateTime(); } QML_DECLARE_TYPE(CalendarController); <commit_msg>Corrected the merge request. Variables show up wrong.<commit_after>/* * Copyright 2011 Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 */ #include "calendarcontroller.h" #include "calendardbsingleton.h" #include <stdlib.h> #include <exception> #include <alarm.h> #include <icalformat.h> #include <QDebug> using namespace std; CalendarController::CalendarController(QObject *parent) : QObject(parent) { setUpCalendars(); } //Destructor CalendarController::~CalendarController() { } bool CalendarController::setUpCalendars() { bool setUpStatus=true; try { CalendarDBSingleton::instance(); calendar = CalendarDBSingleton::calendarPtr(); storage = CalendarDBSingleton::storagePtr(); //This part of code is to support multiple calendars notebook = storage->defaultNotebook().data(); if(notebook->color().isEmpty()) { notebook->setColor("Blue"); } if(notebook->description().isEmpty()){ notebook->setDescription("Default Calendar"); } nUid = notebook->uid(); storage->loadNotebookIncidences(notebook->uid()); } catch (exception &e) { setUpStatus=false; qDebug()<<e.what(); } return setUpStatus; } /** * This method adds the Event to the database * @param eventIO, The IncidenceIO object which has all the * details the user enters on the New Event form. * @return returns true if added successfully, else false */ bool CalendarController :: addModifyEvent(int actionType,QObject* eventIOObj) { bool success=true; IncidenceIO eventIO(*(IncidenceIO*)(eventIOObj)); try { KCalCore::Event::Ptr coreEvent; if(actionType == EAddEvent) { coreEvent = KCalCore::Event::Ptr(new KCalCore::Event()); } else if(actionType == EModifyEvent) { coreEvent = KCalCore::Event::Ptr(calendar->event(eventIO.getUid())); } if(coreEvent.isNull()) { return false; } coreEvent->setSummary(eventIO.getSummary()); coreEvent->setDescription(eventIO.getDescription()); coreEvent->setLocation(eventIO.getLocation()); //handle Event time handleEventTime(coreEvent,eventIO); //handle repeat handleRepeat(coreEvent,eventIO); //handle alarm processing if(eventIO.getAlarmType()!= ENoAlarm) { coreEvent->clearAlarms(); KCalCore::Alarm::Ptr eventAlarm(coreEvent->newAlarm()); handleAlarm(eventIO,eventAlarm); } if(actionType == EAddEvent) { calendar->addEvent(coreEvent,notebook->uid()); } else if(actionType == EModifyEvent) { coreEvent->setRevision(coreEvent->revision()+1); } storage->save(); } catch (exception &e) { success = false; qDebug()<< e.what(); } return success; } /** * This method deletes the event from the Calendar and the Storage * @param eventUid the unique identifier of the Event * @return true of deleted successfully,else false */ bool CalendarController::deleteEvent(QString eventUid) { bool deleted = true; try { storage->loadNotebookIncidences(nUid); KCalCore::Event::Ptr coreEvent = KCalCore::Event::Ptr(calendar->event(eventUid)); if(!coreEvent.isNull()) { deleted = calendar->deleteEvent(coreEvent); } storage->save(); }catch(exception &e){ deleted = false; qDebug()<< e.what(); } return deleted; } /** * Method to set the recurrence of the event. This method is called by addEvent method * @param coreEvent, event whose recurrence has to be set * @param eventIO, the IO object from the UI */ void CalendarController::handleRepeat(KCalCore::Event::Ptr coreEventPtr,const IncidenceIO& eventIO) { try { if(eventIO.getRepeatType()==ENoRepeat){ /*eventRecurrence->setDaily(1); eventRecurrence->setDuration(1); if(eventIO.isAllDay()) { eventRecurrence->setEndDateTime(eventIO.getStartDateTime()); } else { eventRecurrence->setEndDateTime(eventIO.getEndDateTime()); }*/ } else { KCalCore::Recurrence *eventRecurrence = coreEventPtr->recurrence(); switch(eventIO.getRepeatType()) { case EEveryDay: { eventRecurrence->setDaily(1); break; } case EEveryWeek: { eventRecurrence->setWeekly(1); break; } case EEvery2Weeks: { eventRecurrence->setWeekly(2,EMonday); break; } case EEveryMonth: { eventRecurrence->setMonthly(1); break; } case EEveryYear: { eventRecurrence->setYearly(1); break; } case EOtherRepeat: { qDebug()<<"Not Sure At this moment"; eventRecurrence->setWeekly(1); break; } default: { eventRecurrence->clear(); break; } }//end of switch if(eventIO.getRepeatEndType() == UtilMethods::EForNTimes) { eventRecurrence->setDuration(eventIO.getRepeatCount()); } else if(eventIO.getRepeatEndType() == UtilMethods::EAfterDate) { eventRecurrence->setEndDateTime(eventIO.getRepeatEndDateTime()); } }//end of else } catch (exception &e) { qDebug()<<e.what(); } return; } /** * This method handles allday flag in an event */ //Might need some additional processing. //So put the logic seperately into a method instead of cluttering the addEvent method void CalendarController::handleEventTime(KCalCore::Event::Ptr coreEventPtr,const IncidenceIO& eventIO) { try{ coreEventPtr->setDtStart(eventIO.getStartDateTime()); if(eventIO.isAllDay()) { coreEventPtr->setAllDay(true); if(coreEventPtr->hasEndDate()) { coreEventPtr->setDtEnd(eventIO.getStartDateTime());} } else { coreEventPtr->setAllDay(false); coreEventPtr->setDtEnd(eventIO.getEndDateTime()); } } catch(exception &e) { qDebug()<<e.what(); } return; } /** * This method handles setting alarm in an event * @param eventIO, the IncidenceIO object from the UI * @param eventAlarm, the KCalCore::Alarm object with its parent set */ void CalendarController::handleAlarm(const IncidenceIO& eventIO,KCalCore::Alarm::Ptr eventAlarm) { try{ eventAlarm->setText(eventIO.getSummary()); eventAlarm->setDisplayAlarm(eventIO.getSummary()); eventAlarm->setEnabled(true); switch(eventIO.getAlarmType()) { case E10MinB4: default: //snooze with 5min interval eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration( -60*10 ) ); break; case E15MinB4: { eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration( -60*15 ) ); break; } case E30MinB4: { eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration( -60*30 ) ); break; } case E1HrB4: { eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration( -60*60 ) ); break; } case E2HrsB4: { eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration( -60*120 ) ); break; } case E1DayB4: { eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration(-1,KCalCore::Duration::Days) ); break; } case E2DaysB4: { eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration(-2,KCalCore::Duration::Days) ); break; } case E1WeekB4: { eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration(-7,KCalCore::Duration::Days) ); break; } case EOtherAlarm: { qDebug()<<"Not Sure At this moment"; eventAlarm->setSnoozeTime( KCalCore::Duration( 60*5 ) ); eventAlarm->setRepeatCount(1); eventAlarm->setStartOffset( KCalCore::Duration( -60*15 ) ); break; } }//end of switch qDebug()<<"Exiting handleAlarm\n"; } catch(exception &e) { qDebug()<<e.what(); } return; } QList<IncidenceIO> CalendarController::getEventsFromDB(int listType,KDateTime startDate, KDateTime endDate,const QString uid) { QList<IncidenceIO> eventIOList; try { KCalCore::Event::List eventList; if(listType == EAll) { eventList = calendar->rawEvents(KCalCore::EventSortStartDate, KCalCore::SortDirectionAscending); } else if(listType == EDayList) { eventList = calendar->rawEventsForDate(startDate.date(),KDateTime::Spec(KDateTime::LocalZone),KCalCore::EventSortStartDate,KCalCore::SortDirectionAscending); } else if(listType == EMonthList) { eventList = calendar->rawEvents(startDate.date(),endDate.date(),KDateTime::Spec(KDateTime::LocalZone)); } else if(listType == EByUid) { KCalCore::Event::Ptr eventPtr = calendar->event(uid); eventList.append(eventPtr); } for(int i=0;i<eventList.count();i++) { IncidenceIO eventIO; KCalCore::Event *event = eventList.at(i).data(); eventIO.setType(EEvent); eventIO.setUid(event->uid()); eventIO.setDescription(event->description()); eventIO.setSummary(event->summary()); eventIO.setLocation(event->location()); eventIO.setStartDateTime(event->dtStart().toLocalZone()); if(event->allDay() || (event->dtStart().time() == event->dtEnd().time())) { eventIO.setAllDay(true); } else { eventIO.setAllDay(false); eventIO.setEndDateTime(event->dtEnd().toLocalZone()); } if ( event->hasEnabledAlarms() ) { KCalCore::Alarm::List alarmList = event->alarms(); if ( alarmList.count() > 0 ) { KCalCore::Alarm::Ptr ptr = alarmList.at(0); KCalCore::Alarm* eventAlarm = ptr.data(); eventIO.setAlarmDateTime(eventAlarm->time().toLocalZone()); if(eventAlarm->startOffset().asSeconds()==(-60*10)) eventIO.setAlarmType(E10MinB4); else if(eventAlarm->startOffset().asSeconds()==(-60*15)) eventIO.setAlarmType(E15MinB4); else if (eventAlarm->startOffset().asSeconds()==(-60*30)) eventIO.setAlarmType(E30MinB4); else if(eventAlarm->startOffset().asSeconds()==(-60*60)) eventIO.setAlarmType(E1HrB4); else if(eventAlarm->startOffset().asSeconds()==(-60*120)) eventIO.setAlarmType(E2HrsB4); else if(eventAlarm->startOffset().asDays()==(-1)) eventIO.setAlarmType(E1DayB4); else if(eventAlarm->startOffset().asDays()==(-2)) eventIO.setAlarmType(E2DaysB4); else if(eventAlarm->startOffset().asDays()==(-7)) eventIO.setAlarmType(E1WeekB4); else eventIO.setAlarmType(EOtherAlarm); } } else { eventIO.setAlarmType(ENoAlarm); } if(event->hasRecurrenceId()) qDebug() <<"Recurrence Id="<< event->recurrenceId().toString(KDateTime::LocalDate).toStdString().c_str()<<"\n\n"; if(event->recurrence()->recurrenceType()==KCalCore::Recurrence::rNone) { eventIO.setRepeatType(ENoRepeat); } else { if(event->recurrence()->recurrenceType()==KCalCore::Recurrence::rDaily) eventIO.setRepeatType(EEveryDay); else if((event->recurrence()->recurrenceType()==KCalCore::Recurrence::rWeekly) && (event->recurrence()->frequency()!=2)) eventIO.setRepeatType(EEveryWeek); else if((event->recurrence()->recurrenceType()==KCalCore::Recurrence::rWeekly) && (event->recurrence()->frequency()==2)) eventIO.setRepeatType(EEvery2Weeks); else if(event->recurrence()->recurrenceType()==KCalCore::Recurrence::rMonthlyDay) eventIO.setRepeatType(EEveryMonth); else if(event->recurrence()->recurrenceType()==KCalCore::Recurrence::rYearlyDay) eventIO.setRepeatType(EEveryYear); else eventIO.setRepeatType(EOtherRepeat); if(event->recurrence()->duration() > 0) { eventIO.setRepeatEndType(UtilMethods::EForNTimes); eventIO.setRepeatCount(event->recurrence()->duration()); } else if(event->recurrence()->endDateTime()>=event->recurrence()->startDateTime()) { eventIO.setRepeatEndType(UtilMethods::EAfterDate); eventIO.setRepeatCount(0); eventIO.setRepeatEndDateTime(event->recurrence()->endDateTime().toLocalZone()); } } eventIO.setTimeZoneOffset(event->dtStart().utcOffset()); eventIO.setTimeZoneName(event->dtStart().timeZone().name()); eventIOList.append(eventIO); } } catch(exception &e) { qDebug()<<e.what(); } return eventIOList; } QObject* CalendarController::getEventForEdit(const QString uid) { QList<IncidenceIO> listIO = getEventsFromDB(EByUid,KDateTime::currentDateTime(KDateTime::OffsetFromUTC), KDateTime::currentDateTime(KDateTime::OffsetFromUTC),uid); IncidenceIO* objIO = new IncidenceIO(listIO.at(0)); objIO->printIncidence(); return objIO; } QDateTime CalendarController::getEventPositonInView(const QString uid) { QList<IncidenceIO> listIO = getEventsFromDB(EByUid,KDateTime::currentDateTime(KDateTime::OffsetFromUTC), KDateTime::currentDateTime(KDateTime::OffsetFromUTC),uid); IncidenceIO objIO = listIO.at(0); return objIO.getStartDateTime().dateTime(); } QML_DECLARE_TYPE(CalendarController); <|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUIMenuBase.cpp created: 5/4/2005 author: Tomas Lindquist Olsen (based on code by Paul D Turner) purpose: Implementation of MenuBase widget base class *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "elements/CEGUIMenuBase.h" #include "elements/CEGUIPopupMenu.h" #include "elements/CEGUIMenuItem.h" // Start of CEGUI namespace section namespace CEGUI { /************************************************************************* Constants *************************************************************************/ // event strings const String MenuBase::EventNamespace("MenuBase"); const String MenuBase::EventPopupOpened("PopupOpened"); const String MenuBase::EventPopupClosed("PopupClosed"); /************************************************************************* Constructor for MenuBase base class. *************************************************************************/ MenuBase::MenuBase(const String& type, const String& name) : ItemListBase(type, name), d_itemSpacing(0.0f), d_popupItem(0), d_allowMultiplePopups(false), d_autoCloseNestedPopups(false) { // add properties for MenuBase class addMenuBaseProperties(); } /************************************************************************* Destructor for MenuBase base class. *************************************************************************/ MenuBase::~MenuBase(void) { } /************************************************************************* Change the currently open MenuItem PopupMenu *************************************************************************/ void MenuBase::changePopupMenuItem(MenuItem* item) { if (!d_allowMultiplePopups && d_popupItem == item) return; if (!d_allowMultiplePopups && d_popupItem != 0) { WindowEventArgs we(d_popupItem->getPopupMenu()); d_popupItem->closePopupMenu(false); d_popupItem = 0; onPopupClosed(we); } if (item) { d_popupItem = item; d_popupItem->openPopupMenu(false); WindowEventArgs we(d_popupItem->getPopupMenu()); onPopupOpened(we); } } /************************************************************************* handler invoked internally when the a MenuItem attached to this MenuBase opens its popup. *************************************************************************/ void MenuBase::onPopupOpened(WindowEventArgs& e) { fireEvent(EventPopupOpened, e, EventNamespace); } /************************************************************************* handler invoked internally when the a MenuItem attached to this MenuBase closes its popup. *************************************************************************/ void MenuBase::onPopupClosed(WindowEventArgs& e) { fireEvent(EventPopupClosed, e, EventNamespace); } /************************************************************************ Add properties for this widget *************************************************************************/ void MenuBase::addMenuBaseProperties(void) { const String propertyOrigin("MenuBase"); CEGUI_DEFINE_PROPERTY(MenuBase, float, "ItemSpacing", "Property to get/set the item spacing of the menu. Value is a float.", &MenuBase::setItemSpacing, &MenuBase::getItemSpacing, 10.0f ); CEGUI_DEFINE_PROPERTY(MenuBase, bool, "AllowMultiplePopups", "Property to get/set the state of the allow multiple popups setting for the menu. Value is either \"True\" or \"False\".", &MenuBase::setAllowMultiplePopups, &MenuBase::isMultiplePopupsAllowed, false ); CEGUI_DEFINE_PROPERTY(MenuBase, bool, "AllowMultiplePopups", "Property to get/set the state of the allow multiple popups setting for the menu. Value is either \"True\" or \"False\".", &MenuBase::setAutoCloseNestedPopups, &MenuBase::getAutoCloseNestedPopups, false ); } /************************************************************************ Set if multiple child popup menus are allowed simultaneously *************************************************************************/ void MenuBase::setAllowMultiplePopups(bool setting) { if (d_allowMultiplePopups != setting) { // TODO : // close all popups except perhaps the last one opened! d_allowMultiplePopups = setting; } } void MenuBase::setPopupMenuItemClosing() { if (d_popupItem) { d_popupItem->startPopupClosing(); } } //----------------------------------------------------------------------------// void MenuBase::onChildRemoved(WindowEventArgs& e) { // if the removed window was our tracked popup item, zero ptr to it. if (e.window == d_popupItem) d_popupItem = 0; // base class version ItemListBase::onChildRemoved(e); } void MenuBase::onHidden(WindowEventArgs& e) { if (!getAutoCloseNestedPopups()) return; changePopupMenuItem(0); if (d_allowMultiplePopups) { for (size_t i = 0; i < d_listItems.size(); ++i) { if (!d_listItems[i]) continue; MenuItem* menuItem = dynamic_cast<MenuItem*>(d_listItems[i]); if (!menuItem) continue; if (!menuItem->getPopupMenu()) continue; WindowEventArgs we(menuItem->getPopupMenu()); menuItem->closePopupMenu(false); onPopupClosed(we); } } } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>MOD: fix the Property in CEGUIMenuBase<commit_after>/*********************************************************************** filename: CEGUIMenuBase.cpp created: 5/4/2005 author: Tomas Lindquist Olsen (based on code by Paul D Turner) purpose: Implementation of MenuBase widget base class *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "elements/CEGUIMenuBase.h" #include "elements/CEGUIPopupMenu.h" #include "elements/CEGUIMenuItem.h" // Start of CEGUI namespace section namespace CEGUI { /************************************************************************* Constants *************************************************************************/ // event strings const String MenuBase::EventNamespace("MenuBase"); const String MenuBase::EventPopupOpened("PopupOpened"); const String MenuBase::EventPopupClosed("PopupClosed"); /************************************************************************* Constructor for MenuBase base class. *************************************************************************/ MenuBase::MenuBase(const String& type, const String& name) : ItemListBase(type, name), d_itemSpacing(0.0f), d_popupItem(0), d_allowMultiplePopups(false), d_autoCloseNestedPopups(false) { // add properties for MenuBase class addMenuBaseProperties(); } /************************************************************************* Destructor for MenuBase base class. *************************************************************************/ MenuBase::~MenuBase(void) { } /************************************************************************* Change the currently open MenuItem PopupMenu *************************************************************************/ void MenuBase::changePopupMenuItem(MenuItem* item) { if (!d_allowMultiplePopups && d_popupItem == item) return; if (!d_allowMultiplePopups && d_popupItem != 0) { WindowEventArgs we(d_popupItem->getPopupMenu()); d_popupItem->closePopupMenu(false); d_popupItem = 0; onPopupClosed(we); } if (item) { d_popupItem = item; d_popupItem->openPopupMenu(false); WindowEventArgs we(d_popupItem->getPopupMenu()); onPopupOpened(we); } } /************************************************************************* handler invoked internally when the a MenuItem attached to this MenuBase opens its popup. *************************************************************************/ void MenuBase::onPopupOpened(WindowEventArgs& e) { fireEvent(EventPopupOpened, e, EventNamespace); } /************************************************************************* handler invoked internally when the a MenuItem attached to this MenuBase closes its popup. *************************************************************************/ void MenuBase::onPopupClosed(WindowEventArgs& e) { fireEvent(EventPopupClosed, e, EventNamespace); } /************************************************************************ Add properties for this widget *************************************************************************/ void MenuBase::addMenuBaseProperties(void) { const String propertyOrigin("MenuBase"); CEGUI_DEFINE_PROPERTY(MenuBase, float, "ItemSpacing", "Property to get/set the item spacing of the menu. Value is a float.", &MenuBase::setItemSpacing, &MenuBase::getItemSpacing, 10.0f ); CEGUI_DEFINE_PROPERTY(MenuBase, bool, "AllowMultiplePopups", "Property to get/set the state of the allow multiple popups setting for the menu. Value is either \"True\" or \"False\".", &MenuBase::setAllowMultiplePopups, &MenuBase::isMultiplePopupsAllowed, false ); CEGUI_DEFINE_PROPERTY(MenuBase, bool, "AutoCloseNestedPopups", "Property to set if the menu should close all its open child popups, when it gets hidden. Value is either \"True\" or \"False\".", &MenuBase::setAutoCloseNestedPopups, &MenuBase::getAutoCloseNestedPopups, false ); } /************************************************************************ Set if multiple child popup menus are allowed simultaneously *************************************************************************/ void MenuBase::setAllowMultiplePopups(bool setting) { if (d_allowMultiplePopups != setting) { // TODO : // close all popups except perhaps the last one opened! d_allowMultiplePopups = setting; } } void MenuBase::setPopupMenuItemClosing() { if (d_popupItem) { d_popupItem->startPopupClosing(); } } //----------------------------------------------------------------------------// void MenuBase::onChildRemoved(WindowEventArgs& e) { // if the removed window was our tracked popup item, zero ptr to it. if (e.window == d_popupItem) d_popupItem = 0; // base class version ItemListBase::onChildRemoved(e); } void MenuBase::onHidden(WindowEventArgs& e) { if (!getAutoCloseNestedPopups()) return; changePopupMenuItem(0); if (d_allowMultiplePopups) { for (size_t i = 0; i < d_listItems.size(); ++i) { if (!d_listItems[i]) continue; MenuItem* menuItem = dynamic_cast<MenuItem*>(d_listItems[i]); if (!menuItem) continue; if (!menuItem->getPopupMenu()) continue; WindowEventArgs we(menuItem->getPopupMenu()); menuItem->closePopupMenu(false); onPopupClosed(we); } } } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before>//===------ TwoIDPass - inserts 2 ID CFI checks ---------------------------===// // // This file inserts IDs and checks for a CFI implementation based on Abadi's // two ID CFI. An ID is used to check that indirect branches always target // beginning of functions or basic blocks, and a second ID is used to check // that returns always target valid return sites. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "TwoIDPass" #include "llvm/ADT/Statistic.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Value.h" #include "llvm/IR/Function.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/Support/raw_ostream.h" #include <set> using namespace llvm; #define CFI_INSERT_INTRINSIC "llvm.cfiid" #define CFI_CHECK_TAR_INTRINSIC "llvm.cfichecktar" #define CFI_CHECK_RET_INTRINSIC "llvm.cficheckret" #define CFI_ABORT "cfi_abort" #define MAX 0xFFFF namespace { /** * @brief CFILowering class - handles creation of llvm intrinsic * functions */ class CFILowering { typedef std::vector<std::string> ArgNames; typedef std::vector<llvm::Type*> ArgTypes; typedef std::vector<llvm::Value*> ArgVals; //cfi intrinsic functions, all are of the form: //@llvm.arm.cfiid(i32 dest_id) Function *cfiInsertID; Function *cfiCheckTarget; Function *cfiCheckReturn; /** * @brief Creates a function * * @return Function pointer to newly created function * * @arg module - current function * @arg retType - return type of function * @arg theArgTypes - types for function args * @arg theArgNames - names for function args * @arg functName - name of function * @arg linkage - linkage type * @arg declarationOnly - if the function is only a declaration * @arg isVarArg - if function has variable number of arguments */ Function *createFunction(llvm::Module &module, llvm::Type *retType, const ArgTypes &theArgTypes, const ArgNames &theArgNames, const std::string &functName, llvm::GlobalValue::LinkageTypes linkage, bool declarationOnly, bool isVarArg) { llvm::FunctionType *functType = llvm::FunctionType::get(retType, theArgTypes, isVarArg); llvm::Function *ret = llvm::Function::Create(functType, linkage, functName, &module); if (!ret || declarationOnly) return(ret); return NULL; } /** * @brief creates a CFI intrinsic function * * @return Function pointer * * @arg funcName - name of llvm intrinsic function * @arg M - current module */ Function *createCfiFunc(std::string funcName, Module &M) { //create the cfiid_intrinsic function llvm::IRBuilder<> builder(M.getContext()); //function llvm::Type *retType = builder.getVoidTy(); //function arg names ArgNames argNames; argNames.push_back("dest_id"); //function arg types ArgTypes argTypes; argTypes.push_back(builder.getInt32Ty()); //ex. call void @llvm.arm.cfiid(i32 dest_id) Function *cfiFunc = createFunction(M, retType, argTypes, argNames, funcName, llvm::Function::ExternalLinkage, true, false); return cfiFunc; } public: /** * @brief initializes CFILowering object by initializing cfi * intrinsic functions * * @arg M - module */ CFILowering(Module &M) { cfiInsertID = createCfiFunc(CFI_INSERT_INTRINSIC, M); cfiCheckTarget = createCfiFunc(CFI_CHECK_TAR_INTRINSIC, M); cfiCheckReturn = createCfiFunc(CFI_CHECK_RET_INTRINSIC, M); } /** * @brief gets cfiInsertID function * * @return pointer to function */ Function *getCfiInsertID() { return cfiInsertID; } /** * @brief gets cfiCheckTarget function * * @return pointer to function */ Function *getCfiCheckTarget() { return cfiCheckTarget; } /** * @brief gets cfiCheckReturn function * * @return pointer to function */ Function *getCfiCheckReturn() { return cfiCheckReturn; } /** * @brief create cfi_abort function: * * void abort() * { * while(1); * } * * @return void * * @arg M - module to create function in */ void createAbort(Module &M) { Constant *c = M.getOrInsertFunction(CFI_ABORT, Type::getVoidTy(M.getContext()), NULL); Function *abort = dyn_cast<Function>(c); abort->setCallingConv(CallingConv::C); BasicBlock* entry = BasicBlock::Create(getGlobalContext(), "entry", abort); BasicBlock* loop = BasicBlock::Create(getGlobalContext(), "loop", abort); IRBuilder<> builder(entry); builder.CreateBr(loop); builder.SetInsertPoint(loop); builder.CreateBr(loop); } }; struct TwoIDPass : public ModulePass { static char ID; TwoIDPass() : ModulePass(ID) {} typedef std::set<BasicBlock *> BBSet; Function *cfiInsertID; Function *cfiCheckTarget; Function *cfiCheckReturn; Value *targetID; Value *returnID; /** * @brief Find all indirect branch targets and add them to indTargets * * @return void * * @arg F - function to iterate over * @arg indTargets - set of indirect blocks in function */ void findIndTargets(Function *F, BBSet &indTargets) { //for all basic blocks in function Function::iterator FB, FE; for (FB = F->begin(), FE = F->end(); FB != FE; FB++) { BasicBlock *B = &*FB; //check if basic block ends with indirect branch //(TODO add other checks: exceptions, longjumps, trampolines?) if (TerminatorInst *TI = B->getTerminator()) { if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) { //add all possible successors to indBrDestMap int n = IBI->getNumSuccessors(); for (int j = 0; j < n; j++) { indTargets.insert(IBI->getSuccessor(j)); } } } } } /** * @brief Insert targetID at the beginning of all basic blocks that * are potentially indirect targets * * @return void * * @arg M - current module * @arg builder - IRBuilder */ void insertTargetIDs(Module &M, llvm::IRBuilder<> &builder) { Module::iterator MB, ME; for (MB = M.begin(), ME = M.end(); MB != ME; MB++) { Function *F = &*MB; if (F->isDeclaration()) continue; //find all indirect target blocks, including entry block BBSet indTargets; if (F->getName() != "main") indTargets.insert(&F->getEntryBlock()); findIndTargets(F, indTargets); //for all targets in indTargets, insert targetID at beginning //of block BBSet::iterator BB, BE; for (BB = indTargets.begin(), BE = indTargets.end(); BB != BE; BB++) { BasicBlock::iterator II = (*BB)->begin(); builder.SetInsertPoint(II); builder.CreateCall(cfiInsertID, targetID); } } } /** * @brief Insert return IDs after all call sites in function, and * insert checks before indirect calls/branches and before returns * * @return void * * @arg F - current function * @arg builder - IRBuilder */ void insertChecksAndRetIDs(Function &F, llvm::IRBuilder<> &builder) { std::string name = F.getName(); //Insert check before/after each call instruction, //and before each return Function::iterator FB, FE; for (FB = F.begin(), FE = F.end(); FB != FE; FB++) { BasicBlock::iterator BB, BE; for(BB = FB->begin(), BE = FB->end(); BB != BE; BB++) { Instruction *I = &*BB; if (CallInst* callInst = dyn_cast<CallInst>(I)) { Function *calledFunc = callInst->getCalledFunction(); //Only insert checks before indirect calls if (calledFunc == NULL) { builder.SetInsertPoint(BB); builder.CreateCall(cfiCheckTarget, targetID); } if (calledFunc != NULL && !calledFunc->isIntrinsic()) { BB++; builder.SetInsertPoint(BB); builder.CreateCall(cfiInsertID, returnID); } } else if (dyn_cast<IndirectBrInst>(I)) { builder.SetInsertPoint(BB); builder.CreateCall(cfiCheckTarget, targetID); } else if (dyn_cast<ReturnInst>(I)) { if (name != "main") { builder.SetInsertPoint(BB); builder.CreateCall(cfiCheckReturn, returnID); } } } } } /* * prints functions */ void printFunction(Function &F) { errs() << F.getName() << '\n'; Function::iterator FB, FE; for(FB = F.begin(), FE = F.end(); FB != FE; FB++) { errs() << "\t[Block]" << '\n'; FB->dump(); } } /** * @brief Insert an ID before each function, indirect target block, * and after each callsite. Use the same ID for all functions and * indirect target blocks, and the same ID for all return sites, * creating a course grained CFI implementation with only two IDs * * @arg M - module reference */ virtual bool runOnModule(Module &M) { //seed rand with current time srand(time(NULL)); //generate IDs llvm::IRBuilder<> builder(M.getContext()); targetID = llvm::ConstantInt::get(builder.getInt32Ty(), rand() % MAX); returnID = llvm::ConstantInt::get(builder.getInt32Ty(), rand() % MAX); //generate intrinsic functions CFILowering cfil = CFILowering(M); cfiInsertID = cfil.getCfiInsertID(); cfiCheckTarget = cfil.getCfiCheckTarget(); cfiCheckReturn = cfil.getCfiCheckReturn(); //insert IDs and checks Module::iterator MB, ME; for (MB = M.begin(), ME = M.end(); MB != ME; MB++) { Function &F = *MB; insertChecksAndRetIDs(F, builder); } insertTargetIDs(M, builder); //create abort function cfil.createAbort(M); return false; } }; } char TwoIDPass::ID = 0; static RegisterPass<TwoIDPass> X("TwoIDPass", "Two ID CFI Pass"); <commit_msg>two id pass stats<commit_after>//===------ TwoIDPass - inserts 2 ID CFI checks ---------------------------===// // // This file inserts IDs and checks for a CFI implementation based on Abadi's // two ID CFI. An ID is used to check that indirect branches always target // beginning of functions or basic blocks, and a second ID is used to check // that returns always target valid return sites. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "TwoIDPass" #include "llvm/ADT/Statistic.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Value.h" #include "llvm/IR/Function.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/Support/raw_ostream.h" #include <set> using namespace llvm; #define CFI_INSERT_INTRINSIC "llvm.cfiid" #define CFI_CHECK_TAR_INTRINSIC "llvm.cfichecktar" #define CFI_CHECK_RET_INTRINSIC "llvm.cficheckret" #define CFI_ABORT "cfi_abort" #define MAX 0xFFFF STATISTIC(STAT_ITRANSFER, "indirect transfers (icall, ibr, ret)"); STATISTIC(STAT_ICALL, "indirect calls" ); STATISTIC(STAT_CALL, "direct calls" ); STATISTIC(STAT_IBRANCH, "indirect branches"); STATISTIC(STAT_RETURN, "returns"); STATISTIC(STAT_ICALL_TAR, "valid indirect call/branch targets"); STATISTIC(STAT_RET_TAR, "valid return targets"); namespace { /** * @brief CFILowering class - handles creation of llvm intrinsic * functions */ class CFILowering { typedef std::vector<std::string> ArgNames; typedef std::vector<llvm::Type*> ArgTypes; typedef std::vector<llvm::Value*> ArgVals; //cfi intrinsic functions, all are of the form: //@llvm.arm.cfiid(i32 dest_id) Function *cfiInsertID; Function *cfiCheckTarget; Function *cfiCheckReturn; /** * @brief Creates a function * * @return Function pointer to newly created function * * @arg module - current function * @arg retType - return type of function * @arg theArgTypes - types for function args * @arg theArgNames - names for function args * @arg functName - name of function * @arg linkage - linkage type * @arg declarationOnly - if the function is only a declaration * @arg isVarArg - if function has variable number of arguments */ Function *createFunction(llvm::Module &module, llvm::Type *retType, const ArgTypes &theArgTypes, const ArgNames &theArgNames, const std::string &functName, llvm::GlobalValue::LinkageTypes linkage, bool declarationOnly, bool isVarArg) { llvm::FunctionType *functType = llvm::FunctionType::get(retType, theArgTypes, isVarArg); llvm::Function *ret = llvm::Function::Create(functType, linkage, functName, &module); if (!ret || declarationOnly) return(ret); return NULL; } /** * @brief creates a CFI intrinsic function * * @return Function pointer * * @arg funcName - name of llvm intrinsic function * @arg M - current module */ Function *createCfiFunc(std::string funcName, Module &M) { //create the cfiid_intrinsic function llvm::IRBuilder<> builder(M.getContext()); //function llvm::Type *retType = builder.getVoidTy(); //function arg names ArgNames argNames; argNames.push_back("dest_id"); //function arg types ArgTypes argTypes; argTypes.push_back(builder.getInt32Ty()); //ex. call void @llvm.arm.cfiid(i32 dest_id) Function *cfiFunc = createFunction(M, retType, argTypes, argNames, funcName, llvm::Function::ExternalLinkage, true, false); return cfiFunc; } public: /** * @brief initializes CFILowering object by initializing cfi * intrinsic functions * * @arg M - module */ CFILowering(Module &M) { cfiInsertID = createCfiFunc(CFI_INSERT_INTRINSIC, M); cfiCheckTarget = createCfiFunc(CFI_CHECK_TAR_INTRINSIC, M); cfiCheckReturn = createCfiFunc(CFI_CHECK_RET_INTRINSIC, M); } /** * @brief gets cfiInsertID function * * @return pointer to function */ Function *getCfiInsertID() { return cfiInsertID; } /** * @brief gets cfiCheckTarget function * * @return pointer to function */ Function *getCfiCheckTarget() { return cfiCheckTarget; } /** * @brief gets cfiCheckReturn function * * @return pointer to function */ Function *getCfiCheckReturn() { return cfiCheckReturn; } /** * @brief create cfi_abort function: * * void abort() * { * while(1); * } * * @return void * * @arg M - module to create function in */ void createAbort(Module &M) { Constant *c = M.getOrInsertFunction(CFI_ABORT, Type::getVoidTy(M.getContext()), NULL); Function *abort = dyn_cast<Function>(c); abort->setCallingConv(CallingConv::C); BasicBlock* entry = BasicBlock::Create(getGlobalContext(), "entry", abort); BasicBlock* loop = BasicBlock::Create(getGlobalContext(), "loop", abort); IRBuilder<> builder(entry); builder.CreateBr(loop); builder.SetInsertPoint(loop); builder.CreateBr(loop); } }; struct TwoIDPass : public ModulePass { static char ID; TwoIDPass() : ModulePass(ID) {} typedef std::set<BasicBlock *> BBSet; Function *cfiInsertID; Function *cfiCheckTarget; Function *cfiCheckReturn; Value *targetID; Value *returnID; /** * @brief Find all indirect branch targets and add them to indTargets * * @return void * * @arg F - function to iterate over * @arg indTargets - set of indirect blocks in function */ void findIndTargets(Function *F, BBSet &indTargets) { //for all basic blocks in function Function::iterator FB, FE; for (FB = F->begin(), FE = F->end(); FB != FE; FB++) { BasicBlock *B = &*FB; //check if basic block ends with indirect branch //(TODO add other checks: exceptions, longjumps, trampolines?) if (TerminatorInst *TI = B->getTerminator()) { if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) { //add all possible successors to indBrDestMap int n = IBI->getNumSuccessors(); for (int j = 0; j < n; j++) { indTargets.insert(IBI->getSuccessor(j)); } } } } } /** * @brief Insert targetID at the beginning of all basic blocks that * are potentially indirect targets * * @return void * * @arg M - current module * @arg builder - IRBuilder */ void insertTargetIDs(Module &M, llvm::IRBuilder<> &builder) { Module::iterator MB, ME; for (MB = M.begin(), ME = M.end(); MB != ME; MB++) { Function *F = &*MB; if (F->isDeclaration()) continue; //find all indirect target blocks, including entry block BBSet indTargets; if (F->getName() != "main") indTargets.insert(&F->getEntryBlock()); findIndTargets(F, indTargets); //for all targets in indTargets, insert targetID at beginning //of block BBSet::iterator BB, BE; for (BB = indTargets.begin(), BE = indTargets.end(); BB != BE; BB++) { BasicBlock::iterator II = (*BB)->begin(); builder.SetInsertPoint(II); builder.CreateCall(cfiInsertID, targetID); STAT_ICALL_TAR++; } } } /** * @brief Insert return IDs after all call sites in function, and * insert checks before indirect calls/branches and before returns * * @return void * * @arg F - current function * @arg builder - IRBuilder */ void insertChecksAndRetIDs(Function &F, llvm::IRBuilder<> &builder) { std::string name = F.getName(); //Insert check before/after each call instruction, //and before each return Function::iterator FB, FE; for (FB = F.begin(), FE = F.end(); FB != FE; FB++) { BasicBlock::iterator BB, BE; for(BB = FB->begin(), BE = FB->end(); BB != BE; BB++) { Instruction *I = &*BB; if (CallInst* callInst = dyn_cast<CallInst>(I)) { Function *calledFunc = callInst->getCalledFunction(); //Only insert checks before indirect calls if (calledFunc == NULL) { builder.SetInsertPoint(BB); builder.CreateCall(cfiCheckTarget, targetID); //indirect transfer site STAT_ITRANSFER++; STAT_ICALL++; } //Insert IDs after non-intrinsic if (calledFunc != NULL && !calledFunc->isIntrinsic()) { BB++; builder.SetInsertPoint(BB); builder.CreateCall(cfiInsertID, returnID); //direct callsite STAT_CALL++; STAT_RET_TAR++; } } else if (dyn_cast<IndirectBrInst>(I)) { builder.SetInsertPoint(BB); builder.CreateCall(cfiCheckTarget, targetID); //indirect transfer site STAT_ITRANSFER++; STAT_IBRANCH++; } else if (dyn_cast<ReturnInst>(I)) { if (name != "main") { builder.SetInsertPoint(BB); builder.CreateCall(cfiCheckReturn, returnID); //indirect transfer site STAT_ITRANSFER++; STAT_RETURN++; } } } } } /* * prints functions */ void printFunction(Function &F) { errs() << F.getName() << '\n'; Function::iterator FB, FE; for(FB = F.begin(), FE = F.end(); FB != FE; FB++) { errs() << "\t[Block]" << '\n'; FB->dump(); } } /** * @brief Insert an ID before each function, indirect target block, * and after each callsite. Use the same ID for all functions and * indirect target blocks, and the same ID for all return sites, * creating a course grained CFI implementation with only two IDs * * @arg M - module reference */ virtual bool runOnModule(Module &M) { //seed rand with current time srand(time(NULL)); //generate IDs llvm::IRBuilder<> builder(M.getContext()); targetID = llvm::ConstantInt::get(builder.getInt32Ty(), rand() % MAX); returnID = llvm::ConstantInt::get(builder.getInt32Ty(), rand() % MAX); //generate intrinsic functions CFILowering cfil = CFILowering(M); cfiInsertID = cfil.getCfiInsertID(); cfiCheckTarget = cfil.getCfiCheckTarget(); cfiCheckReturn = cfil.getCfiCheckReturn(); //insert IDs and checks Module::iterator MB, ME; for (MB = M.begin(), ME = M.end(); MB != ME; MB++) { Function &F = *MB; insertChecksAndRetIDs(F, builder); } insertTargetIDs(M, builder); //create abort function cfil.createAbort(M); return false; } }; } char TwoIDPass::ID = 0; static RegisterPass<TwoIDPass> X("TwoIDPass", "Two ID CFI Pass"); <|endoftext|>
<commit_before>#include "chainerx/float16.h" #include <algorithm> #include <cmath> #include <limits> #include <vector> #include <gtest/gtest.h> namespace chainerx { namespace { bool IsNan(Float16 x) { uint16_t exp = x.data() & 0x7c00; uint16_t frac = x.data() & 0x03ff; return exp == 0x7c00 && frac != 0x0000; } // Checks if `d` is equal to FromFloat16(ToFloat16(d)) with tolerance `tol`. // This function cannot take NaN as a parameter. The cast of NaN is tested in `Float16Nan`. void CheckToFloat16FromFloat16Near(double d, double tol) { Float16 h{d}; Float16 f{static_cast<float>(d)}; EXPECT_EQ(h.data(), f.data()); float f_result = static_cast<float>(h); double d_result = static_cast<double>(h); ASSERT_FALSE(std::isnan(d)); EXPECT_FALSE(std::isnan(f_result)); EXPECT_FALSE(std::isnan(d_result)); EXPECT_FALSE(IsNan(h)); if (std::isinf(d)) { // Signed inf EXPECT_EQ(d, f_result); EXPECT_EQ(d, d_result); } else { // Absolute error or relative error should be less or equal to tol. tol = std::max(tol, tol * std::abs(d)); EXPECT_NEAR(d, f_result, tol); EXPECT_NEAR(d, d_result, tol); } } // Checks if `h` is equal to ToFloat16(FromFloat16(h)) exactly. // This function cannot take NaN as a parameter. The cast of NaN is tested in `Float16Nan`. void CheckFromFloat16ToFloat16Eq(Float16 h) { float f = static_cast<float>(h); double d = static_cast<double>(h); EXPECT_EQ(d, static_cast<double>(f)); ASSERT_FALSE(IsNan(h)); EXPECT_FALSE(std::isnan(f)); EXPECT_FALSE(std::isnan(d)); EXPECT_EQ(h.data(), Float16{f}.data()); EXPECT_EQ(h.data(), Float16{d}.data()); } TEST(NativeFloat16Test, Float16Zero) { EXPECT_EQ(Float16{float{0.0}}.data(), 0x0000); EXPECT_EQ(Float16{float{-0.0}}.data(), 0x8000); EXPECT_EQ(Float16{double{0.0}}.data(), 0x0000); EXPECT_EQ(Float16{double{-0.0}}.data(), 0x8000); EXPECT_EQ(static_cast<float>(Float16::FromData(0x0000)), 0.0); EXPECT_EQ(static_cast<float>(Float16::FromData(0x8000)), -0.0); EXPECT_EQ(static_cast<double>(Float16::FromData(0x0000)), 0.0); EXPECT_EQ(static_cast<double>(Float16::FromData(0x8000)), -0.0); // Checks if the value is casted to 0.0 or -0.0 EXPECT_EQ(1 / static_cast<float>(Float16::FromData(0x0000)), std::numeric_limits<float>::infinity()); EXPECT_EQ(1 / static_cast<float>(Float16::FromData(0x8000)), -std::numeric_limits<float>::infinity()); EXPECT_EQ(1 / static_cast<double>(Float16::FromData(0x0000)), std::numeric_limits<float>::infinity()); EXPECT_EQ(1 / static_cast<double>(Float16::FromData(0x8000)), -std::numeric_limits<float>::infinity()); } TEST(NativeFloat16Test, Float16Normalized) { for (double x = 1e-3; x < 1e3; x *= 1.01) { // NOLINT(clang-analyzer-security.FloatLoopCounter,cert-flp30-c) EXPECT_NE(Float16{x}.data() & 0x7c00, 0); CheckToFloat16FromFloat16Near(x, 1e-3); CheckToFloat16FromFloat16Near(-x, 1e-3); } for (uint16_t bit = 0x0400; bit < 0x7c00; ++bit) { CheckFromFloat16ToFloat16Eq(Float16::FromData(bit | 0x0000)); CheckFromFloat16ToFloat16Eq(Float16::FromData(bit | 0x8000)); } } TEST(NativeFloat16Test, Float16Denormalized) { for (double x = 1e-7; x < 1e-5; x += 1e-7) { // NOLINT(clang-analyzer-security.FloatLoopCounter,cert-flp30-c) // Check if the underflow gap around zero is filled with denormal number. EXPECT_EQ(Float16{x}.data() & 0x7c00, 0x0000); EXPECT_NE(Float16{x}.data() & 0x03ff, 0x0000); CheckToFloat16FromFloat16Near(x, 1e-7); CheckToFloat16FromFloat16Near(-x, 1e-7); } for (uint16_t bit = 0x0000; bit < 0x0400; ++bit) { CheckFromFloat16ToFloat16Eq(Float16::FromData(bit | 0x0000)); CheckFromFloat16ToFloat16Eq(Float16::FromData(bit | 0x8000)); } } TEST(NativeFloat16Test, Float16Inf) { EXPECT_EQ(Float16{std::numeric_limits<float>::infinity()}.data(), 0x7c00); EXPECT_EQ(Float16{-std::numeric_limits<float>::infinity()}.data(), 0xfc00); EXPECT_EQ(Float16{std::numeric_limits<double>::infinity()}.data(), 0x7c00); EXPECT_EQ(Float16{-std::numeric_limits<double>::infinity()}.data(), 0xfc00); EXPECT_EQ(std::numeric_limits<float>::infinity(), static_cast<float>(Float16::FromData(0x7c00))); EXPECT_EQ(-std::numeric_limits<float>::infinity(), static_cast<float>(Float16::FromData(0xfc00))); EXPECT_EQ(std::numeric_limits<double>::infinity(), static_cast<double>(Float16::FromData(0x7c00))); EXPECT_EQ(-std::numeric_limits<double>::infinity(), static_cast<double>(Float16::FromData(0xfc00))); } TEST(NativeFloat16Test, Float16Nan) { for (uint16_t bit = 0x7c01; bit < 0x8000; ++bit) { EXPECT_TRUE(std::isnan(static_cast<float>(Float16::FromData(bit | 0x0000)))); EXPECT_TRUE(std::isnan(static_cast<float>(Float16::FromData(bit | 0x8000)))); EXPECT_TRUE(std::isnan(static_cast<double>(Float16::FromData(bit | 0x0000)))); EXPECT_TRUE(std::isnan(static_cast<double>(Float16::FromData(bit | 0x8000)))); } EXPECT_TRUE(IsNan(Float16{float{NAN}})); EXPECT_TRUE(IsNan(Float16{double{NAN}})); } // Get the partial set of all Float16 values for reduction of test execution time. // The returned list includes the all values whose trailing 8 digits are `0b00000000` or `0b01010101`. // This list includes all special values (e.g. signed zero, infinity) and some of normalized/denormalize numbers and NaN. std::vector<Float16> GetFloat16Values() { std::vector<Float16> values; values.reserve(1 << 9); // Use uint32_t instead of uint16_t to avoid overflow for (uint32_t bit = 0x0000; bit <= 0xffff; bit += 0x0100) { values.emplace_back(Float16::FromData(bit | 0x0000)); values.emplace_back(Float16::FromData(bit | 0x0055)); } return values; } // Checks if `l` is equal to `r` or both of them are NaN. void ExpectEqFloat16(Float16 l, Float16 r) { if (IsNan(l) && IsNan(r)) { return; } EXPECT_EQ(l.data(), r.data()); } TEST(NativeFloat16Test, Float16Neg) { // Use uint32_t instead of uint16_t to avoid overflow for (uint32_t bit = 0x0000; bit <= 0xffff; ++bit) { Float16 x = Float16::FromData(bit); Float16 expected{-static_cast<double>(x)}; ExpectEqFloat16(expected, -x); } } TEST(NativeFloat16Test, Float16Add) { for (Float16 x : GetFloat16Values()) { for (Float16 y : GetFloat16Values()) { Float16 expected{static_cast<double>(x) + static_cast<double>(y)}; ExpectEqFloat16(expected, x + y); ExpectEqFloat16(expected, y + x); } } } TEST(NativeFloat16Test, Float16Subtract) { for (Float16 x : GetFloat16Values()) { for (Float16 y : GetFloat16Values()) { Float16 expected{static_cast<double>(x) - static_cast<double>(y)}; ExpectEqFloat16(expected, x - y); } } } TEST(NativeFloat16Test, Float16Multiply) { for (Float16 x : GetFloat16Values()) { for (Float16 y : GetFloat16Values()) { Float16 expected{static_cast<double>(x) * static_cast<double>(y)}; ExpectEqFloat16(expected, x * y); ExpectEqFloat16(expected, y * x); EXPECT_EQ(expected.data(), (x * y).data()); } } } TEST(NativeFloat16Test, Float16Divide) { for (Float16 x : GetFloat16Values()) { for (Float16 y : GetFloat16Values()) { Float16 expected{static_cast<double>(x) / static_cast<double>(y)}; ExpectEqFloat16(expected, x / y); } } } TEST(NativeFloat16Test, Float16AddI) { for (Float16 x : GetFloat16Values()) { for (Float16 y : GetFloat16Values()) { Float16 expected{static_cast<double>(y) + static_cast<double>(x)}; Float16 z = (y += x); ExpectEqFloat16(expected, y); ExpectEqFloat16(expected, z); } } } TEST(NativeFloat16Test, Float16SubtractI) { for (Float16 x : GetFloat16Values()) { for (Float16 y : GetFloat16Values()) { Float16 expected{static_cast<double>(y) - static_cast<double>(x)}; Float16 z = y -= x; ExpectEqFloat16(expected, y); ExpectEqFloat16(expected, z); } } } TEST(NativeFloat16Test, Float16MultiplyI) { for (Float16 x : GetFloat16Values()) { for (Float16 y : GetFloat16Values()) { Float16 expected{static_cast<double>(y) * static_cast<double>(x)}; Float16 z = y *= x; ExpectEqFloat16(expected, y); ExpectEqFloat16(expected, z); } } } TEST(NativeFloat16Test, Float16DivideI) { for (Float16 x : GetFloat16Values()) { for (Float16 y : GetFloat16Values()) { Float16 expected{static_cast<double>(y) / static_cast<double>(x)}; Float16 z = y /= x; ExpectEqFloat16(expected, y); ExpectEqFloat16(expected, z); } } } } // namespace } // namespace chainerx <commit_msg>Add float16 comparision test<commit_after>#include "chainerx/float16.h" #include <algorithm> #include <cmath> #include <limits> #include <vector> #include <gtest/gtest.h> namespace chainerx { namespace { bool IsNan(Float16 x) { uint16_t exp = x.data() & 0x7c00; uint16_t frac = x.data() & 0x03ff; return exp == 0x7c00 && frac != 0x0000; } // Checks if `d` is equal to FromFloat16(ToFloat16(d)) with tolerance `tol`. // This function cannot take NaN as a parameter. The cast of NaN is tested in `Float16Nan`. void CheckToFloat16FromFloat16Near(double d, double tol) { Float16 h{d}; Float16 f{static_cast<float>(d)}; EXPECT_EQ(h.data(), f.data()); float f_result = static_cast<float>(h); double d_result = static_cast<double>(h); ASSERT_FALSE(std::isnan(d)); EXPECT_FALSE(std::isnan(f_result)); EXPECT_FALSE(std::isnan(d_result)); EXPECT_FALSE(IsNan(h)); if (std::isinf(d)) { // Signed inf EXPECT_EQ(d, f_result); EXPECT_EQ(d, d_result); } else { // Absolute error or relative error should be less or equal to tol. tol = std::max(tol, tol * std::abs(d)); EXPECT_NEAR(d, f_result, tol); EXPECT_NEAR(d, d_result, tol); } } // Checks if `h` is equal to ToFloat16(FromFloat16(h)) exactly. // This function cannot take NaN as a parameter. The cast of NaN is tested in `Float16Nan`. void CheckFromFloat16ToFloat16Eq(Float16 h) { float f = static_cast<float>(h); double d = static_cast<double>(h); EXPECT_EQ(d, static_cast<double>(f)); ASSERT_FALSE(IsNan(h)); EXPECT_FALSE(std::isnan(f)); EXPECT_FALSE(std::isnan(d)); EXPECT_EQ(h.data(), Float16{f}.data()); EXPECT_EQ(h.data(), Float16{d}.data()); } TEST(NativeFloat16Test, Float16Zero) { EXPECT_EQ(Float16{float{0.0}}.data(), 0x0000); EXPECT_EQ(Float16{float{-0.0}}.data(), 0x8000); EXPECT_EQ(Float16{double{0.0}}.data(), 0x0000); EXPECT_EQ(Float16{double{-0.0}}.data(), 0x8000); EXPECT_EQ(static_cast<float>(Float16::FromData(0x0000)), 0.0); EXPECT_EQ(static_cast<float>(Float16::FromData(0x8000)), -0.0); EXPECT_EQ(static_cast<double>(Float16::FromData(0x0000)), 0.0); EXPECT_EQ(static_cast<double>(Float16::FromData(0x8000)), -0.0); // Checks if the value is casted to 0.0 or -0.0 EXPECT_EQ(1 / static_cast<float>(Float16::FromData(0x0000)), std::numeric_limits<float>::infinity()); EXPECT_EQ(1 / static_cast<float>(Float16::FromData(0x8000)), -std::numeric_limits<float>::infinity()); EXPECT_EQ(1 / static_cast<double>(Float16::FromData(0x0000)), std::numeric_limits<float>::infinity()); EXPECT_EQ(1 / static_cast<double>(Float16::FromData(0x8000)), -std::numeric_limits<float>::infinity()); } TEST(NativeFloat16Test, Float16Normalized) { for (double x = 1e-3; x < 1e3; x *= 1.01) { // NOLINT(clang-analyzer-security.FloatLoopCounter,cert-flp30-c) EXPECT_NE(Float16{x}.data() & 0x7c00, 0); CheckToFloat16FromFloat16Near(x, 1e-3); CheckToFloat16FromFloat16Near(-x, 1e-3); } for (uint16_t bit = 0x0400; bit < 0x7c00; ++bit) { CheckFromFloat16ToFloat16Eq(Float16::FromData(bit | 0x0000)); CheckFromFloat16ToFloat16Eq(Float16::FromData(bit | 0x8000)); } } TEST(NativeFloat16Test, Float16Denormalized) { for (double x = 1e-7; x < 1e-5; x += 1e-7) { // NOLINT(clang-analyzer-security.FloatLoopCounter,cert-flp30-c) // Check if the underflow gap around zero is filled with denormal number. EXPECT_EQ(Float16{x}.data() & 0x7c00, 0x0000); EXPECT_NE(Float16{x}.data() & 0x03ff, 0x0000); CheckToFloat16FromFloat16Near(x, 1e-7); CheckToFloat16FromFloat16Near(-x, 1e-7); } for (uint16_t bit = 0x0000; bit < 0x0400; ++bit) { CheckFromFloat16ToFloat16Eq(Float16::FromData(bit | 0x0000)); CheckFromFloat16ToFloat16Eq(Float16::FromData(bit | 0x8000)); } } TEST(NativeFloat16Test, Float16Inf) { EXPECT_EQ(Float16{std::numeric_limits<float>::infinity()}.data(), 0x7c00); EXPECT_EQ(Float16{-std::numeric_limits<float>::infinity()}.data(), 0xfc00); EXPECT_EQ(Float16{std::numeric_limits<double>::infinity()}.data(), 0x7c00); EXPECT_EQ(Float16{-std::numeric_limits<double>::infinity()}.data(), 0xfc00); EXPECT_EQ(std::numeric_limits<float>::infinity(), static_cast<float>(Float16::FromData(0x7c00))); EXPECT_EQ(-std::numeric_limits<float>::infinity(), static_cast<float>(Float16::FromData(0xfc00))); EXPECT_EQ(std::numeric_limits<double>::infinity(), static_cast<double>(Float16::FromData(0x7c00))); EXPECT_EQ(-std::numeric_limits<double>::infinity(), static_cast<double>(Float16::FromData(0xfc00))); } TEST(NativeFloat16Test, Float16Nan) { for (uint16_t bit = 0x7c01; bit < 0x8000; ++bit) { EXPECT_TRUE(std::isnan(static_cast<float>(Float16::FromData(bit | 0x0000)))); EXPECT_TRUE(std::isnan(static_cast<float>(Float16::FromData(bit | 0x8000)))); EXPECT_TRUE(std::isnan(static_cast<double>(Float16::FromData(bit | 0x0000)))); EXPECT_TRUE(std::isnan(static_cast<double>(Float16::FromData(bit | 0x8000)))); } EXPECT_TRUE(IsNan(Float16{float{NAN}})); EXPECT_TRUE(IsNan(Float16{double{NAN}})); } // Get the partial set of all Float16 values for reduction of test execution time. // The returned list includes the all values whose trailing 8 digits are `0b00000000` or `0b01010101`. // This list includes all special values (e.g. signed zero, infinity) and some of normalized/denormalize numbers and NaN. std::vector<Float16> GetFloat16Values() { std::vector<Float16> values; values.reserve(1 << 9); // Use uint32_t instead of uint16_t to avoid overflow for (uint32_t bit = 0x0000; bit <= 0xffff; bit += 0x0100) { values.emplace_back(Float16::FromData(bit | 0x0000)); values.emplace_back(Float16::FromData(bit | 0x0055)); } return values; } // Checks if `l` is equal to `r` or both of them are NaN. void ExpectEqFloat16(Float16 l, Float16 r) { if (IsNan(l) && IsNan(r)) { return; } EXPECT_EQ(l.data(), r.data()); } TEST(NativeFloat16Test, Float16Neg) { // Use uint32_t instead of uint16_t to avoid overflow for (uint32_t bit = 0x0000; bit <= 0xffff; ++bit) { Float16 x = Float16::FromData(bit); Float16 expected{-static_cast<double>(x)}; ExpectEqFloat16(expected, -x); } } TEST(NativeFloat16Test, Float16Add) { for (Float16 x : GetFloat16Values()) { for (Float16 y : GetFloat16Values()) { Float16 expected{static_cast<double>(x) + static_cast<double>(y)}; ExpectEqFloat16(expected, x + y); ExpectEqFloat16(expected, y + x); } } } TEST(NativeFloat16Test, Float16Subtract) { for (Float16 x : GetFloat16Values()) { for (Float16 y : GetFloat16Values()) { Float16 expected{static_cast<double>(x) - static_cast<double>(y)}; ExpectEqFloat16(expected, x - y); } } } TEST(NativeFloat16Test, Float16Multiply) { for (Float16 x : GetFloat16Values()) { for (Float16 y : GetFloat16Values()) { Float16 expected{static_cast<double>(x) * static_cast<double>(y)}; ExpectEqFloat16(expected, x * y); ExpectEqFloat16(expected, y * x); EXPECT_EQ(expected.data(), (x * y).data()); } } } TEST(NativeFloat16Test, Float16Divide) { for (Float16 x : GetFloat16Values()) { for (Float16 y : GetFloat16Values()) { Float16 expected{static_cast<double>(x) / static_cast<double>(y)}; ExpectEqFloat16(expected, x / y); } } } TEST(NativeFloat16Test, Float16AddI) { for (Float16 x : GetFloat16Values()) { for (Float16 y : GetFloat16Values()) { Float16 expected{static_cast<double>(y) + static_cast<double>(x)}; Float16 z = (y += x); ExpectEqFloat16(expected, y); ExpectEqFloat16(expected, z); } } } TEST(NativeFloat16Test, Float16SubtractI) { for (Float16 x : GetFloat16Values()) { for (Float16 y : GetFloat16Values()) { Float16 expected{static_cast<double>(y) - static_cast<double>(x)}; Float16 z = y -= x; ExpectEqFloat16(expected, y); ExpectEqFloat16(expected, z); } } } TEST(NativeFloat16Test, Float16MultiplyI) { for (Float16 x : GetFloat16Values()) { for (Float16 y : GetFloat16Values()) { Float16 expected{static_cast<double>(y) * static_cast<double>(x)}; Float16 z = y *= x; ExpectEqFloat16(expected, y); ExpectEqFloat16(expected, z); } } } TEST(NativeFloat16Test, Float16DivideI) { for (Float16 x : GetFloat16Values()) { for (Float16 y : GetFloat16Values()) { Float16 expected{static_cast<double>(y) / static_cast<double>(x)}; Float16 z = y /= x; ExpectEqFloat16(expected, y); ExpectEqFloat16(expected, z); } } } TEST(NativeFloat16Test, FloatComparison) { for (Float16 x : GetFloat16Values()) { for (Float16 y : GetFloat16Values()) { #define run_compare_check(op) \ do { \ EXPECT_EQ(static_cast<double>(x) op static_cast<double>(y), x op y); \ EXPECT_EQ(static_cast<double>(y) op static_cast<double>(x), y op x); \ } while (false) run_compare_check(==); run_compare_check(!=); run_compare_check(<); run_compare_check(>); run_compare_check(<=); run_compare_check(>=); #undef run_compare_check } } } } // namespace } // namespace chainerx <|endoftext|>
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/micro/micro_profiler.h" #include <cinttypes> #include <cstdint> #include <cstring> #include "tensorflow/lite/kernels/internal/compatibility.h" #include "tensorflow/lite/micro/micro_log.h" #include "tensorflow/lite/micro/micro_time.h" namespace tflite { uint32_t MicroProfiler::BeginEvent(const char* tag) { if (num_events_ == kMaxEvents) { num_events_ = 0; } tags_[num_events_] = tag; start_ticks_[num_events_] = GetCurrentTimeTicks(); end_ticks_[num_events_] = start_ticks_[num_events_] - 1; return num_events_++; } void MicroProfiler::EndEvent(uint32_t event_handle) { TFLITE_DCHECK(event_handle < kMaxEvents); end_ticks_[event_handle] = GetCurrentTimeTicks(); } uint32_t MicroProfiler::GetTotalTicks() const { int32_t ticks = 0; for (int i = 0; i < num_events_; ++i) { ticks += end_ticks_[i] - start_ticks_[i]; } return ticks; } void MicroProfiler::Log() const { #if !defined(TF_LITE_STRIP_ERROR_STRINGS) for (int i = 0; i < num_events_; ++i) { uint32_t ticks = end_ticks_[i] - start_ticks_[i]; MicroPrintf("%s took %" PRIu32 " ticks (%d ms).", tags_[i], ticks, TicksToMs(ticks)); } #endif } void MicroProfiler::LogCsv() const { #if !defined(TF_LITE_STRIP_ERROR_STRINGS) MicroPrintf("\"Event\",\"Tag\",\"Ticks\""); for (int i = 0; i < num_events_; ++i) { uint32_t ticks = end_ticks_[i] - start_ticks_[i]; MicroPrintf("%d,%s,%" PRIu32, i, tags_[i], ticks); } #endif } void MicroProfiler::LogTicksPerTagCsv() { #if !defined(TF_LITE_STRIP_ERROR_STRINGS) MicroPrintf( "\"Unique Tag\",\"Total ticks across all events with that tag.\""); int total_ticks = 0; for (int i = 0; i < num_events_; ++i) { uint32_t ticks = end_ticks_[i] - start_ticks_[i]; TFLITE_DCHECK(tags_[i] != nullptr); int position = FindExistingOrNextPosition(tags_[i]); TFLITE_DCHECK(position >= 0); total_ticks_per_tag[position].tag = tags_[i]; total_ticks_per_tag[position].ticks = total_ticks_per_tag[position].ticks + ticks; total_ticks += ticks; } for (int i = 0; i < num_events_; ++i) { TicksPerTag each_tag_entry = total_ticks_per_tag[i]; if (each_tag_entry.tag == nullptr) { break; } MicroPrintf("%s, %d", each_tag_entry.tag, each_tag_entry.ticks); } MicroPrintf("total number of ticks, %d", total_ticks); #endif } // This method finds a particular array element in the total_ticks_per_tag array // with the matching tag_name passed in the method. If it can find a // matching array element that has the same tag_name, then it will return the // position of the matching element. But if it unable to find a matching element // with the given tag_name, it will return the next available empty position // from the array. int MicroProfiler::FindExistingOrNextPosition(const char* tag_name) { int pos = 0; for (; pos < num_events_; pos++) { TicksPerTag each_tag_entry = total_ticks_per_tag[pos]; if (each_tag_entry.tag == nullptr || strcmp(each_tag_entry.tag, tag_name) == 0) { return pos; } } return pos < num_events_ ? pos : -1; } } // namespace tflite <commit_msg>Patch tflite profiler until it's fixed upstream (#715).<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/micro/micro_profiler.h" #include <cinttypes> #include <cstdint> #include <cstring> #include "tensorflow/lite/kernels/internal/compatibility.h" #include "tensorflow/lite/micro/micro_log.h" #include "tensorflow/lite/micro/micro_time.h" namespace tflite { uint32_t MicroProfiler::BeginEvent(const char* tag) { if (num_events_ == kMaxEvents) { num_events_ = 0; } tags_[num_events_] = tag; start_ticks_[num_events_] = GetCurrentTimeTicks(); end_ticks_[num_events_] = start_ticks_[num_events_] - 1; return num_events_++; } void MicroProfiler::EndEvent(uint32_t event_handle) { TFLITE_DCHECK(event_handle < kMaxEvents); end_ticks_[event_handle] = GetCurrentTimeTicks(); } uint32_t MicroProfiler::GetTotalTicks() const { int32_t ticks = 0; for (int i = 0; i < num_events_; ++i) { ticks += end_ticks_[i] - start_ticks_[i]; } return ticks; } void MicroProfiler::Log() const { #if !defined(TF_LITE_STRIP_ERROR_STRINGS) for (int i = 0; i < num_events_; ++i) { uint32_t ticks = end_ticks_[i] - start_ticks_[i]; MicroPrintf("%s took %u ticks (%d ms).", tags_[i], ticks, TicksToMs(ticks)); } #endif } void MicroProfiler::LogCsv() const { #if !defined(TF_LITE_STRIP_ERROR_STRINGS) MicroPrintf("\"Event\",\"Tag\",\"Ticks\""); for (int i = 0; i < num_events_; ++i) { uint32_t ticks = end_ticks_[i] - start_ticks_[i]; MicroPrintf("%d,%s,%u", i, tags_[i], ticks); } #endif } void MicroProfiler::LogTicksPerTagCsv() { #if !defined(TF_LITE_STRIP_ERROR_STRINGS) MicroPrintf( "\"Unique Tag\",\"Total ticks across all events with that tag.\""); int total_ticks = 0; for (int i = 0; i < num_events_; ++i) { uint32_t ticks = end_ticks_[i] - start_ticks_[i]; TFLITE_DCHECK(tags_[i] != nullptr); int position = FindExistingOrNextPosition(tags_[i]); TFLITE_DCHECK(position >= 0); total_ticks_per_tag[position].tag = tags_[i]; total_ticks_per_tag[position].ticks = total_ticks_per_tag[position].ticks + ticks; total_ticks += ticks; } for (int i = 0; i < num_events_; ++i) { TicksPerTag each_tag_entry = total_ticks_per_tag[i]; if (each_tag_entry.tag == nullptr) { break; } MicroPrintf("%s, %d", each_tag_entry.tag, each_tag_entry.ticks); } MicroPrintf("total number of ticks, %d", total_ticks); #endif } // This method finds a particular array element in the total_ticks_per_tag array // with the matching tag_name passed in the method. If it can find a // matching array element that has the same tag_name, then it will return the // position of the matching element. But if it unable to find a matching element // with the given tag_name, it will return the next available empty position // from the array. int MicroProfiler::FindExistingOrNextPosition(const char* tag_name) { int pos = 0; for (; pos < num_events_; pos++) { TicksPerTag each_tag_entry = total_ticks_per_tag[pos]; if (each_tag_entry.tag == nullptr || strcmp(each_tag_entry.tag, tag_name) == 0) { return pos; } } return pos < num_events_ ? pos : -1; } } // namespace tflite <|endoftext|>
<commit_before>#include <iostream> #include <thread> #include <Common/ScopedFunction.h> template <typename Value_t, typename Initializer_t=std::function<Value_t (void)>> class LazyInitialized { public: LazyInitialized(Initializer_t i) : m_i(i), m_v() {} LazyInitialized(LazyInitialized<Value_t, Initializer_t>&& that) : m_i(std::move(that.m_i)), m_v(std::move(that.m_v)) {} LazyInitialized<Value_t, Initializer_t>& operator = (LazyInitialized<Value_t, Initializer_t>&& that) { m_i = std::move(that.m_i); m_v = std::move(that.m_v); m_initFlag = std::move(that.m_initFlag); } operator Value_t() { std::call_once(m_initFlag, [this]{ m_v = m_i();}); return m_v; } private: Initializer_t m_i; Value_t m_v; std::once_flag m_initFlag; }; template<typename Value_t, typename Initializer_t> LazyInitialized<Value_t,Initializer_t> make_lazy_initialized(Initializer_t i) { return LazyInitialized<Value_t,Initializer_t>(i); } struct ClassWithLazyMembers { LazyInitialized<double> m_baseLazyValue; LazyInitialized<double> m_lazyValue; ClassWithLazyMembers() : m_baseLazyValue{[]()->double{auto f = make_scoped_function([]{std::cout << "Built base member variable" << std::endl;}); return 3.0;}}, m_lazyValue{[this]()->double{auto f = make_scoped_function([]{std::cout << "Built derived member variable" << std::endl;}); return 2.0 * m_baseLazyValue;}} {} }; int main(int argc, char* argv[]) { auto x = make_lazy_initialized<double>([]()->double{std::cout << "Built variable" << std::endl; return 2.0;}); std::cout << x << std::endl; std::cout << x << std::endl; std::cout << std::endl; ClassWithLazyMembers c; std::cout << c.m_lazyValue << std::endl; std::cout << c.m_lazyValue << std::endl; } <commit_msg>Use boost::optional<commit_after>#include <iostream> #include <thread> #include <Common/ScopedFunction.h> #include <boost/optional.hpp> template <typename Value_t, typename Initializer_t=std::function<Value_t (void)>> class LazyInitialized { public: LazyInitialized(Initializer_t i) : m_i(i), m_v() {} LazyInitialized(LazyInitialized<Value_t, Initializer_t>&& that) : m_i(std::move(that.m_i)), m_v(std::move(that.m_v)) {} LazyInitialized<Value_t, Initializer_t>& operator = (LazyInitialized<Value_t, Initializer_t>&& that) { m_i = std::move(that.m_i); m_v = std::move(that.m_v); } operator Value_t&() { if ( ! m_v ) m_v = m_i(); return *m_v; } private: Initializer_t m_i; boost::optional<Value_t> m_v; }; template<typename Value_t, typename Initializer_t> LazyInitialized<Value_t,Initializer_t> make_lazy_initialized(Initializer_t i) { return LazyInitialized<Value_t,Initializer_t>(i); } struct ClassWithLazyMembers { LazyInitialized<double> m_baseLazyValue; LazyInitialized<double> m_lazyValue; ClassWithLazyMembers() : m_baseLazyValue{[]()->double{auto f = make_scoped_function([]{std::cout << "Built base member variable" << std::endl;}); return 3.0;}}, m_lazyValue{[this]()->double{auto f = make_scoped_function([]{std::cout << "Built derived member variable" << std::endl;}); return 2.0 * m_baseLazyValue;}} {} }; int main(int argc, char* argv[]) { auto x = make_lazy_initialized<double>([]()->double{std::cout << "Built variable" << std::endl; return 2.0;}); std::cout << x << std::endl; std::cout << x << std::endl; std::cout << std::endl; ClassWithLazyMembers c; std::cout << c.m_lazyValue << std::endl; std::cout << c.m_lazyValue << std::endl; } <|endoftext|>
<commit_before>// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved // Please see LICENSE.md in repository root for license information // https://github.com/AtomicGameEngine/AtomicGameEngine #include <Atomic/Atomic.h> #include <Atomic/IO/Log.h> #include <Atomic/Resource/JSONFile.h> #include <Atomic/Resource/ResourceCache.h> #include <Atomic/Core/ProcessUtils.h> #include "JSBind.h" #include "JSBindings.h" #include "JSBHeader.h" #include "JSBModule.h" #include "JSBFunction.h" void JSBModule::ParseHeaders() { for (unsigned i = 0; i < headerFiles_.Size(); i++) { JSBHeader* header = new JSBHeader(this, headerFiles_.At(i)); headers_.Push(header); header->Parse(); } } void JSBModule::PreprocessHeaders() { for (unsigned i = 0; i < headers_.Size(); i++) { headers_[i]->VisitPreprocess(); } } void JSBModule::VisitHeaders() { for (unsigned i = 0; i < headers_.Size(); i++) { headers_[i]->VisitHeader(); } } void JSBModule::WriteClassDeclaration(String& source) { source += "static void jsb_declare_classes(JSVM* vm)\n{\n"; source += "duk_context* ctx = vm->GetJSContext();\n"; for (unsigned i = 0; i < classes_.Size(); i++) { JSBClass* klass = classes_.At(i); if (klass->isNumberArray()) continue; source.AppendWithFormat(" js_class_declare(vm, \"%s\", jsb_constructor_%s);\n", klass->GetName().CString(), klass->GetName().CString()); if (klass->hasProperties()) { source.AppendWithFormat("js_class_push_propertyobject(vm, \"%s\");\n", klass->GetName().CString()); Vector<String> pnames; klass->GetPropertyNames(pnames); for (unsigned j = 0; j < pnames.Size(); j++) { JSBProperty* prop = klass->GetProperty(pnames[j]); source.Append("duk_push_object(ctx);\n"); if (prop->getter_ && !prop->getter_->Skip()) { source.AppendWithFormat("duk_push_c_function(ctx, jsb_class_%s_%s, 0);\n", klass->GetName().CString(), prop->getter_->name_.CString()); source.Append("duk_put_prop_string(ctx, -2, \"get\");\n"); } if (prop->setter_ && !prop->setter_->Skip()) { source.AppendWithFormat("duk_push_c_function(ctx, jsb_class_%s_%s, 1);\n", klass->GetName().CString(), prop->setter_->name_.CString()); source.Append("duk_put_prop_string(ctx, -2, \"set\");\n"); } pnames[j][0] = tolower(pnames[j][0]); source.AppendWithFormat("duk_put_prop_string(ctx, -2, \"%s\");\n", pnames[j].CString()); } source.Append("duk_pop(ctx);\n"); } } source += "\n}\n\n"; } void JSBModule::WriteClassDefine(String& source) { source += "static void jsb_init_classes(JSVM* vm)\n{\n"; for (unsigned i = 0; i < classes_.Size(); i++) { JSBClass* klass = classes_.At(i); if (klass->isNumberArray()) continue; source.AppendWithFormat(" jsb_class_define_%s(vm);\n", klass->GetName().CString()); } source += "\n}\n\n"; } void JSBModule::WriteModulePreInit(String& source) { source.AppendWithFormat("\nvoid jsb_preinit_%s (JSVM* vm)\n{\n\njsb_declare_classes(vm);\n", name_.ToLower().CString()); // register enums and constants source += "// enums and constants\n"; source += "duk_context* ctx = vm->GetJSContext();\n"; source += "duk_get_global_string(ctx, \"Atomic\");\n"; source += "// enums\n"; for (unsigned i = 0; i < enums_.Size(); i++) { JSBEnum* jenum = enums_[i]; for (unsigned k = 0; k < jenum->values_.Size(); k++) { source.AppendWithFormat("duk_push_number(ctx, (double) %s);\n", jenum->values_.At(k).CString()); source.AppendWithFormat("duk_put_prop_string(ctx, -2, \"%s\");\n", jenum->values_.At(k).CString()); } } source += "// constants\n"; for (unsigned i = 0; i < constants_.Size(); i++) { source.AppendWithFormat("duk_push_number(ctx, (double) %s);\n", constants_.At(i).CString()); source.AppendWithFormat("duk_put_prop_string(ctx, -2, \"%s\");\n", constants_.At(i).CString()); } source += "duk_pop(ctx);\n"; source += "// end enums and constants\n"; source += "\n}\n"; } void JSBModule::WriteModuleInit(String& source) { source.AppendWithFormat("\nvoid jsb_init_%s (JSVM* vm)\n{\n\n jsb_init_classes(vm);\n\n}\n\n", name_.ToLower().CString()); } void JSBModule::WriteIncludes(String& source) { Vector<JSBHeader*> allheaders; for (unsigned i = 0; i < enums_.Size(); i++) { allheaders.Push(enums_.At(i)->header_); } for (unsigned i = 0; i < classes_.Size(); i++) { allheaders.Push(classes_.At(i)->GetHeader()); } Vector<JSBHeader*> included; for (unsigned i = 0; i < allheaders.Size(); i++) { JSBHeader* header = allheaders.At(i); if (included.Contains(header)) continue; String headerPath = GetPath(header->filepath_); String headerfile = GetFileNameAndExtension(header->filepath_); headerPath.Replace(JSBind::ROOT_FOLDER + "/Source/Atomic/", "Atomic/"); source.AppendWithFormat("#include <%s%s>\n", headerPath.CString(), headerfile.CString()); included.Push(header); } for (unsigned i = 0; i < includes_.Size(); i++) { if (includes_[i].StartsWith("<")) source.AppendWithFormat("#include %s\n", includes_[i].CString()); else source.AppendWithFormat("#include \"%s\"\n", includes_[i].CString()); } } void JSBModule::EmitSource(const String& filepath) { File file(JSBind::context_); file.Open(filepath, FILE_WRITE); source_ = "// This file was autogenerated by JSBind, changes will be lost\n"; source_ += "#ifdef ATOMIC_PLATFORM_WINDOWS\n"; source_ += "#pragma warning(disable: 4244) // possible loss of data\n"; source_ += "#endif\n"; if (Requires("3D")) { source_ += "#ifdef ATOMIC_3D\n"; } source_ += "#include <Duktape/duktape.h>\n"; source_ += "#include <AtomicJS/Javascript/JSVM.h>\n"; source_ += "#include <AtomicJS/Javascript/JSAPI.h>\n"; WriteIncludes(source_); source_ += "\n\nnamespace Atomic\n{\n \n"; source_ += "// Begin Class Declarations\n"; for (unsigned i = 0; i < classes_.Size(); i++) { classes_[i]->WriteForwardDeclarations(source_); } source_ += "// End Class Declarations\n\n"; source_ += "// Begin Classes\n"; for (unsigned i = 0; i < classes_.Size(); i++) { classes_[i]->Write(source_); } source_ += "// End Classes\n\n"; WriteClassDeclaration(source_); WriteClassDefine(source_); WriteModulePreInit(source_); WriteModuleInit(source_); // end Atomic namespace source_ += "\n}\n"; if (Requires("3D")) { source_ += "#endif //ATOMIC_3D\n"; } file.Write(source_.CString(), source_.Length()); file.Close(); } void JSBModule::Load(const String &moduleJSONFilename) { ResourceCache* cache = JSBind::context_->GetSubsystem<ResourceCache>(); JSONFile* moduleJSONFile = cache->GetResource<JSONFile>(moduleJSONFilename); if (!moduleJSONFile) { LOGERRORF("Couldn't load module json: %s", moduleJSONFilename.CString()); ErrorExit("Couldn't load module json"); } JSONValue moduleJSON = moduleJSONFile->GetRoot(); JSONValue sources = moduleJSON.GetChild("sources"); JSONValue classes = moduleJSON.GetChild("classes"); JSONValue includes = moduleJSON.GetChild("includes"); JSONValue classes_rename = moduleJSON.GetChild("classes_rename"); JSONValue overloads = moduleJSON.GetChild("overloads"); JSONValue requires = moduleJSON.GetChild("requires"); HashMap<String, String> rename; if (requires.IsArray()) { for (unsigned j = 0; j < requires.GetSize(); j++) { requirements_.Push(requires.GetString(j)); } } if (classes_rename.IsObject()) { Vector<String> childNames = classes_rename.GetValueNames(); for (unsigned j = 0; j < childNames.Size(); j++) { String classname = childNames.At(j); String crename = classes_rename.GetString(classname); rename[classname] = crename; } } if (includes.IsArray()) { for (unsigned j = 0; j < includes.GetSize(); j++) { includes_.Push(includes.GetString(j)); } } if (classes.IsArray()) { for (unsigned j = 0; j < classes.GetSize(); j++) { String classname = classes.GetString(j); if (rename.Contains(classname)) bindings_->RegisterClass(classname, rename[classname]); else bindings_->RegisterClass(classname); } } if (overloads.IsObject()) { Vector<String> childNames = overloads.GetChildNames(); for (unsigned j = 0; j < childNames.Size(); j++) { String classname = childNames.At(j); JSBClass* klass = bindings_->GetClass(classname); if (!klass) { ErrorExit("Bad overload klass"); } JSONValue classoverloads = overloads.GetChild(classname); Vector<String> functionNames = classoverloads.GetChildNames(); for (unsigned k = 0; k < functionNames.Size(); k++) { JSONValue sig = classoverloads.GetChild(functionNames[k]); if (!sig.IsArray()) { ErrorExit("Bad overload defintion"); } Vector<String> values; for (unsigned x = 0; x < sig.GetSize(); x++) { values.Push(sig.GetString(x)); } JSBFunctionOverride* fo = new JSBFunctionOverride(functionNames[k], values); klass->AddFunctionOverride(fo); } } } this->name_ = moduleJSON.GetString("name"); if (this->name_ == "Graphics") { #ifdef _MSC_VER sources.AddString("Graphics/Direct3D9"); #else sources.AddString("Graphics/OpenGL"); #endif } for (unsigned j = 0; j < sources.GetSize(); j++) { String sourceFolder = sources.GetString(j); Vector<String> fileNames; String sourceRoot = "Atomic"; if (sourceFolder == "Javascript") sourceRoot = "AtomicJS"; JSBind::fileSystem_->ScanDir(fileNames, JSBind::ROOT_FOLDER + "/Source/" + sourceRoot + "/" + sourceFolder, "*.h", SCAN_FILES, false); for (unsigned k = 0; k < fileNames.Size(); k++) { // TODO: filter String filepath = JSBind::ROOT_FOLDER + "/Source/" + sourceRoot + "/" + sourceFolder + "/" + fileNames[k]; this->headerFiles_.Push(filepath); } } } <commit_msg>JSBind should use OpenGL Graphics module when building Android and Web platform on windows<commit_after>// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved // Please see LICENSE.md in repository root for license information // https://github.com/AtomicGameEngine/AtomicGameEngine #include <Atomic/Atomic.h> #include <Atomic/IO/Log.h> #include <Atomic/Resource/JSONFile.h> #include <Atomic/Resource/ResourceCache.h> #include <Atomic/Core/ProcessUtils.h> #include "JSBind.h" #include "JSBindings.h" #include "JSBHeader.h" #include "JSBModule.h" #include "JSBFunction.h" void JSBModule::ParseHeaders() { for (unsigned i = 0; i < headerFiles_.Size(); i++) { JSBHeader* header = new JSBHeader(this, headerFiles_.At(i)); headers_.Push(header); header->Parse(); } } void JSBModule::PreprocessHeaders() { for (unsigned i = 0; i < headers_.Size(); i++) { headers_[i]->VisitPreprocess(); } } void JSBModule::VisitHeaders() { for (unsigned i = 0; i < headers_.Size(); i++) { headers_[i]->VisitHeader(); } } void JSBModule::WriteClassDeclaration(String& source) { source += "static void jsb_declare_classes(JSVM* vm)\n{\n"; source += "duk_context* ctx = vm->GetJSContext();\n"; for (unsigned i = 0; i < classes_.Size(); i++) { JSBClass* klass = classes_.At(i); if (klass->isNumberArray()) continue; source.AppendWithFormat(" js_class_declare(vm, \"%s\", jsb_constructor_%s);\n", klass->GetName().CString(), klass->GetName().CString()); if (klass->hasProperties()) { source.AppendWithFormat("js_class_push_propertyobject(vm, \"%s\");\n", klass->GetName().CString()); Vector<String> pnames; klass->GetPropertyNames(pnames); for (unsigned j = 0; j < pnames.Size(); j++) { JSBProperty* prop = klass->GetProperty(pnames[j]); source.Append("duk_push_object(ctx);\n"); if (prop->getter_ && !prop->getter_->Skip()) { source.AppendWithFormat("duk_push_c_function(ctx, jsb_class_%s_%s, 0);\n", klass->GetName().CString(), prop->getter_->name_.CString()); source.Append("duk_put_prop_string(ctx, -2, \"get\");\n"); } if (prop->setter_ && !prop->setter_->Skip()) { source.AppendWithFormat("duk_push_c_function(ctx, jsb_class_%s_%s, 1);\n", klass->GetName().CString(), prop->setter_->name_.CString()); source.Append("duk_put_prop_string(ctx, -2, \"set\");\n"); } pnames[j][0] = tolower(pnames[j][0]); source.AppendWithFormat("duk_put_prop_string(ctx, -2, \"%s\");\n", pnames[j].CString()); } source.Append("duk_pop(ctx);\n"); } } source += "\n}\n\n"; } void JSBModule::WriteClassDefine(String& source) { source += "static void jsb_init_classes(JSVM* vm)\n{\n"; for (unsigned i = 0; i < classes_.Size(); i++) { JSBClass* klass = classes_.At(i); if (klass->isNumberArray()) continue; source.AppendWithFormat(" jsb_class_define_%s(vm);\n", klass->GetName().CString()); } source += "\n}\n\n"; } void JSBModule::WriteModulePreInit(String& source) { source.AppendWithFormat("\nvoid jsb_preinit_%s (JSVM* vm)\n{\n\njsb_declare_classes(vm);\n", name_.ToLower().CString()); // register enums and constants source += "// enums and constants\n"; source += "duk_context* ctx = vm->GetJSContext();\n"; source += "duk_get_global_string(ctx, \"Atomic\");\n"; source += "// enums\n"; for (unsigned i = 0; i < enums_.Size(); i++) { JSBEnum* jenum = enums_[i]; for (unsigned k = 0; k < jenum->values_.Size(); k++) { source.AppendWithFormat("duk_push_number(ctx, (double) %s);\n", jenum->values_.At(k).CString()); source.AppendWithFormat("duk_put_prop_string(ctx, -2, \"%s\");\n", jenum->values_.At(k).CString()); } } source += "// constants\n"; for (unsigned i = 0; i < constants_.Size(); i++) { source.AppendWithFormat("duk_push_number(ctx, (double) %s);\n", constants_.At(i).CString()); source.AppendWithFormat("duk_put_prop_string(ctx, -2, \"%s\");\n", constants_.At(i).CString()); } source += "duk_pop(ctx);\n"; source += "// end enums and constants\n"; source += "\n}\n"; } void JSBModule::WriteModuleInit(String& source) { source.AppendWithFormat("\nvoid jsb_init_%s (JSVM* vm)\n{\n\n jsb_init_classes(vm);\n\n}\n\n", name_.ToLower().CString()); } void JSBModule::WriteIncludes(String& source) { Vector<JSBHeader*> allheaders; for (unsigned i = 0; i < enums_.Size(); i++) { allheaders.Push(enums_.At(i)->header_); } for (unsigned i = 0; i < classes_.Size(); i++) { allheaders.Push(classes_.At(i)->GetHeader()); } Vector<JSBHeader*> included; for (unsigned i = 0; i < allheaders.Size(); i++) { JSBHeader* header = allheaders.At(i); if (included.Contains(header)) continue; String headerPath = GetPath(header->filepath_); String headerfile = GetFileNameAndExtension(header->filepath_); headerPath.Replace(JSBind::ROOT_FOLDER + "/Source/Atomic/", "Atomic/"); source.AppendWithFormat("#include <%s%s>\n", headerPath.CString(), headerfile.CString()); included.Push(header); } for (unsigned i = 0; i < includes_.Size(); i++) { if (includes_[i].StartsWith("<")) source.AppendWithFormat("#include %s\n", includes_[i].CString()); else source.AppendWithFormat("#include \"%s\"\n", includes_[i].CString()); } } void JSBModule::EmitSource(const String& filepath) { File file(JSBind::context_); file.Open(filepath, FILE_WRITE); source_ = "// This file was autogenerated by JSBind, changes will be lost\n"; source_ += "#ifdef ATOMIC_PLATFORM_WINDOWS\n"; source_ += "#pragma warning(disable: 4244) // possible loss of data\n"; source_ += "#endif\n"; if (Requires("3D")) { source_ += "#ifdef ATOMIC_3D\n"; } source_ += "#include <Duktape/duktape.h>\n"; source_ += "#include <AtomicJS/Javascript/JSVM.h>\n"; source_ += "#include <AtomicJS/Javascript/JSAPI.h>\n"; WriteIncludes(source_); source_ += "\n\nnamespace Atomic\n{\n \n"; source_ += "// Begin Class Declarations\n"; for (unsigned i = 0; i < classes_.Size(); i++) { classes_[i]->WriteForwardDeclarations(source_); } source_ += "// End Class Declarations\n\n"; source_ += "// Begin Classes\n"; for (unsigned i = 0; i < classes_.Size(); i++) { classes_[i]->Write(source_); } source_ += "// End Classes\n\n"; WriteClassDeclaration(source_); WriteClassDefine(source_); WriteModulePreInit(source_); WriteModuleInit(source_); // end Atomic namespace source_ += "\n}\n"; if (Requires("3D")) { source_ += "#endif //ATOMIC_3D\n"; } file.Write(source_.CString(), source_.Length()); file.Close(); } void JSBModule::Load(const String &moduleJSONFilename) { ResourceCache* cache = JSBind::context_->GetSubsystem<ResourceCache>(); JSONFile* moduleJSONFile = cache->GetResource<JSONFile>(moduleJSONFilename); if (!moduleJSONFile) { LOGERRORF("Couldn't load module json: %s", moduleJSONFilename.CString()); ErrorExit("Couldn't load module json"); } JSONValue moduleJSON = moduleJSONFile->GetRoot(); JSONValue sources = moduleJSON.GetChild("sources"); JSONValue classes = moduleJSON.GetChild("classes"); JSONValue includes = moduleJSON.GetChild("includes"); JSONValue classes_rename = moduleJSON.GetChild("classes_rename"); JSONValue overloads = moduleJSON.GetChild("overloads"); JSONValue requires = moduleJSON.GetChild("requires"); HashMap<String, String> rename; if (requires.IsArray()) { for (unsigned j = 0; j < requires.GetSize(); j++) { requirements_.Push(requires.GetString(j)); } } if (classes_rename.IsObject()) { Vector<String> childNames = classes_rename.GetValueNames(); for (unsigned j = 0; j < childNames.Size(); j++) { String classname = childNames.At(j); String crename = classes_rename.GetString(classname); rename[classname] = crename; } } if (includes.IsArray()) { for (unsigned j = 0; j < includes.GetSize(); j++) { includes_.Push(includes.GetString(j)); } } if (classes.IsArray()) { for (unsigned j = 0; j < classes.GetSize(); j++) { String classname = classes.GetString(j); if (rename.Contains(classname)) bindings_->RegisterClass(classname, rename[classname]); else bindings_->RegisterClass(classname); } } if (overloads.IsObject()) { Vector<String> childNames = overloads.GetChildNames(); for (unsigned j = 0; j < childNames.Size(); j++) { String classname = childNames.At(j); JSBClass* klass = bindings_->GetClass(classname); if (!klass) { ErrorExit("Bad overload klass"); } JSONValue classoverloads = overloads.GetChild(classname); Vector<String> functionNames = classoverloads.GetChildNames(); for (unsigned k = 0; k < functionNames.Size(); k++) { JSONValue sig = classoverloads.GetChild(functionNames[k]); if (!sig.IsArray()) { ErrorExit("Bad overload defintion"); } Vector<String> values; for (unsigned x = 0; x < sig.GetSize(); x++) { values.Push(sig.GetString(x)); } JSBFunctionOverride* fo = new JSBFunctionOverride(functionNames[k], values); klass->AddFunctionOverride(fo); } } } this->name_ = moduleJSON.GetString("name"); if (this->name_ == "Graphics") { #ifdef _MSC_VER if (JSBind::PLATFORM == "ANDROID" || JSBind::PLATFORM == "WEB") { sources.AddString("Graphics/OpenGL"); } else { sources.AddString("Graphics/Direct3D9"); } #else sources.AddString("Graphics/OpenGL"); #endif } for (unsigned j = 0; j < sources.GetSize(); j++) { String sourceFolder = sources.GetString(j); Vector<String> fileNames; String sourceRoot = "Atomic"; if (sourceFolder == "Javascript") sourceRoot = "AtomicJS"; JSBind::fileSystem_->ScanDir(fileNames, JSBind::ROOT_FOLDER + "/Source/" + sourceRoot + "/" + sourceFolder, "*.h", SCAN_FILES, false); for (unsigned k = 0; k < fileNames.Size(); k++) { // TODO: filter String filepath = JSBind::ROOT_FOLDER + "/Source/" + sourceRoot + "/" + sourceFolder + "/" + fileNames[k]; this->headerFiles_.Push(filepath); } } } <|endoftext|>
<commit_before>/*============================================================================= Library: CTK Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "ctkServices_p.h" #include <QStringListIterator> #include <QMutexLocker> #include <QBuffer> #include <algorithm> #include "ctkServiceFactory.h" #include "ctkPluginConstants.h" #include "ctkPluginFrameworkContext_p.h" #include "ctkServiceException.h" #include "ctkServiceRegistrationPrivate.h" #include "ctkQtServiceRegistration_p.h" #include "ctkLDAPExpr_p.h" using namespace QtMobility; struct ServiceRegistrationComparator { bool operator()(const ctkServiceRegistration* a, const ctkServiceRegistration* b) const { return *a < *b; } }; ServiceProperties ctkServices::createServiceProperties(const ServiceProperties& in, const QStringList& classes, long sid) { static qlonglong nextServiceID = 1; ServiceProperties props; if (!in.isEmpty()) { for (ServiceProperties::const_iterator it = in.begin(); it != in.end(); ++it) { const QString key = it.key(); const QString lcKey = it.key().toLower(); for (QListIterator<QString> i(props.keys()); i.hasNext(); ) { if (lcKey == i.next()) { throw std::invalid_argument(std::string("Several entries for property: ") + key.toStdString()); } } props.insert(lcKey, in.value(key)); } } if (!classes.isEmpty()) { props.insert(ctkPluginConstants::OBJECTCLASS, classes); } props.insert(ctkPluginConstants::SERVICE_ID, sid != -1 ? sid : nextServiceID++); return props; } ctkServices::ctkServices(ctkPluginFrameworkContext* fwCtx) : mutex(QMutex::Recursive), framework(fwCtx) { } ctkServices::~ctkServices() { clear(); } void ctkServices::clear() { QList<ctkServiceRegistration*> serviceRegs = services.keys(); qDeleteAll(serviceRegs); services.clear(); classServices.clear(); framework = 0; } ctkServiceRegistration* ctkServices::registerService(ctkPluginPrivate* plugin, const QStringList& classes, QObject* service, const ServiceProperties& properties) { if (service == 0) { throw std::invalid_argument("Can't register 0 as a service"); } // Check if service implements claimed classes and that they exist. for (QStringListIterator i(classes); i.hasNext();) { QString cls = i.next(); if (cls.isEmpty()) { throw std::invalid_argument("Can't register as null class"); } if (!(qobject_cast<ctkServiceFactory*>(service))) { if (!checkServiceClass(service, cls)) { throw std::invalid_argument (std::string("Service object is not an instance of ") + cls.toStdString()); } } } ctkServiceRegistration* res = new ctkServiceRegistration(plugin, service, createServiceProperties(properties, classes)); { QMutexLocker lock(&mutex); services.insert(res, classes); for (QStringListIterator i(classes); i.hasNext(); ) { QString currClass = i.next(); QList<ctkServiceRegistration*>& s = classServices[currClass]; QList<ctkServiceRegistration*>::iterator ip = std::lower_bound(s.begin(), s.end(), res, ServiceRegistrationComparator()); s.insert(ip, res); } } ctkServiceReference r = res->getReference(); plugin->fwCtx->listeners.serviceChanged( plugin->fwCtx->listeners.getMatchingServiceSlots(r), ctkServiceEvent(ctkServiceEvent::REGISTERED, r)); return res; } void ctkServices::registerService(ctkPluginPrivate* plugin, QByteArray serviceDescription) { QMutexLocker lock(&mutex); QBuffer serviceBuffer(&serviceDescription); qServiceManager.addService(&serviceBuffer); QServiceManager::Error error = qServiceManager.error(); if (!(error == QServiceManager::NoError || error == QServiceManager::ServiceAlreadyExists)) { throw std::invalid_argument(std::string("Registering the service descriptor for plugin ") + plugin->symbolicName.toStdString() + " failed: " + getQServiceManagerErrorString(error).toStdString()); } QString serviceName = plugin->symbolicName + "_" + plugin->version.toString(); QList<QServiceInterfaceDescriptor> descriptors = qServiceManager.findInterfaces(serviceName); if (descriptors.isEmpty()) { qDebug().nospace() << "Warning: No interfaces found for service name " << serviceName << " in plugin " << plugin->symbolicName << " (ctkVersion " << plugin->version.toString() << ")"; } QListIterator<QServiceInterfaceDescriptor> it(descriptors); while (it.hasNext()) { QServiceInterfaceDescriptor descr = it.next(); qDebug() << "Registering:" << descr.interfaceName(); QStringList classes; ServiceProperties props; QStringList customKeys = descr.customAttributes(); QStringListIterator keyIt(customKeys); bool classAttrFound = false; while (keyIt.hasNext()) { QString key = keyIt.next(); if (key == ctkPluginConstants::OBJECTCLASS) { classAttrFound = true; classes << descr.customAttribute(key); } else { props.insert(key, descr.customAttribute(key)); } } if (!classAttrFound) { throw std::invalid_argument(std::string("The custom attribute \"") + ctkPluginConstants::OBJECTCLASS.toStdString() + "\" is missing in the interface description of \"" + descr.interfaceName().toStdString()); } ctkServiceRegistration* res = new ctkQtServiceRegistration(plugin, descr, createServiceProperties(props, classes)); services.insert(res, classes); for (QStringListIterator i(classes); i.hasNext(); ) { QString currClass = i.next(); QList<ctkServiceRegistration*>& s = classServices[currClass]; QList<ctkServiceRegistration*>::iterator ip = std::lower_bound(s.begin(), s.end(), res, ServiceRegistrationComparator()); s.insert(ip, res); } ctkServiceReference r = res->getReference(); plugin->fwCtx->listeners.serviceChanged( plugin->fwCtx->listeners.getMatchingServiceSlots(r), ctkServiceEvent(ctkServiceEvent::REGISTERED, r)); } } QString ctkServices::getQServiceManagerErrorString(QServiceManager::Error error) { switch (error) { case QServiceManager::NoError: return QString("No error occurred."); case QServiceManager::StorageAccessError: return QString("The service data storage is not accessible. This could be because the caller does not have the required permissions."); case QServiceManager::InvalidServiceLocation: return QString("The service was not found at its specified location."); case QServiceManager::InvalidServiceXml: return QString("The XML defining the service metadata is invalid."); case QServiceManager::InvalidServiceInterfaceDescriptor: return QString("The service interface descriptor is invalid, or refers to an interface implementation that cannot be accessed in the current scope."); case QServiceManager::ServiceAlreadyExists: return QString("Another service has previously been registered with the same location."); case QServiceManager::ImplementationAlreadyExists: return QString("Another service that implements the same interface version has previously been registered."); case QServiceManager::PluginLoadingFailed: return QString("The service plugin cannot be loaded."); case QServiceManager::ComponentNotFound: return QString("The service or interface implementation has not been registered."); case QServiceManager::ServiceCapabilityDenied: return QString("The security session does not allow the service based on its capabilities."); case QServiceManager::UnknownError: return QString("An unknown error occurred."); default: return QString("Unknown error enum."); } } void ctkServices::updateServiceRegistrationOrder(ctkServiceRegistration* sr, const QStringList& classes) { QMutexLocker lock(&mutex); for (QStringListIterator i(classes); i.hasNext(); ) { QList<ctkServiceRegistration*>& s = classServices[i.next()]; s.removeAll(sr); s.insert(std::lower_bound(s.begin(), s.end(), sr, ServiceRegistrationComparator()), sr); } } bool ctkServices::checkServiceClass(QObject* service, const QString& cls) const { return service->inherits(cls.toAscii()); } QList<ctkServiceRegistration*> ctkServices::get(const QString& clazz) const { QMutexLocker lock(&mutex); return classServices.value(clazz); } ctkServiceReference ctkServices::get(ctkPluginPrivate* plugin, const QString& clazz) const { QMutexLocker lock(&mutex); try { QList<ctkServiceReference> srs = get(clazz, QString()); qDebug() << "get service ref" << clazz << "for plugin" << plugin->location << " = " << srs.size() << "refs"; if (!srs.isEmpty()) { return srs.front(); } } catch (const std::invalid_argument& ) { } throw ctkServiceException(QString("No service registered for: ") + clazz); } QList<ctkServiceReference> ctkServices::get(const QString& clazz, const QString& filter) const { QMutexLocker lock(&mutex); QListIterator<ctkServiceRegistration*>* s = 0; QList<ctkServiceRegistration*> v; ctkLDAPExpr ldap; if (clazz.isEmpty()) { if (!filter.isEmpty()) { ldap = ctkLDAPExpr(filter); QSet<QString> matched = ldap.getMatchedObjectClasses(); if (!matched.isEmpty()) { v.clear(); foreach (QString className, matched) { const QList<ctkServiceRegistration*>& cl = classServices[className]; v += cl; } if (!v.isEmpty()) { s = new QListIterator<ctkServiceRegistration*>(v); } else { return QList<ctkServiceReference>(); } } else { s = new QListIterator<ctkServiceRegistration*>(services.keys()); } } else { s = new QListIterator<ctkServiceRegistration*>(services.keys()); } } else { QList<ctkServiceRegistration*> v = classServices.value(clazz); if (!v.isEmpty()) { s = new QListIterator<ctkServiceRegistration*>(v); } else { return QList<ctkServiceReference>(); } if (!filter.isEmpty()) { ldap = ctkLDAPExpr(filter); } } QList<ctkServiceReference> res; while (s->hasNext()) { ctkServiceRegistration* sr = s->next(); ctkServiceReference sri = sr->getReference(); if (filter.isEmpty() || ldap.evaluate(sr->d_func()->properties, false)) { res.push_back(sri); } } delete s; return res; } void ctkServices::removeServiceRegistration(ctkServiceRegistration* sr) { QMutexLocker lock(&mutex); QStringList classes = sr->d_func()->properties.value(ctkPluginConstants::OBJECTCLASS).toStringList(); services.remove(sr); for (QStringListIterator i(classes); i.hasNext(); ) { QString currClass = i.next(); QList<ctkServiceRegistration*>& s = classServices[currClass]; if (s.size() > 1) { s.removeAll(sr); } else { classServices.remove(currClass); } } } QList<ctkServiceRegistration*> ctkServices::getRegisteredByPlugin(ctkPluginPrivate* p) const { QMutexLocker lock(&mutex); QList<ctkServiceRegistration*> res; for (QHashIterator<ctkServiceRegistration*, QStringList> i(services); i.hasNext(); ) { ctkServiceRegistration* sr = i.next().key(); if ((sr->d_func()->plugin = p)) { res.push_back(sr); } } return res; } QList<ctkServiceRegistration*> ctkServices::getUsedByPlugin(ctkPlugin* p) const { QMutexLocker lock(&mutex); QList<ctkServiceRegistration*> res; for (QHashIterator<ctkServiceRegistration*, QStringList> i(services); i.hasNext(); ) { ctkServiceRegistration* sr = i.next().key(); if (sr->d_func()->isUsedByPlugin(p)) { res.push_back(sr); } } return res; } <commit_msg>Fixed bug: using equals operator instead of assignment<commit_after>/*============================================================================= Library: CTK Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "ctkServices_p.h" #include <QStringListIterator> #include <QMutexLocker> #include <QBuffer> #include <algorithm> #include "ctkServiceFactory.h" #include "ctkPluginConstants.h" #include "ctkPluginFrameworkContext_p.h" #include "ctkServiceException.h" #include "ctkServiceRegistrationPrivate.h" #include "ctkQtServiceRegistration_p.h" #include "ctkLDAPExpr_p.h" using namespace QtMobility; struct ServiceRegistrationComparator { bool operator()(const ctkServiceRegistration* a, const ctkServiceRegistration* b) const { return *a < *b; } }; ServiceProperties ctkServices::createServiceProperties(const ServiceProperties& in, const QStringList& classes, long sid) { static qlonglong nextServiceID = 1; ServiceProperties props; if (!in.isEmpty()) { for (ServiceProperties::const_iterator it = in.begin(); it != in.end(); ++it) { const QString key = it.key(); const QString lcKey = it.key().toLower(); for (QListIterator<QString> i(props.keys()); i.hasNext(); ) { if (lcKey == i.next()) { throw std::invalid_argument(std::string("Several entries for property: ") + key.toStdString()); } } props.insert(lcKey, in.value(key)); } } if (!classes.isEmpty()) { props.insert(ctkPluginConstants::OBJECTCLASS, classes); } props.insert(ctkPluginConstants::SERVICE_ID, sid != -1 ? sid : nextServiceID++); return props; } ctkServices::ctkServices(ctkPluginFrameworkContext* fwCtx) : mutex(QMutex::Recursive), framework(fwCtx) { } ctkServices::~ctkServices() { clear(); } void ctkServices::clear() { QList<ctkServiceRegistration*> serviceRegs = services.keys(); qDeleteAll(serviceRegs); services.clear(); classServices.clear(); framework = 0; } ctkServiceRegistration* ctkServices::registerService(ctkPluginPrivate* plugin, const QStringList& classes, QObject* service, const ServiceProperties& properties) { if (service == 0) { throw std::invalid_argument("Can't register 0 as a service"); } // Check if service implements claimed classes and that they exist. for (QStringListIterator i(classes); i.hasNext();) { QString cls = i.next(); if (cls.isEmpty()) { throw std::invalid_argument("Can't register as null class"); } if (!(qobject_cast<ctkServiceFactory*>(service))) { if (!checkServiceClass(service, cls)) { throw std::invalid_argument (std::string("Service object is not an instance of ") + cls.toStdString()); } } } ctkServiceRegistration* res = new ctkServiceRegistration(plugin, service, createServiceProperties(properties, classes)); { QMutexLocker lock(&mutex); services.insert(res, classes); for (QStringListIterator i(classes); i.hasNext(); ) { QString currClass = i.next(); QList<ctkServiceRegistration*>& s = classServices[currClass]; QList<ctkServiceRegistration*>::iterator ip = std::lower_bound(s.begin(), s.end(), res, ServiceRegistrationComparator()); s.insert(ip, res); } } ctkServiceReference r = res->getReference(); plugin->fwCtx->listeners.serviceChanged( plugin->fwCtx->listeners.getMatchingServiceSlots(r), ctkServiceEvent(ctkServiceEvent::REGISTERED, r)); return res; } void ctkServices::registerService(ctkPluginPrivate* plugin, QByteArray serviceDescription) { QMutexLocker lock(&mutex); QBuffer serviceBuffer(&serviceDescription); qServiceManager.addService(&serviceBuffer); QServiceManager::Error error = qServiceManager.error(); if (!(error == QServiceManager::NoError || error == QServiceManager::ServiceAlreadyExists)) { throw std::invalid_argument(std::string("Registering the service descriptor for plugin ") + plugin->symbolicName.toStdString() + " failed: " + getQServiceManagerErrorString(error).toStdString()); } QString serviceName = plugin->symbolicName + "_" + plugin->version.toString(); QList<QServiceInterfaceDescriptor> descriptors = qServiceManager.findInterfaces(serviceName); if (descriptors.isEmpty()) { qDebug().nospace() << "Warning: No interfaces found for service name " << serviceName << " in plugin " << plugin->symbolicName << " (ctkVersion " << plugin->version.toString() << ")"; } QListIterator<QServiceInterfaceDescriptor> it(descriptors); while (it.hasNext()) { QServiceInterfaceDescriptor descr = it.next(); qDebug() << "Registering:" << descr.interfaceName(); QStringList classes; ServiceProperties props; QStringList customKeys = descr.customAttributes(); QStringListIterator keyIt(customKeys); bool classAttrFound = false; while (keyIt.hasNext()) { QString key = keyIt.next(); if (key == ctkPluginConstants::OBJECTCLASS) { classAttrFound = true; classes << descr.customAttribute(key); } else { props.insert(key, descr.customAttribute(key)); } } if (!classAttrFound) { throw std::invalid_argument(std::string("The custom attribute \"") + ctkPluginConstants::OBJECTCLASS.toStdString() + "\" is missing in the interface description of \"" + descr.interfaceName().toStdString()); } ctkServiceRegistration* res = new ctkQtServiceRegistration(plugin, descr, createServiceProperties(props, classes)); services.insert(res, classes); for (QStringListIterator i(classes); i.hasNext(); ) { QString currClass = i.next(); QList<ctkServiceRegistration*>& s = classServices[currClass]; QList<ctkServiceRegistration*>::iterator ip = std::lower_bound(s.begin(), s.end(), res, ServiceRegistrationComparator()); s.insert(ip, res); } ctkServiceReference r = res->getReference(); plugin->fwCtx->listeners.serviceChanged( plugin->fwCtx->listeners.getMatchingServiceSlots(r), ctkServiceEvent(ctkServiceEvent::REGISTERED, r)); } } QString ctkServices::getQServiceManagerErrorString(QServiceManager::Error error) { switch (error) { case QServiceManager::NoError: return QString("No error occurred."); case QServiceManager::StorageAccessError: return QString("The service data storage is not accessible. This could be because the caller does not have the required permissions."); case QServiceManager::InvalidServiceLocation: return QString("The service was not found at its specified location."); case QServiceManager::InvalidServiceXml: return QString("The XML defining the service metadata is invalid."); case QServiceManager::InvalidServiceInterfaceDescriptor: return QString("The service interface descriptor is invalid, or refers to an interface implementation that cannot be accessed in the current scope."); case QServiceManager::ServiceAlreadyExists: return QString("Another service has previously been registered with the same location."); case QServiceManager::ImplementationAlreadyExists: return QString("Another service that implements the same interface version has previously been registered."); case QServiceManager::PluginLoadingFailed: return QString("The service plugin cannot be loaded."); case QServiceManager::ComponentNotFound: return QString("The service or interface implementation has not been registered."); case QServiceManager::ServiceCapabilityDenied: return QString("The security session does not allow the service based on its capabilities."); case QServiceManager::UnknownError: return QString("An unknown error occurred."); default: return QString("Unknown error enum."); } } void ctkServices::updateServiceRegistrationOrder(ctkServiceRegistration* sr, const QStringList& classes) { QMutexLocker lock(&mutex); for (QStringListIterator i(classes); i.hasNext(); ) { QList<ctkServiceRegistration*>& s = classServices[i.next()]; s.removeAll(sr); s.insert(std::lower_bound(s.begin(), s.end(), sr, ServiceRegistrationComparator()), sr); } } bool ctkServices::checkServiceClass(QObject* service, const QString& cls) const { return service->inherits(cls.toAscii()); } QList<ctkServiceRegistration*> ctkServices::get(const QString& clazz) const { QMutexLocker lock(&mutex); return classServices.value(clazz); } ctkServiceReference ctkServices::get(ctkPluginPrivate* plugin, const QString& clazz) const { QMutexLocker lock(&mutex); try { QList<ctkServiceReference> srs = get(clazz, QString()); qDebug() << "get service ref" << clazz << "for plugin" << plugin->location << " = " << srs.size() << "refs"; if (!srs.isEmpty()) { return srs.front(); } } catch (const std::invalid_argument& ) { } throw ctkServiceException(QString("No service registered for: ") + clazz); } QList<ctkServiceReference> ctkServices::get(const QString& clazz, const QString& filter) const { QMutexLocker lock(&mutex); QListIterator<ctkServiceRegistration*>* s = 0; QList<ctkServiceRegistration*> v; ctkLDAPExpr ldap; if (clazz.isEmpty()) { if (!filter.isEmpty()) { ldap = ctkLDAPExpr(filter); QSet<QString> matched = ldap.getMatchedObjectClasses(); if (!matched.isEmpty()) { v.clear(); foreach (QString className, matched) { const QList<ctkServiceRegistration*>& cl = classServices[className]; v += cl; } if (!v.isEmpty()) { s = new QListIterator<ctkServiceRegistration*>(v); } else { return QList<ctkServiceReference>(); } } else { s = new QListIterator<ctkServiceRegistration*>(services.keys()); } } else { s = new QListIterator<ctkServiceRegistration*>(services.keys()); } } else { QList<ctkServiceRegistration*> v = classServices.value(clazz); if (!v.isEmpty()) { s = new QListIterator<ctkServiceRegistration*>(v); } else { return QList<ctkServiceReference>(); } if (!filter.isEmpty()) { ldap = ctkLDAPExpr(filter); } } QList<ctkServiceReference> res; while (s->hasNext()) { ctkServiceRegistration* sr = s->next(); ctkServiceReference sri = sr->getReference(); if (filter.isEmpty() || ldap.evaluate(sr->d_func()->properties, false)) { res.push_back(sri); } } delete s; return res; } void ctkServices::removeServiceRegistration(ctkServiceRegistration* sr) { QMutexLocker lock(&mutex); QStringList classes = sr->d_func()->properties.value(ctkPluginConstants::OBJECTCLASS).toStringList(); services.remove(sr); for (QStringListIterator i(classes); i.hasNext(); ) { QString currClass = i.next(); QList<ctkServiceRegistration*>& s = classServices[currClass]; if (s.size() > 1) { s.removeAll(sr); } else { classServices.remove(currClass); } } } QList<ctkServiceRegistration*> ctkServices::getRegisteredByPlugin(ctkPluginPrivate* p) const { QMutexLocker lock(&mutex); QList<ctkServiceRegistration*> res; for (QHashIterator<ctkServiceRegistration*, QStringList> i(services); i.hasNext(); ) { ctkServiceRegistration* sr = i.next().key(); if ((sr->d_func()->plugin == p)) { res.push_back(sr); } } return res; } QList<ctkServiceRegistration*> ctkServices::getUsedByPlugin(ctkPlugin* p) const { QMutexLocker lock(&mutex); QList<ctkServiceRegistration*> res; for (QHashIterator<ctkServiceRegistration*, QStringList> i(services); i.hasNext(); ) { ctkServiceRegistration* sr = i.next().key(); if (sr->d_func()->isUsedByPlugin(p)) { res.push_back(sr); } } return res; } <|endoftext|>
<commit_before>// Copyright (c) Microsoft Corporation // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "pch.h" #include <httpClient/httpClient.h> #include <httpClient/httpProvider.h> #include "android_http_request.h" #include "android_platform_context.h" extern "C" { JNIEXPORT void JNICALL Java_com_xbox_httpclient_HttpClientRequest_OnRequestCompleted(JNIEnv* env, jobject instance, jlong call, jobject response) { HCCallHandle sourceCall = reinterpret_cast<HCCallHandle>(call); HttpRequest* request = nullptr; HCHttpCallGetContext(sourceCall, reinterpret_cast<void**>(&request)); std::unique_ptr<HttpRequest> sourceRequest{ request }; if (response == nullptr) { HCHttpCallResponseSetNetworkErrorCode(sourceCall, E_FAIL, 0); XAsyncComplete(sourceRequest->GetAsyncBlock(), E_FAIL, 0); } else { HRESULT result = sourceRequest->ProcessResponse(sourceCall, response); XAsyncComplete(sourceRequest->GetAsyncBlock(), result, 0); } } JNIEXPORT void JNICALL Java_com_xbox_httpclient_HttpClientRequest_OnRequestFailed(JNIEnv* env, jobject instance, jlong call, jstring errorMessage) { HCCallHandle sourceCall = reinterpret_cast<HCCallHandle>(call); HttpRequest* request = nullptr; HCHttpCallGetContext(sourceCall, reinterpret_cast<void**>(&request)); std::unique_ptr<HttpRequest> sourceRequest{ request }; HCHttpCallResponseSetNetworkErrorCode(sourceCall, E_FAIL, 0); const char* nativeErrorString = env->GetStringUTFChars(errorMessage, nullptr); HCHttpCallResponseSetPlatformNetworkErrorMessage(sourceCall, nativeErrorString); env->ReleaseStringUTFChars(errorMessage, nativeErrorString); XAsyncComplete(sourceRequest->GetAsyncBlock(), E_FAIL, 0); } } void Internal_HCHttpCallPerformAsync( _In_ HCCallHandle call, _Inout_ XAsyncBlock* asyncBlock, _In_opt_ void* context, _In_ HCPerformEnv env ) noexcept { auto httpSingleton = xbox::httpclient::get_http_singleton(); if (httpSingleton == nullptr) { HCHttpCallResponseSetNetworkErrorCode(call, E_HC_NOT_INITIALISED, 0); XAsyncComplete(asyncBlock, E_HC_NOT_INITIALISED, 0); return; } std::unique_ptr<HttpRequest> httpRequest{ new HttpRequest( asyncBlock, env->GetJavaVm(), env->GetApplicationContext(), env->GetHttpRequestClass(), env->GetHttpResponseClass() ) }; HRESULT result = httpRequest->Initialize(); if (!SUCCEEDED(result)) { HCHttpCallResponseSetNetworkErrorCode(call, result, 0); XAsyncComplete(asyncBlock, result, 0); return; } const char* requestUrl = nullptr; const char* requestMethod = nullptr; HCHttpCallRequestGetUrl(call, &requestMethod, &requestUrl); httpRequest->SetUrl(requestUrl); uint32_t numHeaders = 0; HCHttpCallRequestGetNumHeaders(call, &numHeaders); for (uint32_t i = 0; i < numHeaders; i++) { const char* headerName = nullptr; const char* headerValue = nullptr; HCHttpCallRequestGetHeaderAtIndex(call, i, &headerName, &headerValue); httpRequest->AddHeader(headerName, headerValue); } const uint8_t* requestBody = nullptr; const char* contentType = nullptr; uint32_t requestBodySize = 0; HCHttpCallRequestGetRequestBodyBytes(call, &requestBody, &requestBodySize); if (requestBodySize > 0) { HCHttpCallRequestGetHeader(call, "Content-Type", &contentType); } httpRequest->SetMethodAndBody(requestMethod, contentType, requestBody, requestBodySize); HCHttpCallSetContext(call, httpRequest.get()); result = httpRequest->ExecuteAsync(call); if (SUCCEEDED(result)) { httpRequest.release(); } else { XAsyncComplete(asyncBlock, E_FAIL, 0); } } <commit_msg>Fixing Android network error retry (#543)<commit_after>// Copyright (c) Microsoft Corporation // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "pch.h" #include <httpClient/httpClient.h> #include <httpClient/httpProvider.h> #include "android_http_request.h" #include "android_platform_context.h" extern "C" { JNIEXPORT void JNICALL Java_com_xbox_httpclient_HttpClientRequest_OnRequestCompleted(JNIEnv* env, jobject instance, jlong call, jobject response) { HCCallHandle sourceCall = reinterpret_cast<HCCallHandle>(call); HttpRequest* request = nullptr; HCHttpCallGetContext(sourceCall, reinterpret_cast<void**>(&request)); std::unique_ptr<HttpRequest> sourceRequest{ request }; if (response == nullptr) { HCHttpCallResponseSetNetworkErrorCode(sourceCall, E_FAIL, 0); XAsyncComplete(sourceRequest->GetAsyncBlock(), E_FAIL, 0); } else { HRESULT result = sourceRequest->ProcessResponse(sourceCall, response); XAsyncComplete(sourceRequest->GetAsyncBlock(), result, 0); } } JNIEXPORT void JNICALL Java_com_xbox_httpclient_HttpClientRequest_OnRequestFailed(JNIEnv* env, jobject instance, jlong call, jstring errorMessage) { HCCallHandle sourceCall = reinterpret_cast<HCCallHandle>(call); HttpRequest* request = nullptr; HCHttpCallGetContext(sourceCall, reinterpret_cast<void**>(&request)); std::unique_ptr<HttpRequest> sourceRequest{ request }; HCHttpCallResponseSetNetworkErrorCode(sourceCall, E_FAIL, 0); const char* nativeErrorString = env->GetStringUTFChars(errorMessage, nullptr); HCHttpCallResponseSetPlatformNetworkErrorMessage(sourceCall, nativeErrorString); env->ReleaseStringUTFChars(errorMessage, nativeErrorString); XAsyncComplete(sourceRequest->GetAsyncBlock(), S_OK, 0); } } void Internal_HCHttpCallPerformAsync( _In_ HCCallHandle call, _Inout_ XAsyncBlock* asyncBlock, _In_opt_ void* context, _In_ HCPerformEnv env ) noexcept { auto httpSingleton = xbox::httpclient::get_http_singleton(); if (httpSingleton == nullptr) { HCHttpCallResponseSetNetworkErrorCode(call, E_HC_NOT_INITIALISED, 0); XAsyncComplete(asyncBlock, E_HC_NOT_INITIALISED, 0); return; } std::unique_ptr<HttpRequest> httpRequest{ new HttpRequest( asyncBlock, env->GetJavaVm(), env->GetApplicationContext(), env->GetHttpRequestClass(), env->GetHttpResponseClass() ) }; HRESULT result = httpRequest->Initialize(); if (!SUCCEEDED(result)) { HCHttpCallResponseSetNetworkErrorCode(call, result, 0); XAsyncComplete(asyncBlock, result, 0); return; } const char* requestUrl = nullptr; const char* requestMethod = nullptr; HCHttpCallRequestGetUrl(call, &requestMethod, &requestUrl); httpRequest->SetUrl(requestUrl); uint32_t numHeaders = 0; HCHttpCallRequestGetNumHeaders(call, &numHeaders); for (uint32_t i = 0; i < numHeaders; i++) { const char* headerName = nullptr; const char* headerValue = nullptr; HCHttpCallRequestGetHeaderAtIndex(call, i, &headerName, &headerValue); httpRequest->AddHeader(headerName, headerValue); } const uint8_t* requestBody = nullptr; const char* contentType = nullptr; uint32_t requestBodySize = 0; HCHttpCallRequestGetRequestBodyBytes(call, &requestBody, &requestBodySize); if (requestBodySize > 0) { HCHttpCallRequestGetHeader(call, "Content-Type", &contentType); } httpRequest->SetMethodAndBody(requestMethod, contentType, requestBody, requestBodySize); HCHttpCallSetContext(call, httpRequest.get()); result = httpRequest->ExecuteAsync(call); if (SUCCEEDED(result)) { httpRequest.release(); } else { XAsyncComplete(asyncBlock, E_FAIL, 0); } } <|endoftext|>
<commit_before>#include "mainwindow.h" // Qt is the worst. // // Assume your keyboard has a key labelled both . and >, as they do on US and UK keyboards. Call it the dot key. // Perform the following: // 1. press dot key; // 2. press shift key; // 3. release dot key; // 4. release shift key. // // Per empirical testing, and key repeat aside, on both macOS and Ubuntu 19.04 that sequence will result in // _three_ keypress events, but only _two_ key release events. You'll get presses for Qt::Key_Period, Qt::Key_Greater // and Qt::Key_Shift. You'll get releases only for Qt::Key_Greater and Qt::Key_Shift. // // How can you detect at runtime that Key_Greater and Key_Period are the same physical key? // // You can't. On Ubuntu they have the same values for QKeyEvent::nativeScanCode(), which are unique to the key, // but they have different ::nativeVirtualKey()s. // // On macOS they have the same ::nativeScanCode() only because on macOS [almost] all keys have the same // ::nativeScanCode(). So that's not usable. They have the same ::nativeVirtualKey()s, but since that isn't true // on Ubuntu, that's also not usable. // // So how can you track the physical keys on a keyboard via Qt? // // You can't. Qt is the worst. SDL doesn't have this problem, including in X11, but I'm not sure I want the extra // dependency. I may need to reassess. #ifdef Q_OS_LINUX #define HAS_X11 #endif #ifdef HAS_X11 #include <X11/keysym.h> #endif std::optional<Inputs::Keyboard::Key> MainWindow::keyForEvent(QKeyEvent *event) { // Workaround for X11: assume PC-esque mapping. #ifdef HAS_X11 if(QGuiApplication::platformName() == QLatin1String("xcb")) { #define BIND(code, key) case code: return Inputs::Keyboard::Key::key; switch(keysym->nativeVirtualKey()) { default: qDebug() << "Unmapped" << event->nativeScanCode(); return {}; BIND(XK_Escape, Escape); BIND(XK_F1, F1); BIND(XK_F2, F2); BIND(XK_F3, F3); BIND(XK_F4, F4); BIND(XK_F5, F5); BIND(XK_F6, F6); BIND(XK_F7, F7); BIND(XK_F8, F8); BIND(XK_F9, F9); BIND(XK_F10, F10); BIND(XK_F11, F11); BIND(XK_F12, F12); BIND(XK_Sys_Req, PrintScreen); BIND(XK_Scroll_Lock, ScrollLock); BIND(XK_Pause, Pause); BIND(XK_grave, BackTick); BIND(XK_1, k1); BIND(XK_2, k2); BIND(XK_3, k3); BIND(XK_4, k4); BIND(XK_5, k5); BIND(XK_6, k6); BIND(XK_7, k7); BIND(XK_8, k8); BIND(XK_9, k9); BIND(XK_0, k0); BIND(XK_minus, Hyphen); BIND(XK_equal, Equals); BIND(XK_BackSpace, Backspace); BIND(XK_Tab, Tab); BIND(XK_Q, Q); BIND(XK_W, W); BIND(XK_E, E); BIND(XK_R, R); BIND(XK_T, T); BIND(XK_Y, Y); BIND(XK_U, U); BIND(XK_I, I); BIND(XK_O, O); BIND(XK_P, P); BIND(XK_bracketleft, OpenSquareBracket); BIND(XK_bracketright, CloseSquareBracket); BIND(XK_backslash, Backslash); BIND(XK_Caps_Lock, CapsLock); BIND(XK_A, A); BIND(XK_S, S); BIND(XK_D, D); BIND(XK_F, F); BIND(XK_G, G); BIND(XK_H, H); BIND(XK_J, J); BIND(XK_K, K); BIND(XK_L, L); BIND(XK_semicolon, Semicolon); BIND(XK_apostrophe, Quote); BIND(XK_Return, Enter); BIND(XK_Shift_L, LeftShift); BIND(XK_Z, Z); BIND(XK_X, X); BIND(XK_C, C); BIND(XK_V, V); BIND(XK_B, B); BIND(XK_N, N); BIND(XK_M, M); BIND(XK_comma, Comma); BIND(XK_period, FullStop); BIND(XK_slash, ForwardSlash); BIND(XK_Shift_R, RightShift); BIND(XK_Control_L, LeftControl); BIND(XK_Control_R, RightControl); BIND(XK_Alt_L, LeftOption); BIND(XK_Alt_R, RightOption); BIND(XK_Meta_L, LeftMeta); BIND(XK_Meta_R, RightMeta); BIND(XK_space, Space); BIND(XK_Left, Left); BIND(XK_Right, Right); BIND(XK_Up, Up); BIND(XK_Down, Down); BIND(XK_Insert, Insert); BIND(XK_Delete, Delete); BIND(XK_Home, Home); BIND(XK_End, End); BIND(XK_Num_Lock, NumLock); BIND(XK_KP_Divide, KeypadSlash); BIND(XK_KP_Multiply, KeypadAsterisk); BIND(XK_KP_Delete, KeypadDelete); BIND(XK_KP_7, Keypad7); BIND(XK_KP_8, Keypad8); BIND(XK_KP_9, Keypad9); BIND(XK_KP_Add, KeypadPlus); BIND(XK_KP_4, Keypad4); BIND(XK_KP_5, Keypad5); BIND(XK_KP_6, Keypad6); BIND(XK_KP_Subtract, KeypadMinus); BIND(XK_KP_1, Keypad1); BIND(XK_KP_2, Keypad2); BIND(XK_KP_3, Keypad3); BIND(XK_KP_Enter, KeypadEnter); BIND(XK_KP_0, Keypad0); BIND(XK_KP_Decimal, KeypadDecimalPoint); BIND(XK_KP_Equal, KeypadEquals); BIND(XK_Help, Help); } #undef BIND } #endif // Fall back on a limited, faulty adaptation. #define BIND2(qtKey, clkKey) case Qt::qtKey: return Inputs::Keyboard::Key::clkKey; #define BIND(key) BIND2(Key_##key, key) switch(event->key()) { default: return {}; BIND(Escape); BIND(F1); BIND(F2); BIND(F3); BIND(F4); BIND(F5); BIND(F6); BIND(F7); BIND(F8); BIND(F9); BIND(F10); BIND(F11); BIND(F12); BIND2(Key_Print, PrintScreen); BIND(ScrollLock); BIND(Pause); BIND2(Key_AsciiTilde, BackTick); BIND2(Key_1, k1); BIND2(Key_2, k2); BIND2(Key_3, k3); BIND2(Key_4, k4); BIND2(Key_5, k5); BIND2(Key_6, k6); BIND2(Key_7, k7); BIND2(Key_8, k8); BIND2(Key_9, k9); BIND2(Key_0, k0); BIND2(Key_Minus, Hyphen); BIND2(Key_Plus, Equals); BIND(Backspace); BIND(Tab); BIND(Q); BIND(W); BIND(E); BIND(R); BIND(T); BIND(Y); BIND(U); BIND(I); BIND(O); BIND(P); BIND2(Key_BraceLeft, OpenSquareBracket); BIND2(Key_BraceRight, CloseSquareBracket); BIND(Backslash); BIND(CapsLock); BIND(A); BIND(S); BIND(D); BIND(F); BIND(G); BIND(H); BIND(J); BIND(K); BIND(L); BIND(Semicolon); BIND2(Key_Apostrophe, Quote); BIND2(Key_QuoteDbl, Quote); // TODO: something to hash? BIND2(Key_Return, Enter); BIND2(Key_Shift, LeftShift); BIND(Z); BIND(X); BIND(C); BIND(V); BIND(B); BIND(N); BIND(M); BIND(Comma); BIND2(Key_Period, FullStop); BIND2(Key_Slash, ForwardSlash); // Omitted: right shift. BIND2(Key_Control, LeftControl); BIND2(Key_Alt, LeftOption); BIND2(Key_Meta, LeftMeta); BIND(Space); BIND2(Key_AltGr, RightOption); BIND(Left); BIND(Right); BIND(Up); BIND(Down); BIND(Insert); BIND(Home); BIND(PageUp); BIND(Delete); BIND(End); BIND(PageDown); BIND(NumLock); } #undef BIND #undef BIND2 } <commit_msg>Fix class name, add constructor.<commit_after>#include "mainwindow.h" // Qt is the worst. // // Assume your keyboard has a key labelled both . and >, as they do on US and UK keyboards. Call it the dot key. // Perform the following: // 1. press dot key; // 2. press shift key; // 3. release dot key; // 4. release shift key. // // Per empirical testing, and key repeat aside, on both macOS and Ubuntu 19.04 that sequence will result in // _three_ keypress events, but only _two_ key release events. You'll get presses for Qt::Key_Period, Qt::Key_Greater // and Qt::Key_Shift. You'll get releases only for Qt::Key_Greater and Qt::Key_Shift. // // How can you detect at runtime that Key_Greater and Key_Period are the same physical key? // // You can't. On Ubuntu they have the same values for QKeyEvent::nativeScanCode(), which are unique to the key, // but they have different ::nativeVirtualKey()s. // // On macOS they have the same ::nativeScanCode() only because on macOS [almost] all keys have the same // ::nativeScanCode(). So that's not usable. They have the same ::nativeVirtualKey()s, but since that isn't true // on Ubuntu, that's also not usable. // // So how can you track the physical keys on a keyboard via Qt? // // You can't. Qt is the worst. SDL doesn't have this problem, including in X11, but I'm not sure I want the extra // dependency. I may need to reassess. #ifdef Q_OS_LINUX #define HAS_X11 #endif #ifdef HAS_X11 #include <X11/keysym.h> #endif KeyboardMapper::KeyboardMapper() { #ifdef HAS_X11 #endif } std::optional<Inputs::Keyboard::Key> KeyboardMapper::keyForEvent(QKeyEvent *event) { // Workaround for X11: assume PC-esque mapping. #ifdef HAS_X11 if(QGuiApplication::platformName() == QLatin1String("xcb")) { #define BIND(code, key) case code: return Inputs::Keyboard::Key::key; switch(event->nativeVirtualKey()) { default: qDebug() << "Unmapped" << event->nativeScanCode(); return {}; BIND(XK_Escape, Escape); BIND(XK_F1, F1); BIND(XK_F2, F2); BIND(XK_F3, F3); BIND(XK_F4, F4); BIND(XK_F5, F5); BIND(XK_F6, F6); BIND(XK_F7, F7); BIND(XK_F8, F8); BIND(XK_F9, F9); BIND(XK_F10, F10); BIND(XK_F11, F11); BIND(XK_F12, F12); BIND(XK_Sys_Req, PrintScreen); BIND(XK_Scroll_Lock, ScrollLock); BIND(XK_Pause, Pause); BIND(XK_grave, BackTick); BIND(XK_1, k1); BIND(XK_2, k2); BIND(XK_3, k3); BIND(XK_4, k4); BIND(XK_5, k5); BIND(XK_6, k6); BIND(XK_7, k7); BIND(XK_8, k8); BIND(XK_9, k9); BIND(XK_0, k0); BIND(XK_minus, Hyphen); BIND(XK_equal, Equals); BIND(XK_BackSpace, Backspace); BIND(XK_Tab, Tab); BIND(XK_Q, Q); BIND(XK_W, W); BIND(XK_E, E); BIND(XK_R, R); BIND(XK_T, T); BIND(XK_Y, Y); BIND(XK_U, U); BIND(XK_I, I); BIND(XK_O, O); BIND(XK_P, P); BIND(XK_bracketleft, OpenSquareBracket); BIND(XK_bracketright, CloseSquareBracket); BIND(XK_backslash, Backslash); BIND(XK_Caps_Lock, CapsLock); BIND(XK_A, A); BIND(XK_S, S); BIND(XK_D, D); BIND(XK_F, F); BIND(XK_G, G); BIND(XK_H, H); BIND(XK_J, J); BIND(XK_K, K); BIND(XK_L, L); BIND(XK_semicolon, Semicolon); BIND(XK_apostrophe, Quote); BIND(XK_Return, Enter); BIND(XK_Shift_L, LeftShift); BIND(XK_Z, Z); BIND(XK_X, X); BIND(XK_C, C); BIND(XK_V, V); BIND(XK_B, B); BIND(XK_N, N); BIND(XK_M, M); BIND(XK_comma, Comma); BIND(XK_period, FullStop); BIND(XK_slash, ForwardSlash); BIND(XK_Shift_R, RightShift); BIND(XK_Control_L, LeftControl); BIND(XK_Control_R, RightControl); BIND(XK_Alt_L, LeftOption); BIND(XK_Alt_R, RightOption); BIND(XK_Meta_L, LeftMeta); BIND(XK_Meta_R, RightMeta); BIND(XK_space, Space); BIND(XK_Left, Left); BIND(XK_Right, Right); BIND(XK_Up, Up); BIND(XK_Down, Down); BIND(XK_Insert, Insert); BIND(XK_Delete, Delete); BIND(XK_Home, Home); BIND(XK_End, End); BIND(XK_Num_Lock, NumLock); BIND(XK_KP_Divide, KeypadSlash); BIND(XK_KP_Multiply, KeypadAsterisk); BIND(XK_KP_Delete, KeypadDelete); BIND(XK_KP_7, Keypad7); BIND(XK_KP_8, Keypad8); BIND(XK_KP_9, Keypad9); BIND(XK_KP_Add, KeypadPlus); BIND(XK_KP_4, Keypad4); BIND(XK_KP_5, Keypad5); BIND(XK_KP_6, Keypad6); BIND(XK_KP_Subtract, KeypadMinus); BIND(XK_KP_1, Keypad1); BIND(XK_KP_2, Keypad2); BIND(XK_KP_3, Keypad3); BIND(XK_KP_Enter, KeypadEnter); BIND(XK_KP_0, Keypad0); BIND(XK_KP_Decimal, KeypadDecimalPoint); BIND(XK_KP_Equal, KeypadEquals); BIND(XK_Help, Help); } #undef BIND } #endif // Fall back on a limited, faulty adaptation. #define BIND2(qtKey, clkKey) case Qt::qtKey: return Inputs::Keyboard::Key::clkKey; #define BIND(key) BIND2(Key_##key, key) switch(event->key()) { default: return {}; BIND(Escape); BIND(F1); BIND(F2); BIND(F3); BIND(F4); BIND(F5); BIND(F6); BIND(F7); BIND(F8); BIND(F9); BIND(F10); BIND(F11); BIND(F12); BIND2(Key_Print, PrintScreen); BIND(ScrollLock); BIND(Pause); BIND2(Key_AsciiTilde, BackTick); BIND2(Key_1, k1); BIND2(Key_2, k2); BIND2(Key_3, k3); BIND2(Key_4, k4); BIND2(Key_5, k5); BIND2(Key_6, k6); BIND2(Key_7, k7); BIND2(Key_8, k8); BIND2(Key_9, k9); BIND2(Key_0, k0); BIND2(Key_Minus, Hyphen); BIND2(Key_Plus, Equals); BIND(Backspace); BIND(Tab); BIND(Q); BIND(W); BIND(E); BIND(R); BIND(T); BIND(Y); BIND(U); BIND(I); BIND(O); BIND(P); BIND2(Key_BraceLeft, OpenSquareBracket); BIND2(Key_BraceRight, CloseSquareBracket); BIND(Backslash); BIND(CapsLock); BIND(A); BIND(S); BIND(D); BIND(F); BIND(G); BIND(H); BIND(J); BIND(K); BIND(L); BIND(Semicolon); BIND2(Key_Apostrophe, Quote); BIND2(Key_QuoteDbl, Quote); // TODO: something to hash? BIND2(Key_Return, Enter); BIND2(Key_Shift, LeftShift); BIND(Z); BIND(X); BIND(C); BIND(V); BIND(B); BIND(N); BIND(M); BIND(Comma); BIND2(Key_Period, FullStop); BIND2(Key_Slash, ForwardSlash); // Omitted: right shift. BIND2(Key_Control, LeftControl); BIND2(Key_Alt, LeftOption); BIND2(Key_Meta, LeftMeta); BIND(Space); BIND2(Key_AltGr, RightOption); BIND(Left); BIND(Right); BIND(Up); BIND(Down); BIND(Insert); BIND(Home); BIND(PageUp); BIND(Delete); BIND(End); BIND(PageDown); BIND(NumLock); } #undef BIND #undef BIND2 } <|endoftext|>
<commit_before>/* * Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include "bpmhistogramdescriptors.h" #include "essentiamath.h" using namespace std; using namespace essentia; using namespace standard; const char* BpmHistogramDescriptors::name = "BpmHistogramDescriptors"; const char* BpmHistogramDescriptors::description = DOC("This algorithm computes beats per minute histogram and its statistics for the highest and second highest peak.\n" "Note: histogram vector contains occurance frequency for each bpm value, 0-th element corresponds to 0 bpm value."); const int BpmHistogramDescriptors::maxBPM = 250; // max number of BPM bins const int BpmHistogramDescriptors::numPeaks = 2; const int BpmHistogramDescriptors::weightWidth = 3; const int BpmHistogramDescriptors::spreadWidth = 9; void BpmHistogramDescriptors::compute() { // copy input vector<Real> bpmValues = _bpmIntervals.get(); // drop too-short intervals Real threshold = 60. / Real(maxBPM); vector<Real>::iterator i = bpmValues.begin(); while (i != bpmValues.end()) { if (*i < threshold) { i = bpmValues.erase(i); } else { // convert values from interval to bpm bpmValues[i - bpmValues.begin()] = 60. / bpmValues[i - bpmValues.begin()]; ++i; } } if (bpmValues.empty()) { _firstPeakBPM.get() = 0.0; _firstPeakWeight.get() = 0.0; _firstPeakSpread.get() = 0.0; _secondPeakBPM.get() = 0.0; _secondPeakWeight.get() = 0.0; _secondPeakSpread.get() = 0.0; return; } // compute histogram vector<Real> weights(maxBPM, 0.0); for (int i=0; i<int(bpmValues.size()); ++i) { int idx = min( maxBPM-1, int(round(bpmValues[i]))); weights[idx]++; } // normalize histogram weights for (int i=0; i<int(weights.size()); ++i) { weights[i] /= bpmValues.size(); } _histogram.get() = weights; // peaks stats vector<Real> peakBPMs; vector<Real> peakWeights; vector<Real> peakSpreads; for (int i=0; i<numPeaks; ++i) { int idx = argmax(weights); Real peakBPM = idx; // peak weight is the weight of the peak and the weights of its two neighbors Real peakWeight = weights[idx] + (idx>0 ? weights[idx - ((weightWidth-1) / 2)] : 0) + (idx<int(weights.size())-1 ? weights[idx + ((weightWidth-1) / 2)] : 0); Real peakSpread = 0.0; int minIndex = max(idx - ((spreadWidth-1) / 2), 0); int maxIndex = min(idx + ((spreadWidth-1) / 2), int(weights.size())); for (int i=minIndex; i<=maxIndex; ++i) { peakSpread += weights[i]; weights[i] = 0.0; } if (peakSpread > 0) { peakSpread = 1 - peakWeight / peakSpread; } peakBPMs.push_back(peakBPM); peakWeights.push_back(peakWeight); peakSpreads.push_back(peakSpread); } // output results _firstPeakBPM.get() = peakBPMs[0]; _firstPeakWeight.get() = peakWeights[0]; _firstPeakSpread.get() = peakSpreads[0]; _secondPeakBPM.get() = peakBPMs[1]; _secondPeakWeight.get() = peakWeights[1]; _secondPeakSpread.get() = peakSpreads[1]; } <commit_msg>Return zero histogram in the case of empty signal<commit_after>/* * Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include "bpmhistogramdescriptors.h" #include "essentiamath.h" using namespace std; using namespace essentia; using namespace standard; const char* BpmHistogramDescriptors::name = "BpmHistogramDescriptors"; const char* BpmHistogramDescriptors::description = DOC("This algorithm computes beats per minute histogram and its statistics for the highest and second highest peak.\n" "Note: histogram vector contains occurance frequency for each bpm value, 0-th element corresponds to 0 bpm value."); const int BpmHistogramDescriptors::maxBPM = 250; // max number of BPM bins const int BpmHistogramDescriptors::numPeaks = 2; const int BpmHistogramDescriptors::weightWidth = 3; const int BpmHistogramDescriptors::spreadWidth = 9; void BpmHistogramDescriptors::compute() { // copy input vector<Real> bpmValues = _bpmIntervals.get(); // drop too-short intervals Real threshold = 60. / Real(maxBPM); vector<Real>::iterator i = bpmValues.begin(); while (i != bpmValues.end()) { if (*i < threshold) { i = bpmValues.erase(i); } else { // convert values from interval to bpm bpmValues[i - bpmValues.begin()] = 60. / bpmValues[i - bpmValues.begin()]; ++i; } } vector<Real> weights(maxBPM, 0.0); if (bpmValues.empty()) { _firstPeakBPM.get() = 0.0; _firstPeakWeight.get() = 0.0; _firstPeakSpread.get() = 0.0; _secondPeakBPM.get() = 0.0; _secondPeakWeight.get() = 0.0; _secondPeakSpread.get() = 0.0; _histogram.get() = weights; return; } // compute histogram for (int i=0; i<int(bpmValues.size()); ++i) { int idx = min( maxBPM-1, int(round(bpmValues[i]))); weights[idx]++; } // normalize histogram weights for (int i=0; i<int(weights.size()); ++i) { weights[i] /= bpmValues.size(); } _histogram.get() = weights; // peaks stats vector<Real> peakBPMs; vector<Real> peakWeights; vector<Real> peakSpreads; for (int i=0; i<numPeaks; ++i) { int idx = argmax(weights); Real peakBPM = idx; // peak weight is the weight of the peak and the weights of its two neighbors Real peakWeight = weights[idx] + (idx>0 ? weights[idx - ((weightWidth-1) / 2)] : 0) + (idx<int(weights.size())-1 ? weights[idx + ((weightWidth-1) / 2)] : 0); Real peakSpread = 0.0; int minIndex = max(idx - ((spreadWidth-1) / 2), 0); int maxIndex = min(idx + ((spreadWidth-1) / 2), int(weights.size())); for (int i=minIndex; i<=maxIndex; ++i) { peakSpread += weights[i]; weights[i] = 0.0; } if (peakSpread > 0) { peakSpread = 1 - peakWeight / peakSpread; } peakBPMs.push_back(peakBPM); peakWeights.push_back(peakWeight); peakSpreads.push_back(peakSpread); } // output results _firstPeakBPM.get() = peakBPMs[0]; _firstPeakWeight.get() = peakWeights[0]; _firstPeakSpread.get() = peakSpreads[0]; _secondPeakBPM.get() = peakBPMs[1]; _secondPeakWeight.get() = peakWeights[1]; _secondPeakSpread.get() = peakSpreads[1]; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkGEImageIOTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <string> #include "itkGEAdwImageIO.h" #include "itkGE4ImageIO.h" #include "itkGE5ImageIO.h" #include "itkSiemensVisionImageIO.h" #include "itkGEAdwImageIOFactory.h" #include "itkGE4ImageIOFactory.h" #include "itkGE5ImageIOFactory.h" #include "itkSiemensVisionImageIOFactory.h" #include "itkImageIOFactory.h" #include "itkExceptionObject.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkImage.h" #include <itksys/SystemTools.hxx> typedef itk::Image<signed short, 3> ImageType ; typedef ImageType::Pointer ImagePointer ; typedef itk::ImageFileReader< ImageType > ImageReaderType ; typedef itk::ImageFileWriter< ImageType > ImageWriterType ; int itkGEImageIOFactoryTest(int ac, char * av[]) { static bool firstTime = true; if(firstTime) { itk::ObjectFactoryBase::RegisterFactory(itk::GEAdwImageIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory(itk::GE4ImageIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory(itk::GE5ImageIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory(itk::SiemensVisionImageIOFactory::New() ); firstTime = false; } if(ac < 2) { return EXIT_FAILURE; } char *filename = *++av; ImagePointer input ; ImageReaderType::Pointer imageReader = ImageReaderType::New() ; try { imageReader->SetFileName(filename); imageReader->Update() ; input = imageReader->GetOutput() ; } catch (itk::ExceptionObject &e) { std::cerr << "Caught unexpected exception. Test Failed!" << std::endl; std::cerr << e << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } int itkGEImageIOTest(int ac, char * av[]) { // // first argument is passing in the writable directory to do all testing if(ac > 1) { char *testdir = *++av; --ac; itksys::SystemTools::ChangeDirectory(testdir); } if((ac != 5) && (ac != 4)) { return EXIT_FAILURE; } std::string failmode(av[1]); std::string filetype(av[2]); std::string filename(av[3]); bool Failmode = failmode == std::string("true"); itk::ImageIOBase::Pointer io; if(filetype == "GE4") { io = itk::GE4ImageIO::New(); } else if(filetype == "GE5") { io = itk::GE5ImageIO::New(); } else if(filetype == "GEAdw") { io = itk::GEAdwImageIO::New(); } else if(filetype == "Siemens") { io = itk::SiemensVisionImageIO::New(); } else { return EXIT_FAILURE; } ImagePointer input ; ImageReaderType::Pointer imageReader = ImageReaderType::New() ; try { imageReader->SetImageIO(io); imageReader->SetFileName(filename.c_str()) ; imageReader->Update() ; input = imageReader->GetOutput() ; } catch (itk::ExceptionObject &e) { if (Failmode) { std::cerr << "Caught unexpected exception. Test Failed!" << std::endl; } else { std::cerr << "Caught expected exception. Test Passed!" << std::endl; } std::cerr << e << std::endl; return Failmode ? 1 : 0; } if (failmode == std::string("true")) { ImageWriterType::Pointer writer = ImageWriterType::New(); writer->SetInput( input ); writer->SetFileName( av[4] ); writer->Update(); } return Failmode ? 0 : 1; } <commit_msg>COMP: trying to track down test failures on Intel 9.0 64 bit compiler.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkGEImageIOTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <string> #include "itkGEAdwImageIO.h" #include "itkGE4ImageIO.h" #include "itkGE5ImageIO.h" #include "itkSiemensVisionImageIO.h" #include "itkGEAdwImageIOFactory.h" #include "itkGE4ImageIOFactory.h" #include "itkGE5ImageIOFactory.h" #include "itkSiemensVisionImageIOFactory.h" #include "itkImageIOFactory.h" #include "itkExceptionObject.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkImage.h" #include <itksys/SystemTools.hxx> typedef itk::Image<signed short, 3> ImageType ; typedef ImageType::Pointer ImagePointer ; typedef itk::ImageFileReader< ImageType > ImageReaderType ; typedef itk::ImageFileWriter< ImageType > ImageWriterType ; int itkGEImageIOFactoryTest(int ac, char * av[]) { static bool firstTime = true; if(firstTime) { itk::ObjectFactoryBase::RegisterFactory(itk::GEAdwImageIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory(itk::GE4ImageIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory(itk::GE5ImageIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory(itk::SiemensVisionImageIOFactory::New() ); firstTime = false; } if(ac < 2) { return EXIT_FAILURE; } char *filename = *++av; ImagePointer input ; ImageReaderType::Pointer imageReader = ImageReaderType::New() ; try { imageReader->SetFileName(filename); imageReader->Update() ; input = imageReader->GetOutput() ; } catch (itk::ExceptionObject &e) { std::cout << "Caught unexpected exception. Test Failed!" << std::endl; std::cout << e << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } int itkGEImageIOTest(int ac, char * av[]) { // // first argument is passing in the writable directory to do all testing if(ac > 1) { char *testdir = *++av; --ac; itksys::SystemTools::ChangeDirectory(testdir); } if((ac != 5) && (ac != 4)) { return EXIT_FAILURE; } std::string failmode(av[1]); std::string filetype(av[2]); std::string filename(av[3]); bool Failmode = failmode == std::string("true"); itk::ImageIOBase::Pointer io; if(filetype == "GE4") { io = itk::GE4ImageIO::New(); } else if(filetype == "GE5") { io = itk::GE5ImageIO::New(); } else if(filetype == "GEAdw") { io = itk::GEAdwImageIO::New(); } else if(filetype == "Siemens") { io = itk::SiemensVisionImageIO::New(); } else { return EXIT_FAILURE; } ImagePointer input ; ImageReaderType::Pointer imageReader = ImageReaderType::New() ; try { imageReader->SetImageIO(io); imageReader->SetFileName(filename.c_str()) ; imageReader->Update() ; input = imageReader->GetOutput() ; } catch (itk::ExceptionObject &e) { if (Failmode) { std::cout << "Caught unexpected exception. Test Failed!" << std::endl; } else { std::cout << "Caught expected exception. Test Passed!" << std::endl; } std::cout << e << std::endl; return Failmode ? 1 : 0; } if (failmode == std::string("true")) { ImageWriterType::Pointer writer = ImageWriterType::New(); writer->SetInput( input ); writer->SetFileName( av[4] ); writer->Update(); } return Failmode ? 0 : 1; } <|endoftext|>
<commit_before>#include "Thermostat.h" #include "Nose_Hoover_Chain.h" #include "Andersen.h" #include "Lowe_Andersen.h" #include "Gaussian.h" #include "Nose_Hoover.h" #include "Thermostat_None.h" #include "Berendsen.h" #include "Bussi.h" #include "Functions.h" #include "consts.h" using namespace consts; #include <iostream> #include <fstream> #include <algorithm> #include <cmath> #include <string> #include <cstring> using namespace std; /* ######################### */ int main(int argc, char* argv[]) { //default für p,Temp,dtime,runs,warmlauf,ausgabe :jedes xte wird ausgegeben double a_para[]{4, 20, 1E-15, 1E6, 1E3, 1}; int i_para{ 1 }; string s_para{}, s_therm{}; string s_temp{}, s_pos_vel{}; ofstream dat_temp{}, dat_pos_vel{}; Thermostat *thermostat{}; // Bestimmen der Parameter zur Initialisierung von Poly und Thermostat for (i_para = 1; i_para < min(7, argc); ++i_para) { if (is_number(argv[i_para])) a_para[i_para - 1] = stod(argv[i_para]); else break; } a_para[2] /= ref_time; while (i_para < argc - 1 && is_number(argv[i_para])) ++i_para; int i_thermos = i_para; while (++i_para < argc - 1 && is_number(argv[i_para])) ++i_para; int i_poly_init = min(argc - 1, i_para); Polymer poly{ static_cast<unsigned> (a_para[0]), a_para[1] }; if (strcmp(argv[i_poly_init], "one") == 0) poly.initiate_monomers_one(); else poly.initiate_monomers_random(); // Auswählen des Thermostats if (argc > 1 && i_thermos < argc) { if (strcmp(argv[i_thermos], "Andersen") == 0) { double nu{ set_param(1. / a_para[2] / a_para[0], argv, argc, i_thermos + 1) }; thermostat = new Andersen{ poly, a_para[2], nu }; s_therm = "Andersen"; } else if (strcmp(argv[i_thermos], "Lowe_Andersen") == 0) { double nu{ set_param(1. / a_para[2] / a_para[0], argv, argc, i_thermos + 1) }; thermostat = new Lowe_Andersen{ poly, a_para[2], nu }; s_therm = "Lowe_Andersen"; } else if (strcmp(argv[i_thermos], "Gaussian") == 0) { thermostat = new Gaussian{ poly, a_para[2] }; s_therm = "Gaussian"; } else if (strcmp(argv[i_thermos], "Nose_Hoover") == 0) { double q_def{ poly.monomers.size()*poly.target_temperature()*ref_time / 1E-12 }; double q{ set_param(q_def, argv, argc, i_thermos + 1) }; thermostat = new Nose_Hoover{ poly, a_para[2], q }; s_therm = "Nose_Hoover"; } else if (strcmp(argv[i_thermos], "Nose_Hoover_Chain") == 0) { double q_def{ poly.monomers.size()*poly.monomer_mass*poly.target_temperature()/poly.feder_konst() }; double q{ set_param(q_def, argv, argc, i_thermos + 1) }; double q2 = poly.monomer_mass*poly.target_temperature()/poly.feder_konst(); //changemeplease thermostat = new Nose_Hoover_Chain{ poly, a_para[2], q, q2 }; s_therm = "Nose_Hoover_Chain"; } else if (strcmp(argv[i_thermos], "Berendsen") == 0) { double couplingtime = 10 * a_para[2]; thermostat = new Berendsen{ poly, a_para[2], couplingtime }; s_therm = "Berendsen"; } else if (strcmp(argv[i_thermos], "Bussi") == 0) { double couplingtime = 10 * a_para[2]; thermostat = new Bussi{ poly, a_para[2], couplingtime }; s_therm = "Bussi"; } else { thermostat = new Thermostat_None{ poly, a_para[2] }; s_therm = "None"; } } else { thermostat = new Thermostat_None{ poly, a_para[2] }; s_therm = "None"; } cout << "Thermostat:\t" << s_therm << endl; s_para = "_p"; s_para += to_string((int)a_para[0]); s_para += "_T"; s_para += to_string((int)a_para[1]); s_temp = s_therm + "_temp" + s_para + ".dat"; dat_temp.open(s_temp, ios::out | ios::trunc); s_pos_vel = s_therm + "_pos_vel" + s_para + ".dat"; dat_pos_vel.open(s_pos_vel, ios::out | ios::trunc); // Simulation for (int i = 0; i < a_para[4]; ++i) thermostat->propagate(); cout << "Warmlauf abgeschlossen" << endl; int index_print{ (int)(a_para[3] * 4E-1) }; int index_to_file{ (int)a_para[5] }; for (int i = 0; i < a_para[3]; i++) { if (!(i % index_to_file)) { dat_temp << i*a_para[2] << " " << poly.calculate_temp() << endl; dat_pos_vel << poly; } if (!(i % index_print)) { cout << i*a_para[2] << endl; cout << "Ekin: " << poly.update_ekin() << endl; cout << "T: " << poly.calculate_temp() << endl; } thermostat->propagate(); } delete thermostat; cout << "<< Die Datei '" << s_temp << "' wurde erstellt." << endl; cout << "<< Die Datei '" << s_pos_vel << "' wurde erstellt." << endl; dat_temp.close(); dat_pos_vel.close(); return 0; } <commit_msg>NHC richtig initialisiert<commit_after>#include "Thermostat.h" #include "Nose_Hoover_Chain.h" #include "Andersen.h" #include "Lowe_Andersen.h" #include "Gaussian.h" #include "Nose_Hoover.h" #include "Thermostat_None.h" #include "Berendsen.h" #include "Bussi.h" #include "Functions.h" #include "consts.h" using namespace consts; #include <iostream> #include <fstream> #include <algorithm> #include <cmath> #include <string> #include <cstring> using namespace std; /* ######################### */ int main(int argc, char* argv[]) { //default für p,Temp,dtime,runs,warmlauf,ausgabe :jedes xte wird ausgegeben double a_para[]{4, 20, 1E-15, 1E6, 1E3, 1}; int i_para{ 1 }; string s_para{}, s_therm{}; string s_temp{}, s_pos_vel{}; ofstream dat_temp{}, dat_pos_vel{}; Thermostat *thermostat{}; // Bestimmen der Parameter zur Initialisierung von Poly und Thermostat for (i_para = 1; i_para < min(7, argc); ++i_para) { if (is_number(argv[i_para])) a_para[i_para - 1] = stod(argv[i_para]); else break; } a_para[2] /= ref_time; while (i_para < argc - 1 && is_number(argv[i_para])) ++i_para; int i_thermos = i_para; while (++i_para < argc - 1 && is_number(argv[i_para])) ++i_para; int i_poly_init = min(argc - 1, i_para); Polymer poly{ static_cast<unsigned> (a_para[0]), a_para[1] }; if (strcmp(argv[i_poly_init], "one") == 0) poly.initiate_monomers_one(); else poly.initiate_monomers_random(); // Auswählen des Thermostats if (argc > 1 && i_thermos < argc) { if (strcmp(argv[i_thermos], "Andersen") == 0) { double nu{ set_param(1. / a_para[2] / a_para[0], argv, argc, i_thermos + 1) }; thermostat = new Andersen{ poly, a_para[2], nu }; s_therm = "Andersen"; } else if (strcmp(argv[i_thermos], "Lowe_Andersen") == 0) { double nu{ set_param(1. / a_para[2] / a_para[0], argv, argc, i_thermos + 1) }; thermostat = new Lowe_Andersen{ poly, a_para[2], nu }; s_therm = "Lowe_Andersen"; } else if (strcmp(argv[i_thermos], "Gaussian") == 0) { thermostat = new Gaussian{ poly, a_para[2] }; s_therm = "Gaussian"; } else if (strcmp(argv[i_thermos], "Nose_Hoover") == 0) { double q_def{ poly.monomers.size()*poly.target_temperature()*ref_time / 1E-12 }; double q{ set_param(q_def, argv, argc, i_thermos + 1) }; thermostat = new Nose_Hoover{ poly, a_para[2], q }; s_therm = "Nose_Hoover"; } else if (strcmp(argv[i_thermos], "Nose_Hoover_Chain") == 0) { double q_def{ poly.monomer_mass*poly.target_temperature()/poly.feder_konst() }; double q{ set_param(q_def * poly.monomers.size() , argv, argc, i_thermos + 1) }; double q2{ set_param( q_def , argv, argc, i_thermos + 2 ) }; thermostat = new Nose_Hoover_Chain{ poly, a_para[2], q, q2 }; s_therm = "Nose_Hoover_Chain"; } else if (strcmp(argv[i_thermos], "Berendsen") == 0) { double couplingtime = 10 * a_para[2]; thermostat = new Berendsen{ poly, a_para[2], couplingtime }; s_therm = "Berendsen"; } else if (strcmp(argv[i_thermos], "Bussi") == 0) { double couplingtime = 10 * a_para[2]; thermostat = new Bussi{ poly, a_para[2], couplingtime }; s_therm = "Bussi"; } else { thermostat = new Thermostat_None{ poly, a_para[2] }; s_therm = "None"; } } else { thermostat = new Thermostat_None{ poly, a_para[2] }; s_therm = "None"; } cout << "Thermostat:\t" << s_therm << endl; s_para = "_p"; s_para += to_string((int)a_para[0]); s_para += "_T"; s_para += to_string((int)a_para[1]); s_temp = s_therm + "_temp" + s_para + ".dat"; dat_temp.open(s_temp, ios::out | ios::trunc); s_pos_vel = s_therm + "_pos_vel" + s_para + ".dat"; dat_pos_vel.open(s_pos_vel, ios::out | ios::trunc); // Simulation for (int i = 0; i < a_para[4]; ++i) thermostat->propagate(); cout << "Warmlauf abgeschlossen" << endl; int index_print{ (int)(a_para[3] * 4E-1) }; int index_to_file{ (int)a_para[5] }; for (int i = 0; i < a_para[3]; i++) { if (!(i % index_to_file)) { dat_temp << i*a_para[2] << " " << poly.calculate_temp() << endl; dat_pos_vel << poly; } if (!(i % index_print)) { cout << i*a_para[2] << endl; cout << "Ekin: " << poly.update_ekin() << endl; cout << "T: " << poly.calculate_temp() << endl; } thermostat->propagate(); } delete thermostat; cout << "<< Die Datei '" << s_temp << "' wurde erstellt." << endl; cout << "<< Die Datei '" << s_pos_vel << "' wurde erstellt." << endl; dat_temp.close(); dat_pos_vel.close(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2007, 2008, 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/platform/graphics/Font.h" #include "core/platform/NotImplemented.h" #include "core/platform/graphics/FloatRect.h" #include "core/platform/graphics/GlyphBuffer.h" #include "core/platform/graphics/GraphicsContext.h" #include "core/platform/graphics/SimpleFontData.h" #include "core/platform/graphics/harfbuzz/HarfBuzzShaper.h" #include "SkPaint.h" #include "SkTemplates.h" #include "wtf/unicode/Unicode.h" namespace WebCore { bool Font::canReturnFallbackFontsForComplexText() { return false; } bool Font::canExpandAroundIdeographsInComplexText() { return false; } void Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font, const GlyphBuffer& glyphBuffer, int from, int numGlyphs, const FloatPoint& point, const FloatRect& textRect) const { SkASSERT(sizeof(GlyphBufferGlyph) == sizeof(uint16_t)); // compile-time assert const GlyphBufferGlyph* glyphs = glyphBuffer.glyphs(from); SkScalar x = SkFloatToScalar(point.x()); SkScalar y = SkFloatToScalar(point.y()); // FIXME: text rendering speed: // Android has code in their WebCore fork to special case when the // GlyphBuffer has no advances other than the defaults. In that case the // text drawing can proceed faster. However, it's unclear when those // patches may be upstreamed to WebKit so we always use the slower path // here. const GlyphBufferAdvance* adv = glyphBuffer.advances(from); SkAutoSTMalloc<32, SkPoint> storage(numGlyphs), storage2(numGlyphs), storage3(numGlyphs); SkPoint* pos = storage.get(); SkPoint* vPosBegin = storage2.get(); SkPoint* vPosEnd = storage3.get(); bool isVertical = font->platformData().orientation() == Vertical; for (int i = 0; i < numGlyphs; i++) { SkScalar myWidth = SkFloatToScalar(adv[i].width()); pos[i].set(x, y); if (isVertical) { vPosBegin[i].set(x + myWidth, y); vPosEnd[i].set(x + myWidth, y - myWidth); } x += myWidth; y += SkFloatToScalar(adv[i].height()); } TextDrawingModeFlags textMode = gc->textDrawingMode(); // We draw text up to two times (once for fill, once for stroke). if (textMode & TextModeFill) { SkPaint paint; gc->setupPaintForFilling(&paint); font->platformData().setupPaint(&paint); gc->adjustTextRenderMode(&paint); paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding); if (isVertical) { SkPath path; for (int i = 0; i < numGlyphs; ++i) { path.reset(); path.moveTo(vPosBegin[i]); path.lineTo(vPosEnd[i]); gc->drawTextOnPath(glyphs + i, 2, path, textRect, 0, paint); } } else gc->drawPosText(glyphs, numGlyphs << 1, pos, textRect, paint); } if ((textMode & TextModeStroke) && gc->strokeStyle() != NoStroke && gc->strokeThickness() > 0) { SkPaint paint; gc->setupPaintForStroking(&paint); font->platformData().setupPaint(&paint); gc->adjustTextRenderMode(&paint); paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding); if (textMode & TextModeFill) { // If we also filled, we don't want to draw shadows twice. // See comment in FontChromiumWin.cpp::paintSkiaText() for more details. // Since we use the looper for shadows, we remove it (if any) now. paint.setLooper(0); } if (isVertical) { SkPath path; for (int i = 0; i < numGlyphs; ++i) { path.reset(); path.moveTo(vPosBegin[i]); path.lineTo(vPosEnd[i]); gc->drawTextOnPath(glyphs + i, 2, path, textRect, 0, paint); } } else gc->drawPosText(glyphs, numGlyphs << 1, pos, textRect, paint); } } static void setupForTextPainting(SkPaint* paint, SkColor color) { paint->setTextEncoding(SkPaint::kGlyphID_TextEncoding); paint->setColor(color); } void Font::drawComplexText(GraphicsContext* gc, const TextRunPaintInfo& runInfo, const FloatPoint& point) const { if (!runInfo.run.length()) return; TextDrawingModeFlags textMode = gc->textDrawingMode(); bool fill = textMode & TextModeFill; bool stroke = (textMode & TextModeStroke) && gc->strokeStyle() != NoStroke && gc->strokeThickness() > 0; if (!fill && !stroke) return; SkPaint strokePaint, fillPaint; if (fill) { gc->setupPaintForFilling(&fillPaint); setupForTextPainting(&fillPaint, gc->fillColor().rgb()); } if (stroke) { gc->setupPaintForStroking(&strokePaint); setupForTextPainting(&strokePaint, gc->strokeColor().rgb()); } GlyphBuffer glyphBuffer; HarfBuzzShaper shaper(this, runInfo.run); shaper.setDrawRange(runInfo.from, runInfo.to); if (!shaper.shape(&glyphBuffer)) return; FloatPoint adjustedPoint = shaper.adjustStartPoint(point); drawGlyphBuffer(gc, runInfo, glyphBuffer, adjustedPoint); } void Font::drawEmphasisMarksForComplexText(GraphicsContext* /* context */, const TextRunPaintInfo& /* runInfo */, const AtomicString& /* mark */, const FloatPoint& /* point */) const { notImplemented(); } float Font::floatWidthForComplexText(const TextRun& run, HashSet<const SimpleFontData*>* /* fallbackFonts */, GlyphOverflow* /* glyphOverflow */) const { HarfBuzzShaper shaper(this, run); if (!shaper.shape()) return 0; return shaper.totalWidth(); } // Return the code point index for the given |x| offset into the text run. int Font::offsetForPositionForComplexText(const TextRun& run, float xFloat, bool includePartialGlyphs) const { HarfBuzzShaper shaper(this, run); if (!shaper.shape()) return 0; return shaper.offsetForPosition(xFloat); } // Return the rectangle for selecting the given range of code-points in the TextRun. FloatRect Font::selectionRectForComplexText(const TextRun& run, const FloatPoint& point, int height, int from, int to) const { HarfBuzzShaper shaper(this, run); if (!shaper.shape()) return FloatRect(); return shaper.selectionRect(point, height, from, to); } } // namespace WebCore <commit_msg>Remove dead code from FontHarfBuzz.<commit_after>/* * Copyright (c) 2007, 2008, 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/platform/graphics/Font.h" #include "core/platform/NotImplemented.h" #include "core/platform/graphics/FloatRect.h" #include "core/platform/graphics/GlyphBuffer.h" #include "core/platform/graphics/GraphicsContext.h" #include "core/platform/graphics/SimpleFontData.h" #include "core/platform/graphics/harfbuzz/HarfBuzzShaper.h" #include "SkPaint.h" #include "SkTemplates.h" #include "wtf/unicode/Unicode.h" namespace WebCore { bool Font::canReturnFallbackFontsForComplexText() { return false; } bool Font::canExpandAroundIdeographsInComplexText() { return false; } void Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font, const GlyphBuffer& glyphBuffer, int from, int numGlyphs, const FloatPoint& point, const FloatRect& textRect) const { SkASSERT(sizeof(GlyphBufferGlyph) == sizeof(uint16_t)); // compile-time assert const GlyphBufferGlyph* glyphs = glyphBuffer.glyphs(from); SkScalar x = SkFloatToScalar(point.x()); SkScalar y = SkFloatToScalar(point.y()); // FIXME: text rendering speed: // Android has code in their WebCore fork to special case when the // GlyphBuffer has no advances other than the defaults. In that case the // text drawing can proceed faster. However, it's unclear when those // patches may be upstreamed to WebKit so we always use the slower path // here. const GlyphBufferAdvance* adv = glyphBuffer.advances(from); SkAutoSTMalloc<32, SkPoint> storage(numGlyphs), storage2(numGlyphs), storage3(numGlyphs); SkPoint* pos = storage.get(); SkPoint* vPosBegin = storage2.get(); SkPoint* vPosEnd = storage3.get(); bool isVertical = font->platformData().orientation() == Vertical; for (int i = 0; i < numGlyphs; i++) { SkScalar myWidth = SkFloatToScalar(adv[i].width()); pos[i].set(x, y); if (isVertical) { vPosBegin[i].set(x + myWidth, y); vPosEnd[i].set(x + myWidth, y - myWidth); } x += myWidth; y += SkFloatToScalar(adv[i].height()); } TextDrawingModeFlags textMode = gc->textDrawingMode(); // We draw text up to two times (once for fill, once for stroke). if (textMode & TextModeFill) { SkPaint paint; gc->setupPaintForFilling(&paint); font->platformData().setupPaint(&paint); gc->adjustTextRenderMode(&paint); paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding); if (isVertical) { SkPath path; for (int i = 0; i < numGlyphs; ++i) { path.reset(); path.moveTo(vPosBegin[i]); path.lineTo(vPosEnd[i]); gc->drawTextOnPath(glyphs + i, 2, path, textRect, 0, paint); } } else gc->drawPosText(glyphs, numGlyphs << 1, pos, textRect, paint); } if ((textMode & TextModeStroke) && gc->strokeStyle() != NoStroke && gc->strokeThickness() > 0) { SkPaint paint; gc->setupPaintForStroking(&paint); font->platformData().setupPaint(&paint); gc->adjustTextRenderMode(&paint); paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding); if (textMode & TextModeFill) { // If we also filled, we don't want to draw shadows twice. // See comment in FontChromiumWin.cpp::paintSkiaText() for more details. // Since we use the looper for shadows, we remove it (if any) now. paint.setLooper(0); } if (isVertical) { SkPath path; for (int i = 0; i < numGlyphs; ++i) { path.reset(); path.moveTo(vPosBegin[i]); path.lineTo(vPosEnd[i]); gc->drawTextOnPath(glyphs + i, 2, path, textRect, 0, paint); } } else gc->drawPosText(glyphs, numGlyphs << 1, pos, textRect, paint); } } void Font::drawComplexText(GraphicsContext* gc, const TextRunPaintInfo& runInfo, const FloatPoint& point) const { if (!runInfo.run.length()) return; TextDrawingModeFlags textMode = gc->textDrawingMode(); bool fill = textMode & TextModeFill; bool stroke = (textMode & TextModeStroke) && gc->strokeStyle() != NoStroke && gc->strokeThickness() > 0; if (!fill && !stroke) return; GlyphBuffer glyphBuffer; HarfBuzzShaper shaper(this, runInfo.run); shaper.setDrawRange(runInfo.from, runInfo.to); if (!shaper.shape(&glyphBuffer)) return; FloatPoint adjustedPoint = shaper.adjustStartPoint(point); drawGlyphBuffer(gc, runInfo, glyphBuffer, adjustedPoint); } void Font::drawEmphasisMarksForComplexText(GraphicsContext* /* context */, const TextRunPaintInfo& /* runInfo */, const AtomicString& /* mark */, const FloatPoint& /* point */) const { notImplemented(); } float Font::floatWidthForComplexText(const TextRun& run, HashSet<const SimpleFontData*>* /* fallbackFonts */, GlyphOverflow* /* glyphOverflow */) const { HarfBuzzShaper shaper(this, run); if (!shaper.shape()) return 0; return shaper.totalWidth(); } // Return the code point index for the given |x| offset into the text run. int Font::offsetForPositionForComplexText(const TextRun& run, float xFloat, bool includePartialGlyphs) const { HarfBuzzShaper shaper(this, run); if (!shaper.shape()) return 0; return shaper.offsetForPosition(xFloat); } // Return the rectangle for selecting the given range of code-points in the TextRun. FloatRect Font::selectionRectForComplexText(const TextRun& run, const FloatPoint& point, int height, int from, int to) const { HarfBuzzShaper shaper(this, run); if (!shaper.shape()) return FloatRect(); return shaper.selectionRect(point, height, from, to); } } // namespace WebCore <|endoftext|>
<commit_before>#include "codestring.h" #include "codevector.h" // splits a string into parts, by spl. Vector<String> strsplit(const String& str, const String& spl) { Vector<String> ret; String tmp = str; if (!spl) return ret; __SIZETYPE index; while (!!tmp) { index = tmp.indexOf(spl); if (index == -1) { ret.pushback(tmp); return ret; } ret.pushback(tmp.substr(0, index)); tmp = tmp.substr(index + spl.length()); } return ret; } // joins a vector of strings, concatenating join as a punctuator. String strjoin(Vector<String> vs, const String& join) { String ret; bool first = true; for (__SIZETYPE i = 0; i < vs.size(); i++) { if (first) { first = false; } else { ret += join; } ret += vs[i]; } return ret; }<commit_msg>slightly modify strsplit and join<commit_after>#include "codestring.h" #include "codevector.h" // forward declarations: Vector<String> strsplit(String, String); String strjoin(Vector<String>, String); /** Implementation **/ // splits a string into parts, by spl. Vector<String> strsplit(String str, String spl = "") { Vector<String> ret; if (!spl) { // splits it into single characters. for (__SIZETYPE i = 0; i < str.length(); i++) ret.pushback(str[i]); return ret; } __SIZETYPE index; while (!!str) { index = str.indexOf(spl); if (index == -1) { ret.pushback(str); return ret; } ret.pushback(str.substr(0, index)); str = str.substr(index + spl.length()); } return ret; } // joins a vector of strings, concatenating join as a punctuator. String strjoin(Vector<String> vs, String join = "") { String ret; bool first = true; for (__SIZETYPE i = 0; i < vs.size(); i++) { if (first) { first = false; } else { ret += join; } ret += vs[i]; } return ret; }<|endoftext|>
<commit_before>#include <hydra/component/particlecomponent.hpp> #include <hydra/engine.hpp> #include <imgui/imgui.h> #include <hydra/component/cameracomponent.hpp> #include <algorithm> #define frand() (float(rand()) / float(RAND_MAX)) using namespace Hydra::World; using namespace Hydra::Component; ParticleComponent::~ParticleComponent() {} void ParticleComponent::serialize(nlohmann::json & json) const{ json["delay"] = delay; json["accumulator"] = accumulator; json["behaviour"] = static_cast<int>(behaviour); json["texture"] = static_cast<int>(texture); } void ParticleComponent::deserialize(nlohmann::json & json){ delay = json.value<float>("delay", 0); accumulator = json.value<int>("accumulator", 0); behaviour = static_cast<EmitterBehaviour>(json["behaviour"].get<int>()); texture = static_cast<ParticleTexture>(json["texture"].get<int>()); } void ParticleComponent::registerUI() { float pps = (int)(1.0f / delay); if (ImGui::DragFloat("Particles/Second", &pps)) { pps = std::max(0.0f, pps); delay = 1.0f / pps; } ImGui::InputFloat("Delay between particles", &delay, 0, 0, -1, ImGuiInputTextFlags_ReadOnly); ImGui::DragFloat("Accumulator", &accumulator, 1.0); ImGui::Combo("Emitter Behaviour", reinterpret_cast<int*>(&behaviour), EmitterBehaviourStr, static_cast<int>(EmitterBehaviour::MAX_COUNT)); ImGui::Combo("Particle Texture", reinterpret_cast<int*>(&texture), ParticleTextureStr, static_cast<int>(ParticleTexture::MAX_COUNT)); if (!ImGui::CollapsingHeader("Particles")) return; int i = -1; for (auto& p : particles) { i++; ImGui::PushID((void*)&p); ImGui::Text("Particle #%d", i); ImGui::SameLine(); if (ImGui::Button("Edit")) ImGui::OpenPopup((std::string("particle") + std::to_string(i)).c_str()); if (ImGui::BeginPopup((std::string("particle") + std::to_string(i)).c_str())) { ImGui::Text("Editing Particle #%d", i); p.transform.registerUI(); ImGui::Text("Velocity"); ImGui::DragFloat3("##velocity", glm::value_ptr(p.velocity)); ImGui::Text("Acceleration"); ImGui::DragFloat3("##acceleration", glm::value_ptr(p.acceleration)); ImGui::Text("Life"); ImGui::DragFloat("##life", &p.life); ImGui::Text("Start Life"); ImGui::DragFloat("##startlife", &p.startLife); if (ImGui::Button("Close")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } ImGui::NextColumn(); ImGui::PopID(); } } void ParticleComponent::spawnParticles() { using world = Hydra::World::World; auto t = world::getEntity(entityID)->getComponent<Hydra::Component::TransformComponent>(); auto findFree = [this]() -> Particle* { static size_t orgI = 0; size_t i = orgI; do { if (particles[i].life <= 0) { orgI = (i+1) % MaxParticleAmount; return &particles[i]; } i = (i + 1) % MaxParticleAmount; } while (i != orgI); return nullptr; }; switch (behaviour) { case EmitterBehaviour::PerSecond: while (accumulator >= delay) { Particle* p = findFree(); if (!p) break; accumulator -= delay; const float velX = frand() * 2 - 2; const float velY = frand() * 6 - 1; const float velZ = frand() * 2 - 2; const float accX = frand() * 2 - 2; const float accY = frand() * 8.5f; const float accZ = frand() * 2 - 2; const float life = frand() + 1.f; const glm::vec3 vel = glm::normalize(glm::vec3(velX, velY, velZ)); const glm::vec3 acc = glm::vec3(accX, accY, accZ); p->respawn(*t, vel, acc, life); } break; case EmitterBehaviour::Explosion: while (accumulator >= delay) { Particle* p = findFree(); if (!p) break; accumulator -= delay; const float velX = (frand() * 6.0f - 3.0f) + optionalNormal.x; const float velY = (frand() * 6.0f - 2.0f) + optionalNormal.y; const float velZ = (frand() * 6.0f - 3.0f) + optionalNormal.z; const float accX = velX * 2.0f; const float accY = velY * 2.0f; const float accZ = velZ * 2.0f; const float life = 4.0f; const glm::vec3 vel = normalize(glm::vec3(velX, velY, velZ)); const glm::vec3 acc = glm::vec3(accX, accY, accZ); p->respawn(*t, vel, acc, life); } break; default: break; } } <commit_msg>trying to merge master<commit_after>#include <hydra/component/particlecomponent.hpp> #include <hydra/engine.hpp> #include <imgui/imgui.h> #include <hydra/component/cameracomponent.hpp> #include <algorithm> #define frand() (float(rand()) / float(RAND_MAX)) using namespace Hydra::World; using namespace Hydra::Component; ParticleComponent::~ParticleComponent() {} void ParticleComponent::serialize(nlohmann::json & json) const{ json["delay"] = delay; json["accumulator"] = accumulator; json["behaviour"] = static_cast<int>(behaviour); json["texture"] = static_cast<int>(texture); } void ParticleComponent::deserialize(nlohmann::json & json){ // teast delay = json.value<float>("delay", 0); accumulator = json.value<int>("accumulator", 0); behaviour = static_cast<EmitterBehaviour>(json["behaviour"].get<int>()); texture = static_cast<ParticleTexture>(json["texture"].get<int>()); } void ParticleComponent::registerUI() { float pps = (int)(1.0f / delay); if (ImGui::DragFloat("Particles/Second", &pps)) { pps = std::max(0.0f, pps); delay = 1.0f / pps; } ImGui::InputFloat("Delay between particles", &delay, 0, 0, -1, ImGuiInputTextFlags_ReadOnly); ImGui::DragFloat("Accumulator", &accumulator, 1.0); ImGui::Combo("Emitter Behaviour", reinterpret_cast<int*>(&behaviour), EmitterBehaviourStr, static_cast<int>(EmitterBehaviour::MAX_COUNT)); ImGui::Combo("Particle Texture", reinterpret_cast<int*>(&texture), ParticleTextureStr, static_cast<int>(ParticleTexture::MAX_COUNT)); if (!ImGui::CollapsingHeader("Particles")) return; int i = -1; for (auto& p : particles) { i++; ImGui::PushID((void*)&p); ImGui::Text("Particle #%d", i); ImGui::SameLine(); if (ImGui::Button("Edit")) ImGui::OpenPopup((std::string("particle") + std::to_string(i)).c_str()); if (ImGui::BeginPopup((std::string("particle") + std::to_string(i)).c_str())) { ImGui::Text("Editing Particle #%d", i); p.transform.registerUI(); ImGui::Text("Velocity"); ImGui::DragFloat3("##velocity", glm::value_ptr(p.velocity)); ImGui::Text("Acceleration"); ImGui::DragFloat3("##acceleration", glm::value_ptr(p.acceleration)); ImGui::Text("Life"); ImGui::DragFloat("##life", &p.life); ImGui::Text("Start Life"); ImGui::DragFloat("##startlife", &p.startLife); if (ImGui::Button("Close")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } ImGui::NextColumn(); ImGui::PopID(); } } void ParticleComponent::spawnParticles() { using world = Hydra::World::World; auto t = world::getEntity(entityID)->getComponent<Hydra::Component::TransformComponent>(); auto findFree = [this]() -> Particle* { static size_t orgI = 0; size_t i = orgI; do { if (particles[i].life <= 0) { orgI = (i+1) % MaxParticleAmount; return &particles[i]; } i = (i + 1) % MaxParticleAmount; } while (i != orgI); return nullptr; }; switch (behaviour) { case EmitterBehaviour::PerSecond: while (accumulator >= delay) { Particle* p = findFree(); if (!p) break; accumulator -= delay; const float velX = frand() * 2 - 2; const float velY = frand() * 6 - 1; const float velZ = frand() * 2 - 2; const float accX = frand() * 2 - 2; const float accY = frand() * 8.5f; const float accZ = frand() * 2 - 2; const float life = frand() + 1.f; const glm::vec3 vel = glm::normalize(glm::vec3(velX, velY, velZ)); const glm::vec3 acc = glm::vec3(accX, accY, accZ); p->respawn(*t, vel, acc, life); } break; case EmitterBehaviour::Explosion: while (accumulator >= delay) { Particle* p = findFree(); if (!p) break; accumulator -= delay; const float velX = (frand() * 6.0f - 3.0f) + optionalNormal.x; const float velY = (frand() * 6.0f - 2.0f) + optionalNormal.y; const float velZ = (frand() * 6.0f - 3.0f) + optionalNormal.z; const float accX = velX * 2.0f; const float accY = velY * 2.0f; const float accZ = velZ * 2.0f; const float life = 4.0f; const glm::vec3 vel = normalize(glm::vec3(velX, velY, velZ)); const glm::vec3 acc = glm::vec3(accX, accY, accZ); p->respawn(*t, vel, acc, life); } break; default: break; } } <|endoftext|>
<commit_before>#include <stdio.h> #include "pthread.h" #include <atomic> #include <stdlib.h> #ifndef XV6_USER #include <string.h> #else #include "types.h" #include "user.h" #endif #include "mtrace.h" #include "fstest.h" #ifndef XV6_USER #include <stdlib.h> #include <sched.h> int setaffinity(int cpu) { cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(cpu, &mask); return sched_setaffinity(0, sizeof(mask), &mask); } #endif static bool verbose = false; static bool check_commutativity = false; static std::atomic<int> waiters; static std::atomic<int> ready; static void* callthread(void* arg) { int (*callf)(void) = (int (*)(void)) arg; waiters++; while (ready.load() == 0) ; callf(); waiters--; while (ready.load() == 1) ; return 0; } int main(int ac, char** av) { setaffinity(0); int max = 0; if (ac > 1) max = atoi(av[1]); for (int i = 0; (max == 0 || i < max) && fstests[i].setup; i++) { if (check_commutativity) { fstests[i].setup(); int ra0 = fstests[i].call0(); int ra1 = fstests[i].call1(); fstests[i].cleanup(); fstests[i].setup(); int rb1 = fstests[i].call1(); int rb0 = fstests[i].call0(); fstests[i].cleanup(); if (ra0 == rb0 && ra1 == rb1) { if (verbose) printf("test %d: commutes: %s->%d %s->%d\n", i, fstests[i].call0name, ra0, fstests[i].call1name, ra1); } else { printf("test %d: diverges: %s->%d %s->%d vs %s->%d %s->%d\n", i, fstests[i].call0name, ra0, fstests[i].call1name, ra1, fstests[i].call0name, rb0, fstests[i].call1name, rb1); } } fstests[i].setup(); waiters = 0; ready = 0; pthread_t tid0, tid1; setaffinity(0); pthread_create(&tid0, 0, callthread, (void*) fstests[i].call0); setaffinity(1); pthread_create(&tid1, 0, callthread, (void*) fstests[i].call1); setaffinity(0); while (waiters.load() != 2) ; char mtname[64]; snprintf(mtname, sizeof(mtname), "fstest-%d", i); #ifdef XV6_USER mtenable_type(mtrace_record_ascope, mtname); #else mtenable_type(mtrace_record_kernelscope, mtname); #endif ready = 1; while (waiters.load() != 0) ; mtdisable(mtname); ready = 2; pthread_join(tid0, 0); pthread_join(tid1, 0); fstests[i].cleanup(); printf("test %d completed threads\n", i); } } <commit_msg>add a check_threads flag to fstest<commit_after>#include <stdio.h> #include "pthread.h" #include <atomic> #include <stdlib.h> #ifndef XV6_USER #include <string.h> #else #include "types.h" #include "user.h" #endif #include "mtrace.h" #include "fstest.h" #ifndef XV6_USER #include <stdlib.h> #include <sched.h> int setaffinity(int cpu) { cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(cpu, &mask); return sched_setaffinity(0, sizeof(mask), &mask); } #endif static bool verbose = false; static bool check_commutativity = false; static bool check_threads = true; static std::atomic<int> waiters; static std::atomic<int> ready; static void* callthread(void* arg) { int (*callf)(void) = (int (*)(void)) arg; waiters++; while (ready.load() == 0) ; callf(); waiters--; while (ready.load() == 1) ; return 0; } int main(int ac, char** av) { setaffinity(0); int max = 0; if (ac > 1) max = atoi(av[1]); for (int i = 0; (max == 0 || i < max) && fstests[i].setup; i++) { if (check_commutativity) { fstests[i].setup(); int ra0 = fstests[i].call0(); int ra1 = fstests[i].call1(); fstests[i].cleanup(); fstests[i].setup(); int rb1 = fstests[i].call1(); int rb0 = fstests[i].call0(); fstests[i].cleanup(); if (ra0 == rb0 && ra1 == rb1) { if (verbose) printf("test %d: commutes: %s->%d %s->%d\n", i, fstests[i].call0name, ra0, fstests[i].call1name, ra1); } else { printf("test %d: diverges: %s->%d %s->%d vs %s->%d %s->%d\n", i, fstests[i].call0name, ra0, fstests[i].call1name, ra1, fstests[i].call0name, rb0, fstests[i].call1name, rb1); } } if (!check_threads) continue; fstests[i].setup(); waiters = 0; ready = 0; pthread_t tid0, tid1; setaffinity(0); pthread_create(&tid0, 0, callthread, (void*) fstests[i].call0); setaffinity(1); pthread_create(&tid1, 0, callthread, (void*) fstests[i].call1); setaffinity(0); while (waiters.load() != 2) ; char mtname[64]; snprintf(mtname, sizeof(mtname), "fstest-%d", i); #ifdef XV6_USER mtenable_type(mtrace_record_ascope, mtname); #else mtenable_type(mtrace_record_kernelscope, mtname); #endif ready = 1; while (waiters.load() != 0) ; mtdisable(mtname); ready = 2; pthread_join(tid0, 0); pthread_join(tid1, 0); fstests[i].cleanup(); printf("test %d completed threads\n", i); } } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "echomesh/audio/EnvelopeValuePlayer.h" namespace echomesh { TEST(EnvelopeValuePlayer, Base) { EnvelopeValue ev; ev.isConstant = true; ev.value = 23.0; EnvelopeValuePlayer player(ev); ASSERT_TRUE(player.isConstant()); } } // namespace echomesh <commit_msg>Convert to text fixture.<commit_after>#include <gtest/gtest.h> #include "echomesh/audio/EnvelopeValuePlayer.h" namespace echomesh { namespace { class EnvelopeValuePlayerTest : public ::testing::Test { public: EnvelopeValuePlayerTest() {} protected: void make() { player_ = new EnvelopeValuePlayer(ev_); } EnvelopeValue ev_; ScopedPointer<EnvelopeValuePlayer> player_; }; } // namespace TEST_F(EnvelopeValuePlayerTest, Base) { make(); ASSERT_TRUE(player_->isConstant()); } } // namespace echomesh <|endoftext|>
<commit_before>// (C) Copyright Gennadiy Rozental 2005-2010. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : implements compiler like Log formatter // *************************************************************************** #ifndef BOOST_TEST_COMPILER_LOG_FORMATTER_IPP_020105GER #define BOOST_TEST_COMPILER_LOG_FORMATTER_IPP_020105GER // Boost.Test #include <boost/test/framework.hpp> #include <boost/test/execution_monitor.hpp> #include <boost/test/tree/test_unit.hpp> #include <boost/test/utils/basic_cstring/io.hpp> #include <boost/test/utils/lazy_ostream.hpp> #include <boost/test/utils/setcolor.hpp> #include <boost/test/output/compiler_log_formatter.hpp> #include <boost/test/unit_test_parameters.hpp> // Boost #include <boost/version.hpp> // STL #include <iostream> #include <boost/test/detail/suppress_warnings.hpp> //____________________________________________________________________________// namespace boost { namespace unit_test { namespace output { // ************************************************************************** // // ************** compiler_log_formatter ************** // // ************************************************************************** // namespace { const_string test_phase_identifier() { return framework::is_initialized() ? const_string( framework::current_test_case().p_name.get() ) : BOOST_TEST_L( "Test setup" ); } } // local namespace //____________________________________________________________________________// void compiler_log_formatter::log_start( std::ostream& output, counter_t test_cases_amount ) { if( test_cases_amount > 0 ) output << "Running " << test_cases_amount << " test " << (test_cases_amount > 1 ? "cases" : "case") << "...\n"; } //____________________________________________________________________________// void compiler_log_formatter::log_finish( std::ostream& ostr ) { ostr.flush(); } //____________________________________________________________________________// void compiler_log_formatter::log_build_info( std::ostream& output ) { output << "Platform: " << BOOST_PLATFORM << '\n' << "Compiler: " << BOOST_COMPILER << '\n' << "STL : " << BOOST_STDLIB << '\n' << "Boost : " << BOOST_VERSION/100000 << "." << BOOST_VERSION/100 % 1000 << "." << BOOST_VERSION % 100 << std::endl; } //____________________________________________________________________________// void compiler_log_formatter::test_unit_start( std::ostream& output, test_unit const& tu ) { BOOST_TEST_SCOPE_SETCOLOR( output, term_attr::BRIGHT, term_color::BLUE ); output << "Entering test " << tu.p_type_name << " \"" << tu.p_name << "\"" << std::endl; } //____________________________________________________________________________// void compiler_log_formatter::test_unit_finish( std::ostream& output, test_unit const& tu, unsigned long elapsed ) { BOOST_TEST_SCOPE_SETCOLOR( output, term_attr::BRIGHT, term_color::BLUE ); output << "Leaving test " << tu.p_type_name << " \"" << tu.p_name << "\""; if( elapsed > 0 ) { output << "; testing time: "; if( elapsed % 1000 == 0 ) output << elapsed/1000 << "ms"; else output << elapsed << "mks"; } output << std::endl; } //____________________________________________________________________________// void compiler_log_formatter::test_unit_skipped( std::ostream& output, test_unit const& tu ) { BOOST_TEST_SCOPE_SETCOLOR( output, term_attr::BRIGHT, term_color::YELLOW ); output << "Test " << tu.p_type_name << " \"" << tu.p_name << "\"" << "is skipped" << std::endl; } //____________________________________________________________________________// void compiler_log_formatter::log_exception_start( std::ostream& output, log_checkpoint_data const& checkpoint_data, execution_exception const& ex ) { execution_exception::location const& loc = ex.where(); print_prefix( output, loc.m_file_name, loc.m_line_num ); { BOOST_TEST_SCOPE_SETCOLOR( output, term_attr::BLINK, term_color::RED ); output << "fatal error in \"" << (loc.m_function.is_empty() ? test_phase_identifier() : loc.m_function ) << "\": " << ex.what(); } if( !checkpoint_data.m_file_name.is_empty() ) { output << '\n'; print_prefix( output, checkpoint_data.m_file_name, checkpoint_data.m_line_num ); BOOST_TEST_SCOPE_SETCOLOR( output, term_attr::BRIGHT, term_color::CYAN ); output << "last checkpoint"; if( !checkpoint_data.m_message.empty() ) output << ": " << checkpoint_data.m_message; } } //____________________________________________________________________________// void compiler_log_formatter::log_exception_finish( std::ostream& output ) { output << std::endl; } //____________________________________________________________________________// void compiler_log_formatter::log_entry_start( std::ostream& output, log_entry_data const& entry_data, log_entry_types let ) { switch( let ) { case BOOST_UTL_ET_INFO: print_prefix( output, entry_data.m_file_name, entry_data.m_line_num ); if( runtime_config::color_output() ) output << setcolor( term_attr::BRIGHT, term_color::GREEN ); output << "info: "; break; case BOOST_UTL_ET_MESSAGE: if( runtime_config::color_output() ) output << setcolor( term_attr::BRIGHT, term_color::CYAN ); break; case BOOST_UTL_ET_WARNING: print_prefix( output, entry_data.m_file_name, entry_data.m_line_num ); if( runtime_config::color_output() ) output << setcolor( term_attr::BRIGHT, term_color::YELLOW ); output << "warning in \"" << test_phase_identifier() << "\": "; break; case BOOST_UTL_ET_ERROR: print_prefix( output, entry_data.m_file_name, entry_data.m_line_num ); if( runtime_config::color_output() ) output << setcolor( term_attr::BRIGHT, term_color::RED ); output << "error in \"" << test_phase_identifier() << "\": "; break; case BOOST_UTL_ET_FATAL_ERROR: print_prefix( output, entry_data.m_file_name, entry_data.m_line_num ); if( runtime_config::color_output() ) output << setcolor( term_attr::BLINK, term_color::RED ); output << "fatal error in \"" << test_phase_identifier() << "\": "; break; } } //____________________________________________________________________________// void compiler_log_formatter::log_entry_value( std::ostream& output, const_string value ) { output << value; } //____________________________________________________________________________// void compiler_log_formatter::log_entry_value( std::ostream& output, lazy_ostream const& value ) { output << value; } //____________________________________________________________________________// void compiler_log_formatter::log_entry_finish( std::ostream& output ) { if( runtime_config::color_output() ) output << setcolor(); output << std::endl; } //____________________________________________________________________________// void compiler_log_formatter::print_prefix( std::ostream& output, const_string file, std::size_t line ) { #ifdef __APPLE_CC__ // Xcode-compatible logging format, idea by Richard Dingwall at // <http://richarddingwall.name/2008/06/01/using-the-boost-unit-test-framework-with-xcode-3/>. output << file << ':' << line << ": "; #else output << file << '(' << line << "): "; #endif } //____________________________________________________________________________// void compiler_log_formatter::entry_context_start( std::ostream& output ) { output << "\nFailure occurred in a following context:"; } //____________________________________________________________________________// void compiler_log_formatter::entry_context_finish( std::ostream& output ) { output.flush(); } //____________________________________________________________________________// void compiler_log_formatter::log_entry_context( std::ostream& output, const_string context_descr ) { output << "\n " << context_descr; } //____________________________________________________________________________// } // namespace output } // namespace unit_test } // namespace boost #include <boost/test/detail/enable_warnings.hpp> #endif // BOOST_TEST_COMPILER_LOG_FORMATTER_IPP_020105GER <commit_msg>Make Boost.Test error messages to appear in VC10 errors list Fixes #5374<commit_after>// (C) Copyright Gennadiy Rozental 2005-2010. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : implements compiler like Log formatter // *************************************************************************** #ifndef BOOST_TEST_COMPILER_LOG_FORMATTER_IPP_020105GER #define BOOST_TEST_COMPILER_LOG_FORMATTER_IPP_020105GER // Boost.Test #include <boost/test/framework.hpp> #include <boost/test/execution_monitor.hpp> #include <boost/test/tree/test_unit.hpp> #include <boost/test/utils/basic_cstring/io.hpp> #include <boost/test/utils/lazy_ostream.hpp> #include <boost/test/utils/setcolor.hpp> #include <boost/test/output/compiler_log_formatter.hpp> #include <boost/test/unit_test_parameters.hpp> // Boost #include <boost/version.hpp> // STL #include <iostream> #include <boost/test/detail/suppress_warnings.hpp> //____________________________________________________________________________// namespace boost { namespace unit_test { namespace output { // ************************************************************************** // // ************** compiler_log_formatter ************** // // ************************************************************************** // namespace { const_string test_phase_identifier() { return framework::is_initialized() ? const_string( framework::current_test_case().p_name.get() ) : BOOST_TEST_L( "Test setup" ); } } // local namespace //____________________________________________________________________________// void compiler_log_formatter::log_start( std::ostream& output, counter_t test_cases_amount ) { if( test_cases_amount > 0 ) output << "Running " << test_cases_amount << " test " << (test_cases_amount > 1 ? "cases" : "case") << "...\n"; } //____________________________________________________________________________// void compiler_log_formatter::log_finish( std::ostream& ostr ) { ostr.flush(); } //____________________________________________________________________________// void compiler_log_formatter::log_build_info( std::ostream& output ) { output << "Platform: " << BOOST_PLATFORM << '\n' << "Compiler: " << BOOST_COMPILER << '\n' << "STL : " << BOOST_STDLIB << '\n' << "Boost : " << BOOST_VERSION/100000 << "." << BOOST_VERSION/100 % 1000 << "." << BOOST_VERSION % 100 << std::endl; } //____________________________________________________________________________// void compiler_log_formatter::test_unit_start( std::ostream& output, test_unit const& tu ) { BOOST_TEST_SCOPE_SETCOLOR( output, term_attr::BRIGHT, term_color::BLUE ); output << "Entering test " << tu.p_type_name << " \"" << tu.p_name << "\"" << std::endl; } //____________________________________________________________________________// void compiler_log_formatter::test_unit_finish( std::ostream& output, test_unit const& tu, unsigned long elapsed ) { BOOST_TEST_SCOPE_SETCOLOR( output, term_attr::BRIGHT, term_color::BLUE ); output << "Leaving test " << tu.p_type_name << " \"" << tu.p_name << "\""; if( elapsed > 0 ) { output << "; testing time: "; if( elapsed % 1000 == 0 ) output << elapsed/1000 << "ms"; else output << elapsed << "mks"; } output << std::endl; } //____________________________________________________________________________// void compiler_log_formatter::test_unit_skipped( std::ostream& output, test_unit const& tu ) { BOOST_TEST_SCOPE_SETCOLOR( output, term_attr::BRIGHT, term_color::YELLOW ); output << "Test " << tu.p_type_name << " \"" << tu.p_name << "\"" << "is skipped" << std::endl; } //____________________________________________________________________________// void compiler_log_formatter::log_exception_start( std::ostream& output, log_checkpoint_data const& checkpoint_data, execution_exception const& ex ) { execution_exception::location const& loc = ex.where(); print_prefix( output, loc.m_file_name, loc.m_line_num ); { BOOST_TEST_SCOPE_SETCOLOR( output, term_attr::BLINK, term_color::RED ); output << "fatal error in \"" << (loc.m_function.is_empty() ? test_phase_identifier() : loc.m_function ) << "\": " << ex.what(); } if( !checkpoint_data.m_file_name.is_empty() ) { output << '\n'; print_prefix( output, checkpoint_data.m_file_name, checkpoint_data.m_line_num ); BOOST_TEST_SCOPE_SETCOLOR( output, term_attr::BRIGHT, term_color::CYAN ); output << "last checkpoint"; if( !checkpoint_data.m_message.empty() ) output << ": " << checkpoint_data.m_message; } } //____________________________________________________________________________// void compiler_log_formatter::log_exception_finish( std::ostream& output ) { output << std::endl; } //____________________________________________________________________________// void compiler_log_formatter::log_entry_start( std::ostream& output, log_entry_data const& entry_data, log_entry_types let ) { switch( let ) { case BOOST_UTL_ET_INFO: print_prefix( output, entry_data.m_file_name, entry_data.m_line_num ); if( runtime_config::color_output() ) output << setcolor( term_attr::BRIGHT, term_color::GREEN ); output << "info: "; break; case BOOST_UTL_ET_MESSAGE: if( runtime_config::color_output() ) output << setcolor( term_attr::BRIGHT, term_color::CYAN ); break; case BOOST_UTL_ET_WARNING: print_prefix( output, entry_data.m_file_name, entry_data.m_line_num ); if( runtime_config::color_output() ) output << setcolor( term_attr::BRIGHT, term_color::YELLOW ); output << "warning: in \"" << test_phase_identifier() << "\": "; break; case BOOST_UTL_ET_ERROR: print_prefix( output, entry_data.m_file_name, entry_data.m_line_num ); if( runtime_config::color_output() ) output << setcolor( term_attr::BRIGHT, term_color::RED ); output << "error: in \"" << test_phase_identifier() << "\": "; break; case BOOST_UTL_ET_FATAL_ERROR: print_prefix( output, entry_data.m_file_name, entry_data.m_line_num ); if( runtime_config::color_output() ) output << setcolor( term_attr::BLINK, term_color::RED ); output << "fatal error: in \"" << test_phase_identifier() << "\": "; break; } } //____________________________________________________________________________// void compiler_log_formatter::log_entry_value( std::ostream& output, const_string value ) { output << value; } //____________________________________________________________________________// void compiler_log_formatter::log_entry_value( std::ostream& output, lazy_ostream const& value ) { output << value; } //____________________________________________________________________________// void compiler_log_formatter::log_entry_finish( std::ostream& output ) { if( runtime_config::color_output() ) output << setcolor(); output << std::endl; } //____________________________________________________________________________// void compiler_log_formatter::print_prefix( std::ostream& output, const_string file, std::size_t line ) { #ifdef __APPLE_CC__ // Xcode-compatible logging format, idea by Richard Dingwall at // <http://richarddingwall.name/2008/06/01/using-the-boost-unit-test-framework-with-xcode-3/>. output << file << ':' << line << ": "; #else output << file << '(' << line << "): "; #endif } //____________________________________________________________________________// void compiler_log_formatter::entry_context_start( std::ostream& output ) { output << "\nFailure occurred in a following context:"; } //____________________________________________________________________________// void compiler_log_formatter::entry_context_finish( std::ostream& output ) { output.flush(); } //____________________________________________________________________________// void compiler_log_formatter::log_entry_context( std::ostream& output, const_string context_descr ) { output << "\n " << context_descr; } //____________________________________________________________________________// } // namespace output } // namespace unit_test } // namespace boost #include <boost/test/detail/enable_warnings.hpp> #endif // BOOST_TEST_COMPILER_LOG_FORMATTER_IPP_020105GER <|endoftext|>
<commit_before>#ifndef COAPY_HPP #define COAPY_HPP #include <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_stl.hpp> #include <boost/spirit/include/phoenix_container.hpp> #include <boost/spirit/include/qi_uint.hpp> #include <boost/spirit/include/qi_eps.hpp> #include <frame_detail.hpp> namespace coapy { namespace qi = boost::spirit::qi; template <typename Iterator> bool coap_message_parser(Iterator first, Iterator last, coapy::coap_message &msg) { using qi::byte_; using qi::big_word; using qi::hex; using qi::eps; using boost::phoenix::ref; using boost::phoenix::push_back; using boost::phoenix::clear; using qi::_1; using qi::parse; using qi::repeat; namespace phnx = boost::phoenix; uint8_t coap_header = 0; uint8_t coap_code = 0; uint8_t option_header = 0; uint32_t delta = 0; uint8_t option_delta_length = 0; coapy::coap_option option{}; bool r = parse(first, last, ( //header version:2-type:2-tag length:4 byte_[ref(coap_header) = _1] //code:8 >> byte_[ref(coap_code) = _1] //message id:16 >> big_word[ref(msg.message_id) = _1] //token:0-8 (here 0-15) >> repeat((ref(coap_header) & 0b00001111))[byte_[push_back(phnx::ref(msg.token),_1)]] //options >> *( //option header:8 byte_[ref(option_header) = _1] >> ( ( eps(ref(option_header) == 0xFF) >> +byte_[push_back(phnx::ref(msg.payload),_1)]) | ( eps(ref(delta) = (ref(option_header) >> 4 )) >> eps(ref(option_delta_length) = (ref(option_header) & 0b00001111)) //option optional delta >> ( ( eps(ref(delta) <= 12) | (eps(ref(delta) == 13) >> byte_[ref(delta) += _1]) | (eps(ref(delta) == 14) >> big_word[ref(delta) = (_1 + 255)]) //can overflow ) >> eps[ref(option.number) += ref(delta)] //internal >> eps[clear(phnx::ref(option.values))] ) //option optional value length >> ( (eps(ref(option_delta_length) <= 12) | (eps(ref(option_delta_length) == 13) >> byte_[ref(option_delta_length) += _1]) | (eps(ref(option_delta_length) == 14) >> big_word[ref(option_delta_length) = (_1 + 255)]) //can overflow ) //option value >> repeat(ref(option_delta_length))[byte_[push_back(phnx::ref(option.values),_1)]] ) //adding option to option list >> eps[push_back(phnx::ref(msg.options),phnx::ref(option))] ) ) ) )); msg.version = (coap_header & 0b11000000) >> 6; msg.type = (coap_header & 0b00110000) >> 4; msg.code_class = (coap_code & 0b11100000) >> 5; msg.code_detail = (coap_code & 0b00011111); return r; }; } #endif <commit_msg>BUGFIX: when delta was zero, option was ignored<commit_after>#ifndef COAPY_HPP #define COAPY_HPP #include <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_stl.hpp> #include <boost/spirit/include/phoenix_container.hpp> #include <boost/spirit/include/qi_uint.hpp> #include <boost/spirit/include/qi_eps.hpp> #include <frame_detail.hpp> namespace coapy { namespace qi = boost::spirit::qi; template <typename Iterator> bool coap_message_parser(Iterator first, Iterator last, coapy::coap_message &msg) { using qi::byte_; using qi::big_word; using qi::hex; using qi::eps; using boost::phoenix::ref; using boost::phoenix::push_back; using boost::phoenix::clear; using qi::_1; using qi::parse; using qi::repeat; namespace phnx = boost::phoenix; uint8_t coap_header = 0; uint8_t coap_code = 0; uint8_t option_header = 0; uint32_t delta = 0; uint8_t option_delta_length = 0; coapy::coap_option option{}; bool r = parse(first, last, ( //header version:2-type:2-tag length:4 byte_[ref(coap_header) = _1] //code:8 >> byte_[ref(coap_code) = _1] //message id:16 >> big_word[ref(msg.message_id) = _1] //token:0-8 (here 0-15) >> repeat((ref(coap_header) & 0b00001111))[byte_[push_back(phnx::ref(msg.token),_1)]] //options >> *( //option header:8 byte_[ref(option_header) = _1] >> ( ( eps(ref(option_header) == 0xFF) >> +byte_[push_back(phnx::ref(msg.payload),_1)]) | ( eps[ref(delta) = (ref(option_header) >> 4 )] >> eps(ref(option_delta_length) = (ref(option_header) & 0b00001111)) //option optional delta >> ( ( eps(ref(delta) <= 12) | (eps(ref(delta) == 13) >> byte_[ref(delta) += _1]) | (eps(ref(delta) == 14) >> big_word[ref(delta) = (_1 + 255)]) //can overflow ) >> eps[ref(option.number) += ref(delta)] //internal >> eps[clear(phnx::ref(option.values))] ) //option optional value length >> ( (eps(ref(option_delta_length) <= 12) | (eps(ref(option_delta_length) == 13) >> byte_[ref(option_delta_length) += _1]) | (eps(ref(option_delta_length) == 14) >> big_word[ref(option_delta_length) = (_1 + 255)]) //can overflow ) //option value >> repeat(ref(option_delta_length))[byte_[push_back(phnx::ref(option.values),_1)]] ) //adding option to option list >> eps[push_back(phnx::ref(msg.options),phnx::ref(option))] ) ) ) )); msg.version = (coap_header & 0b11000000) >> 6; msg.type = (coap_header & 0b00110000) >> 4; msg.code_class = (coap_code & 0b11100000) >> 5; msg.code_detail = (coap_code & 0b00011111); return r; }; } #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: LegendHelper.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-09-17 13:25:08 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "LegendHelper.hxx" #include "macros.hxx" #ifndef _COM_SUN_STAR_CHART2_XCHARTDOCUMENT_HPP_ #include <com/sun/star/chart2/XChartDocument.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XLEGEND_HPP_ #include <com/sun/star/chart2/XLegend.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif using namespace ::com::sun::star; //............................................................................. namespace chart { //............................................................................. // static rtl::OUString LegendHelper::getIdentifierForLegend() { static rtl::OUString aIdentifier( C2U( "@legend" ) ); return aIdentifier; } // static uno::Reference< chart2::XLegend > LegendHelper::getLegend( const uno::Reference< frame::XModel >& xModel ) { uno::Reference< chart2::XLegend > xResult; uno::Reference< chart2::XChartDocument > xChartDoc( xModel, uno::UNO_QUERY ); if( xChartDoc.is()) { try { uno::Reference< chart2::XDiagram > xDia( xChartDoc->getDiagram()); if( xDia.is()) xResult.set( xDia->getLegend() ); } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } } return xResult; } // static void LegendHelper::defaultFillEmptyLegend( const uno::Reference< chart2::XLegend > & xLegend, const uno::Reference< chart2::XDiagram > & xDiagram ) { if( xLegend.is() && xDiagram.is() ) { try { uno::Reference< chart2::XDataSeriesTreeParent > xRoot( xDiagram->getTree()); uno::Sequence< uno::Reference< chart2::XDataSeriesTreeNode > > aChildren( xRoot->getChildren()); for( sal_Int32 i = 0; i < aChildren.getLength(); ++i ) { uno::Reference< lang::XServiceInfo > xInfo( aChildren[ i ], uno::UNO_QUERY ); if( xInfo.is() && xInfo->supportsService( C2U( "com.sun.star.chart2.ChartTypeGroup" ))) { uno::Reference< chart2::XLegendEntry > xEntry( xInfo, uno::UNO_QUERY ); if( xEntry.is()) xLegend->registerEntry( xEntry ); } } } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } } } // static void LegendHelper::flushLegend( const uno::Reference< chart2::XLegend > & xLegend ) { if( xLegend.is()) { uno::Sequence< uno::Reference< chart2::XLegendEntry > > aEntries( xLegend->getEntries()); for( sal_Int32 i = 0; i < aEntries.getLength(); ++i ) { xLegend->revokeEntry( aEntries[ i ] ); } } } //............................................................................. } //namespace chart //............................................................................. <commit_msg>INTEGRATION: CWS chart2mst3 (1.5.4); FILE MERGED 2006/10/18 17:16:57 bm 1.5.4.7: RESYNC: (1.6-1.7); FILE MERGED 2006/10/16 15:38:16 bm 1.5.4.6: #i70287# +hasLegend (used by toolbar toggle legend command) 2005/12/21 21:29:27 iha 1.5.4.5: remove identifiers from model objects and create an index based CID protocol instead for selection purposes 2005/10/07 12:09:02 bm 1.5.4.4: RESYNC: (1.5-1.6); FILE MERGED 2005/08/18 15:20:44 bm 1.5.4.3: (gs)etDiagram -> (gs)etFirstDiagram to avoid name clashes with old API 2005/06/16 12:53:14 iha 1.5.4.2: create legend on demand 2004/09/16 14:43:28 iha 1.5.4.1: implement api redesign<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: LegendHelper.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: vg $ $Date: 2007-05-22 19:00:28 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "LegendHelper.hxx" #include "macros.hxx" #ifndef _COM_SUN_STAR_CHART2_XCHARTDOCUMENT_HPP_ #include <com/sun/star/chart2/XChartDocument.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XLEGEND_HPP_ #include <com/sun/star/chart2/XLegend.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif using namespace ::com::sun::star; //............................................................................. namespace chart { //............................................................................. // static uno::Reference< chart2::XLegend > LegendHelper::getLegend( const uno::Reference< frame::XModel >& xModel , const uno::Reference< uno::XComponentContext >& xContext , bool bCreate ) { uno::Reference< chart2::XLegend > xResult; uno::Reference< chart2::XChartDocument > xChartDoc( xModel, uno::UNO_QUERY ); if( xChartDoc.is()) { try { uno::Reference< chart2::XDiagram > xDia( xChartDoc->getFirstDiagram()); if( xDia.is() ) { xResult.set( xDia->getLegend() ); if( bCreate && !xResult.is() && xContext.is() ) { xResult.set( xContext->getServiceManager()->createInstanceWithContext( C2U( "com.sun.star.chart2.Legend" ), xContext ), uno::UNO_QUERY ); xDia->setLegend( xResult ); } } else if(bCreate) { DBG_ERROR("need diagram for creation of legend"); } } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } } return xResult; } // static bool LegendHelper::hasLegend( const uno::Reference< chart2::XDiagram > & xDiagram ) { bool bReturn = false; if( xDiagram.is()) { uno::Reference< beans::XPropertySet > xLegendProp( xDiagram->getLegend(), uno::UNO_QUERY ); if( xLegendProp.is()) xLegendProp->getPropertyValue( C2U("Show")) >>= bReturn; } return bReturn; } //............................................................................. } //namespace chart //............................................................................. <|endoftext|>
<commit_before>//===========================================================================// // Copyright (C) Microsoft Corporation. All rights reserved. // //===========================================================================// //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // #pragma once #ifndef _MLRTRIANGLELIGHTING_HPP_ #define _MLRTRIANGLELIGHTING_HPP_ void CLASSNAME::Lighting(MLRLight* const* lights, int32_t nrLights) { Check_Object(this); // //---------------------------------------------------------------------- // If no lights or normals are specified, use the original vertex colors //---------------------------------------------------------------------- // actualColors = &colors; int32_t state_mask = GetCurrentState().GetLightingMode(void); if (nrLights == 0 || normals.GetLength() == 0 || state_mask == MLRState::LightingOffMode) return; Check_Pointer(lights); // //------------------------------- // See if we need vertex lighting //------------------------------- // if (state_mask & MLRState::VertexLightingMode) { Start_Timer(Vertex_Light_Time); Verify(colors.GetLength() == litColors.GetLength()); Verify(normals.GetLength() == colors.GetLength()); Verify(coords.GetLength() == colors.GetLength()); int32_t i, k, len = colors.GetLength(void); MLRVertexData vertexData; #if COLOR_AS_DWORD TO_DO; #else RGBAColor *color = &colors[0]; #endif // //-------------------------------- // Now light the array of vertices //-------------------------------- // vertexData.point = &coords[0]; vertexData.color = &litColors[0]; vertexData.normal = &normals[0]; for(k=0;k<len;k++) { if(visibleIndexedVertices[k] != 0) { vertexData.color->red = 0.0f; vertexData.color->green = 0.0f; vertexData.color->blue = 0.0f; vertexData.color->alpha = color->alpha; for (i=0;i<nrLights;i++) { MLRLight *light = lights[i]; Check_Object(light); int32_t mask = state_mask & light->GetLightMask(void); if (!mask) continue; if (mask&MLRState::VertexLightingMode) { if ( GetCurrentState().GetBackFaceMode() != MLRState::BackFaceOffMode || light->GetLightType() == MLRLight::AmbientLight ) { light->LightVertex(vertexData); Set_Statistic(LitVertices, LitVertices+1); } } } vertexData.color->red *= color->red; vertexData.color->green *= color->green; vertexData.color->blue *= color->blue; vertexData.color->alpha *= color->alpha; } vertexData.point++; vertexData.color++; vertexData.normal++; color++; } actualColors = &litColors; Stop_Timer(Vertex_Light_Time); } if (state_mask & MLRState::LightMapLightingMode) { Start_Timer(LightMap_Light_Time); int32_t i; for (i=0;i<nrLights;i++) { MLRLight *light = lights[i]; Check_Object(light); MLRLightMap *lm = light->GetLightMap(void); if(lm==NULL) { continue; } // Verify(state.GetAlphaMode() == MLRState::OneZeroMode); int32_t mask = state_mask & light->GetLightMask(void); if (!mask) continue; if (mask & MLRState::LightMapLightingMode) { LightMapLighting(lights[i]); } } Stop_Timer(LightMap_Light_Time); } } #endif <commit_msg>minimised dependencies, normalise type, layout and warnings. Replaced NULL with nullptr<commit_after>//===========================================================================// // Copyright (C) Microsoft Corporation. All rights reserved. // //===========================================================================// //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // #pragma once #ifndef _MLRTRIANGLELIGHTING_HPP_ #define _MLRTRIANGLELIGHTING_HPP_ void CLASSNAME::Lighting(MLRLight* const* lights, int32_t nrLights) { Check_Object(this); // //---------------------------------------------------------------------- // If no lights or normals are specified, use the original vertex colors //---------------------------------------------------------------------- // actualColors = &colors; int32_t state_mask = GetCurrentState().GetLightingMode(void); if (nrLights == 0 || normals.GetLength() == 0 || state_mask == MLRState::LightingOffMode) return; Check_Pointer(lights); // //------------------------------- // See if we need vertex lighting //------------------------------- // if (state_mask & MLRState::VertexLightingMode) { Start_Timer(Vertex_Light_Time); Verify(colors.GetLength() == litColors.GetLength()); Verify(normals.GetLength() == colors.GetLength()); Verify(coords.GetLength() == colors.GetLength()); int32_t i, k, len = colors.GetLength(void); MLRVertexData vertexData; #if COLOR_AS_DWORD TO_DO; #else RGBAColor *color = &colors[0]; #endif // //-------------------------------- // Now light the array of vertices //-------------------------------- // vertexData.point = &coords[0]; vertexData.color = &litColors[0]; vertexData.normal = &normals[0]; for(k=0;k<len;k++) { if(visibleIndexedVertices[k] != 0) { vertexData.color->red = 0.0f; vertexData.color->green = 0.0f; vertexData.color->blue = 0.0f; vertexData.color->alpha = color->alpha; for (i=0;i<nrLights;i++) { MLRLight *light = lights[i]; Check_Object(light); int32_t mask = state_mask & light->GetLightMask(void); if (!mask) continue; if (mask&MLRState::VertexLightingMode) { if ( GetCurrentState().GetBackFaceMode() != MLRState::BackFaceOffMode || light->GetLightType() == MLRLight::AmbientLight ) { light->LightVertex(vertexData); Set_Statistic(LitVertices, LitVertices+1); } } } vertexData.color->red *= color->red; vertexData.color->green *= color->green; vertexData.color->blue *= color->blue; vertexData.color->alpha *= color->alpha; } vertexData.point++; vertexData.color++; vertexData.normal++; color++; } actualColors = &litColors; Stop_Timer(Vertex_Light_Time); } if (state_mask & MLRState::LightMapLightingMode) { Start_Timer(LightMap_Light_Time); int32_t i; for (i=0;i<nrLights;i++) { MLRLight *light = lights[i]; Check_Object(light); MLRLightMap *lm = light->GetLightMap(void); if(lm==nullptr) { continue; } // Verify(state.GetAlphaMode() == MLRState::OneZeroMode); int32_t mask = state_mask & light->GetLightMask(void); if (!mask) continue; if (mask & MLRState::LightMapLightingMode) { LightMapLighting(lights[i]); } } Stop_Timer(LightMap_Light_Time); } } #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAcosImageFilter.h" #include "itkAdaptImageFilter.h" #include "itkAddImageFilter.h" #include "itkAnisotropicDiffusionEquation.h" #include "itkAnisotropicDiffusionImageFilter.h" #include "itkAsinImageFilter.h" #include "itkAtan2ImageFilter.h" #include "itkAtanImageFilter.h" #include "itkBinaryDilateImageFilter.h" #include "itkBinaryErodeImageFilter.h" #include "itkBinaryFunctorImageFilter.h" #include "itkBinaryMagnitudeImageFilter.h" #include "itkBinaryMorphologicalDialationFilter.h" #include "itkBinaryMorphologicalErosionFilter.h" #include "itkBinaryMorphologicalFilterBase.h" #include "itkBinomialBlurImageFilter.h" #include "itkCastImageFilter.h" #include "itkConstantPadImageFilter.h" #include "itkCosImageFilter.h" #include "itkCurvature2DAnisotropicDiffusionEquation.h" #include "itkCurvatureAnisotropicDiffusionImageFilter.h" #include "itkCurvatureNDAnisotropicDiffusionEquation.h" #include "itkDanielssonDistanceMapImageFilter.h" #include "itkDerivativeImageFilter.h" #include "itkDifferenceOfGaussiansGradientImageFilter.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkEigenAnalysis2DImageFilter.h" #include "itkExpImageFilter.h" #include "itkExpandImageFilter.h" #include "itkExtractImageFilter.h" #include "itkFileIOToImageFilter.h" #include "itkFirstDerivativeRecursiveGaussianImageFilter.h" #include "itkGradient2DAnisotropicDiffusionEquation.h" #include "itkGradientAnisotropicDiffusionImageFilter.h" #include "itkGradientMagnitudeImageFilter.h" #include "itkGradientNDAnisotropicDiffusionEquation.h" #include "itkGradientRecursiveGaussianImageFilter.h" #include "itkGradientToMagnitudeImageFilter.h" #include "itkGrayscaleDilateImageFilter.h" #include "itkGrayscaleErodeImageFilter.h" #include "itkGrayscaleFunctionDilateImageFilter.h" #include "itkGrayscaleFunctionErodeImageFilter.h" #include "itkImageFileReader.h" #include "itkImageToMeshFilter.h" #include "itkImageToParametricSpaceFilter.h" #include "itkImageWriter.h" #include "itkImportImageFilter.h" #include "itkJoinImageFilter.h" #include "itkLog10ImageFilter.h" #include "itkLogImageFilter.h" #include "itkMeshSource.h" #include "itkMeshToMeshFilter.h" #include "itkMirrorPadImageFilter.h" #include "itkMorphologyImageFilter.h" #include "itkMultiplyImageFilter.h" #include "itkNaryAddImageFilter.h" #include "itkNaryFunctorImageFilter.h" #include "itkNeighborhoodOperatorImageFilter.h" #include "itkNonThreadedShrinkImageFilter.h" #include "itkPadImageFilter.h" #include "itkPlaheImageFilter.h" #include "itkRandomImageSource.h" #include "itkRawImageWriter.h" #include "itkRecursiveGaussianImageFilter.h" #include "itkRecursiveSeparableImageFilter.h" #include "itkReflectiveImageRegionIterator.h" #include "itkResampleImageFilter.h" #include "itkScalarAnisotropicDiffusionEquation.h" #include "itkSecondDerivativeRecursiveGaussianImageFilter.h" #include "itkShrinkImageFilter.h" #include "itkSinImageFilter.h" #include "itkSpatialFunctionImageEvaluatorFilter.h" #include "itkSqrtImageFilter.h" #include "itkStreamingImageFilter.h" #include "itkSubtractImageFilter.h" #include "itkTanImageFilter.h" #include "itkTernaryAddImageFilter.h" #include "itkTernaryFunctorImageFilter.h" #include "itkTernaryMagnitudeImageFilter.h" #include "itkTernaryMagnitudeSquaredImageFilter.h" #include "itkThresholdImageFilter.h" #include "itkTransformMeshFilter.h" #include "itkTwoOutputExampleImageFilter.h" #include "itkUnaryFunctorImageFilter.h" #include "itkVTKImageReader.h" #include "itkVTKImageWriter.h" #include "itkVectorAnisotropicDiffusionEquation.h" #include "itkVectorCastImageFilter.h" #include "itkVectorCurvature2DAnisotropicDiffusionEquation.h" #include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h" #include "itkVectorCurvatureNDAnisotropicDiffusionEquation.h" #include "itkVectorExpandImageFilter.h" #include "itkVectorGradient2DAnisotropicDiffusionEquation.h" #include "itkVectorGradientAnisotropicDiffusionImageFilter.h" #include "itkVectorGradientNDAnisotropicDiffusionEquation.h" #include "itkVectorNeighborhoodOperatorImageFilter.h" #include "itkWarpImageFilter.h" #include "itkWrapPadImageFilter.h" #include "itkWriter.h" int main ( int argc, char* argv ) { return 0; } <commit_msg>ENH:Moved MeshSource and MeshToMeshFilter to Common/<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAcosImageFilter.h" #include "itkAdaptImageFilter.h" #include "itkAddImageFilter.h" #include "itkAnisotropicDiffusionEquation.h" #include "itkAnisotropicDiffusionImageFilter.h" #include "itkAsinImageFilter.h" #include "itkAtan2ImageFilter.h" #include "itkAtanImageFilter.h" #include "itkBinaryDilateImageFilter.h" #include "itkBinaryErodeImageFilter.h" #include "itkBinaryFunctorImageFilter.h" #include "itkBinaryMagnitudeImageFilter.h" #include "itkBinaryMorphologicalDialationFilter.h" #include "itkBinaryMorphologicalErosionFilter.h" #include "itkBinaryMorphologicalFilterBase.h" #include "itkBinomialBlurImageFilter.h" #include "itkCastImageFilter.h" #include "itkConstantPadImageFilter.h" #include "itkCosImageFilter.h" #include "itkCurvature2DAnisotropicDiffusionEquation.h" #include "itkCurvatureAnisotropicDiffusionImageFilter.h" #include "itkCurvatureNDAnisotropicDiffusionEquation.h" #include "itkDanielssonDistanceMapImageFilter.h" #include "itkDerivativeImageFilter.h" #include "itkDifferenceOfGaussiansGradientImageFilter.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkEigenAnalysis2DImageFilter.h" #include "itkExpImageFilter.h" #include "itkExpandImageFilter.h" #include "itkExtractImageFilter.h" #include "itkFileIOToImageFilter.h" #include "itkFirstDerivativeRecursiveGaussianImageFilter.h" #include "itkGradient2DAnisotropicDiffusionEquation.h" #include "itkGradientAnisotropicDiffusionImageFilter.h" #include "itkGradientMagnitudeImageFilter.h" #include "itkGradientNDAnisotropicDiffusionEquation.h" #include "itkGradientRecursiveGaussianImageFilter.h" #include "itkGradientToMagnitudeImageFilter.h" #include "itkGrayscaleDilateImageFilter.h" #include "itkGrayscaleErodeImageFilter.h" #include "itkGrayscaleFunctionDilateImageFilter.h" #include "itkGrayscaleFunctionErodeImageFilter.h" #include "itkImageFileReader.h" #include "itkImageToMeshFilter.h" #include "itkImageToParametricSpaceFilter.h" #include "itkImageWriter.h" #include "itkImportImageFilter.h" #include "itkJoinImageFilter.h" #include "itkLog10ImageFilter.h" #include "itkLogImageFilter.h" #include "itkMirrorPadImageFilter.h" #include "itkMorphologyImageFilter.h" #include "itkMultiplyImageFilter.h" #include "itkNaryAddImageFilter.h" #include "itkNaryFunctorImageFilter.h" #include "itkNeighborhoodOperatorImageFilter.h" #include "itkNonThreadedShrinkImageFilter.h" #include "itkPadImageFilter.h" #include "itkPlaheImageFilter.h" #include "itkRandomImageSource.h" #include "itkRawImageWriter.h" #include "itkRecursiveGaussianImageFilter.h" #include "itkRecursiveSeparableImageFilter.h" #include "itkReflectiveImageRegionIterator.h" #include "itkResampleImageFilter.h" #include "itkScalarAnisotropicDiffusionEquation.h" #include "itkSecondDerivativeRecursiveGaussianImageFilter.h" #include "itkShrinkImageFilter.h" #include "itkSinImageFilter.h" #include "itkSpatialFunctionImageEvaluatorFilter.h" #include "itkSqrtImageFilter.h" #include "itkStreamingImageFilter.h" #include "itkSubtractImageFilter.h" #include "itkTanImageFilter.h" #include "itkTernaryAddImageFilter.h" #include "itkTernaryFunctorImageFilter.h" #include "itkTernaryMagnitudeImageFilter.h" #include "itkTernaryMagnitudeSquaredImageFilter.h" #include "itkThresholdImageFilter.h" #include "itkTransformMeshFilter.h" #include "itkTwoOutputExampleImageFilter.h" #include "itkUnaryFunctorImageFilter.h" #include "itkVTKImageReader.h" #include "itkVTKImageWriter.h" #include "itkVectorAnisotropicDiffusionEquation.h" #include "itkVectorCastImageFilter.h" #include "itkVectorCurvature2DAnisotropicDiffusionEquation.h" #include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h" #include "itkVectorCurvatureNDAnisotropicDiffusionEquation.h" #include "itkVectorExpandImageFilter.h" #include "itkVectorGradient2DAnisotropicDiffusionEquation.h" #include "itkVectorGradientAnisotropicDiffusionImageFilter.h" #include "itkVectorGradientNDAnisotropicDiffusionEquation.h" #include "itkVectorNeighborhoodOperatorImageFilter.h" #include "itkWarpImageFilter.h" #include "itkWrapPadImageFilter.h" #include "itkWriter.h" int main ( int argc, char* argv ) { return 0; } <|endoftext|>
<commit_before>#include <e_line_judge/ball_detection.h> BallDetection::BallDetection(const cv::Scalar &lower_range, const cv::Scalar &upper_range, double radius_estimate) { hsv_min = lower_range; hsv_max = upper_range; radius_estimate_ = radius_estimate; std::cout << "Start detection system" << std::endl; } BallDetection::~BallDetection() { } bool BallDetection::detect_ball(const cv::Mat &image, cv::Point2i &ball_center, double &ball_radius, bool debug) { cv::Mat hsv_image; //vector for storing the detected circles std::vector<cv::Vec3f> circles; //convert image to HSV format cv::cvtColor(image, hsv_image, CV_BGR2HSV, 0); //orange color detection cv::inRange(hsv_image, hsv_min, hsv_max, hsv_image); if (debug) { cv::imshow("before blur", hsv_image); cv::waitKey(30); } //filter noise // cv::GaussianBlur(hsv_image, hsv_image, cv::Size(9, 9), 2, 2 ); cv::medianBlur(hsv_image, hsv_image,13); if (debug) { cv::imshow("blur", hsv_image); cv::waitKey(30); } //Apply the Hough Transform to find the circles cv::HoughCircles(hsv_image, circles, CV_HOUGH_GRADIENT, 2, hsv_image.rows/4, 100, 40, 20, 200); //Detect the largest circle double max_radius = 0.0; if(circles.size() == 0) { return false; } else { for(size_t i = 0; i < circles.size(); i++) { //getting x and y of the circle cv::Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); //getting the circle radius double radius = circles[i][2]; if(radius > max_radius) { max_radius = radius; ball_radius = radius; ball_center = center; } } return true; } } <commit_msg>decreasing minimum radius to detect from 20 to 5 pixels<commit_after>#include <e_line_judge/ball_detection.h> BallDetection::BallDetection(const cv::Scalar &lower_range, const cv::Scalar &upper_range, double radius_estimate) { hsv_min = lower_range; hsv_max = upper_range; radius_estimate_ = radius_estimate; std::cout << "Start detection system" << std::endl; } BallDetection::~BallDetection() { } bool BallDetection::detect_ball(const cv::Mat &image, cv::Point2i &ball_center, double &ball_radius, bool debug) { cv::Mat hsv_image; //vector for storing the detected circles std::vector<cv::Vec3f> circles; //convert image to HSV format cv::cvtColor(image, hsv_image, CV_BGR2HSV, 0); //orange color detection cv::inRange(hsv_image, hsv_min, hsv_max, hsv_image); if (debug) { cv::imshow("before blur", hsv_image); cv::waitKey(30); } //filter noise // cv::GaussianBlur(hsv_image, hsv_image, cv::Size(9, 9), 2, 2 ); cv::medianBlur(hsv_image, hsv_image,13); if (debug) { cv::imshow("blur", hsv_image); cv::waitKey(30); } //Apply the Hough Transform to find the circles cv::HoughCircles(hsv_image, circles, CV_HOUGH_GRADIENT, 2, hsv_image.rows/4, 100, 40, 5, 200); //Detect the largest circle double max_radius = 0.0; if(circles.size() == 0) { return false; } else { for(size_t i = 0; i < circles.size(); i++) { //getting x and y of the circle cv::Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); //getting the circle radius double radius = circles[i][2]; if(radius > max_radius) { max_radius = radius; ball_radius = radius; ball_center = center; } } return true; } } <|endoftext|>
<commit_before>/* * * Copyright (C) 2000 Frans Kaashoek ([email protected]) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * */ #include "chord.h" bool locationtable::doForeignRPC (rpc_program prog, unsigned long procno, void *in, void *out, chordID ID, aclnt_cb cb) { xdrproc_t inproc = prog.tbl[procno].xdr_arg; if (!inproc) return false; xdrsuio x (XDR_ENCODE); if (!inproc (x.xdrp (), const_cast<void *> (in))) { return false; } size_t marshalled_len = x.uio ()->resid (); char *marshalled_data = suio_flatten (x.uio ()); chord_RPC_arg farg; farg.dest = ID; farg.host_prog = prog.progno; farg.host_proc = procno; farg.marshalled_args.setsize (marshalled_len); memcpy (farg.marshalled_args.base (), marshalled_data, marshalled_len); delete marshalled_data; location *l = getlocation (ID); assert (l); ptr<aclnt> c = aclnt::alloc (l->x, chord_program_1); assert (c); chord_RPC_res *res = New chord_RPC_res (); c->call (CHORDPROC_HOSTRPC, &farg, res, wrap (this, &locationtable::doForeignRPC_cb, res, out, prog, procno, cb)); } void locationtable::doForeignRPC_cb (chord_RPC_res *res, void *out, rpc_program prog, int procno, aclnt_cb cb, clnt_stat err) { if ((err) || (res->status)) (*cb)(err); else { char *mRes = res->resok->marshalled_res.base (); size_t reslen = res->resok->marshalled_res.size (); xdrmem x (mRes, reslen, XDR_DECODE); xdrproc_t outproc = prog.tbl[procno].xdr_res; if (! outproc (x.xdrp (), out) ) { cb (RPC_CANTDECODERES); } else { cb (RPC_SUCCESS); } } delete res; } long locationtable::new_xid (svccb *sbp) { last_xid += 1; octbl.insert (last_xid, sbp); return last_xid; } void locationtable::reply (long xid, void *out, long outlen) { svccb **sbp = octbl[xid]; assert (sbp); chord_RPC_res res; res.set_status (CHORD_OK); res.resok->marshalled_res.setsize (outlen); memcpy (res.resok->marshalled_res.base (), out, outlen); (*sbp)->replyref (res); octbl.remove (xid); } void locationtable::doRPC (chordID &ID, rpc_program prog, int procno, ptr<void> in, void *out, aclnt_cb cb) { location *l = getlocation (ID); assert (l); assert (l->refcnt >= 0); touch_cachedlocs (l); if (l->x) { if (prog.progno == CHORD_PROGRAM) { ptr<aclnt> c = aclnt::alloc(l->x, prog); if (c == 0) { (*cb) (RPC_CANTSEND); delete_connections (l); } else { u_int64_t s = getnsec (); touch_connections (l); c->call (procno, in, out, wrap (mkref (this), &locationtable::doRPCcb, cb, l, s)); } } else doForeignRPC (prog, procno, in, out, ID, cb); } else { doRPC_cbstate *st = New doRPC_cbstate (prog, procno, in, out, cb, ID); l->connectlist.insert_tail (st); if (!l->connecting) { chord_connect(ID, wrap (mkref (this), &locationtable::dorpc_connect_cb, l)); } } } void locationtable::doRPCcb (aclnt_cb cb, location *l, u_int64_t s, clnt_stat err) { if (err) { nrpcfailed++; } else { u_int64_t lat = getnsec () - s; l->rpcdelay += lat; l->nrpc++; rpcdelay += lat; nrpc++; if (lat > l->maxdelay) l->maxdelay = lat; } // l->x = 0; (*cb) (err); } void locationtable::dorpc_connect_cb(location *l, ptr<axprt_stream> x) { assert(l); l->connecting = false; if (x == NULL) { warnx << "connect_cb: connect failed\n"; doRPC_cbstate *st, *st1; for (st = l->connectlist.first; st; st = st1) { st1 = l->connectlist.next (st); aclnt_cb cb = st->cb; (*cb) (RPC_FAILED); l->connectlist.remove(st); delete st; } // decrefcnt (l); return; } assert (l->refcnt >= 0); l->x = x; l->connecting = false; add_connections (l); nconnections++; // l->timeout_cb = delaycb (360, 0, wrap(this, &locationtable::timeout, l)); doRPC_cbstate *st, *st1; for (st = l->connectlist.first; st; st = st1) { if (st->progno.progno == CHORD_PROGRAM) { ptr<aclnt> c = aclnt::alloc (x, st->progno); c->call (st->procno, st->in, st->out, st->cb); } else { doForeignRPC (st->progno, st->procno, st->in, st->out, st->ID, st->cb); } st1 = l->connectlist.next (st); l->connectlist.remove(st); delete st; } } void locationtable::chord_connect(chordID ID, callback<void, ptr<axprt_stream> >::ref cb) { location *l = getlocation(ID); assert (l); assert (l->refcnt >= 0); l->connecting = true; // increfcnt (ID); ptr<struct timeval> start = new refcounted<struct timeval>(); gettimeofday(start, NULL); if (l->x) { (*cb)(l->x); } else { warnx << "tcpconnect: " << l->addr.hostname << " " << l->addr.port << "\n"; tcpconnect (l->addr.hostname, l->addr.port, wrap (mkref (this), &locationtable::connect_cb, cb)); } } void locationtable::connect_cb (callback<void, ptr<axprt_stream> >::ref cb, int fd) { if (fd < 0) { warn ("connect failed: %m\n"); (*cb)(NULL); } else { tcp_nodelay(fd); ptr<axprt_stream> x = axprt_stream::alloc(fd); (*cb)(x); } } void locationtable::add_connections (location *l) { assert (l->x); if (size_connections >= max_connections) { delete_connections (connections.first); } connections.insert_tail (l); size_connections++; } void locationtable::touch_connections (location *l) { assert (l->x); connections.remove (l); connections.insert_tail (l); } void locationtable::delete_connections (location *l) { assert (l); assert (!l->connecting); if (l->x) { warnx << "delete_connections: delete stream to " << l->n << "\n"; connections.remove (l); size_connections--; l->x = NULL; } } void locationtable::stats () { char buf[1024]; warnx << "LOCATION TABLE STATS: estimate # nodes " << nnodes << "\n"; warnx << "total # of RPCs: good " << nrpc << " failed " << nrpcfailed << "\n"; fprintf(stderr, " Average latency: %f\n", ((float) (rpcdelay/nrpc))); warnx << "total # of connections opened: " << nconnections << "\n"; warnx << " Per link avg. RPC latencies\n"; for (location *l = locs.first (); l ; l = locs.next (l)) { warnx << " link " << l->n << " : # RPCs: " << l->nrpc << "\n"; sprintf (buf, " Average latency: %f\n", ((float)(l->rpcdelay))/l->nrpc); warnx << buf; sprintf (buf, " Max latency: %qd\n", l->maxdelay); warnx << buf; } } <commit_msg>Let foreign RPC recover from connections that disappear due to failures.<commit_after>/* * * Copyright (C) 2000 Frans Kaashoek ([email protected]) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * */ #include "chord.h" bool locationtable::doForeignRPC (rpc_program prog, unsigned long procno, void *in, void *out, chordID ID, aclnt_cb cb) { xdrproc_t inproc = prog.tbl[procno].xdr_arg; if (!inproc) return false; xdrsuio x (XDR_ENCODE); if (!inproc (x.xdrp (), const_cast<void *> (in))) { return false; } size_t marshalled_len = x.uio ()->resid (); char *marshalled_data = suio_flatten (x.uio ()); chord_RPC_arg farg; farg.dest = ID; farg.host_prog = prog.progno; farg.host_proc = procno; farg.marshalled_args.setsize (marshalled_len); memcpy (farg.marshalled_args.base (), marshalled_data, marshalled_len); delete marshalled_data; location *l = getlocation (ID); assert (l); ptr<aclnt> c = aclnt::alloc (l->x, chord_program_1); if (c) { chord_RPC_res *res = New chord_RPC_res (); c->call (CHORDPROC_HOSTRPC, &farg, res, wrap (this, &locationtable::doForeignRPC_cb, res, out, prog, procno, cb)); } else { (*cb) (RPC_CANTSEND); delete_connections (l); } } void locationtable::doForeignRPC_cb (chord_RPC_res *res, void *out, rpc_program prog, int procno, aclnt_cb cb, clnt_stat err) { if ((err) || (res->status)) (*cb)(err); else { char *mRes = res->resok->marshalled_res.base (); size_t reslen = res->resok->marshalled_res.size (); xdrmem x (mRes, reslen, XDR_DECODE); xdrproc_t outproc = prog.tbl[procno].xdr_res; if (! outproc (x.xdrp (), out) ) { cb (RPC_CANTDECODERES); } else { cb (RPC_SUCCESS); } } delete res; } long locationtable::new_xid (svccb *sbp) { last_xid += 1; octbl.insert (last_xid, sbp); return last_xid; } void locationtable::reply (long xid, void *out, long outlen) { svccb **sbp = octbl[xid]; assert (sbp); chord_RPC_res res; res.set_status (CHORD_OK); res.resok->marshalled_res.setsize (outlen); memcpy (res.resok->marshalled_res.base (), out, outlen); (*sbp)->replyref (res); octbl.remove (xid); } void locationtable::doRPC (chordID &ID, rpc_program prog, int procno, ptr<void> in, void *out, aclnt_cb cb) { location *l = getlocation (ID); assert (l); assert (l->refcnt >= 0); touch_cachedlocs (l); if (l->x) { if (prog.progno == CHORD_PROGRAM) { ptr<aclnt> c = aclnt::alloc(l->x, prog); if (c == 0) { (*cb) (RPC_CANTSEND); delete_connections (l); } else { u_int64_t s = getnsec (); touch_connections (l); c->call (procno, in, out, wrap (mkref (this), &locationtable::doRPCcb, cb, l, s)); } } else doForeignRPC (prog, procno, in, out, ID, cb); } else { doRPC_cbstate *st = New doRPC_cbstate (prog, procno, in, out, cb, ID); l->connectlist.insert_tail (st); if (!l->connecting) { chord_connect(ID, wrap (mkref (this), &locationtable::dorpc_connect_cb, l)); } } } void locationtable::doRPCcb (aclnt_cb cb, location *l, u_int64_t s, clnt_stat err) { if (err) { nrpcfailed++; } else { u_int64_t lat = getnsec () - s; l->rpcdelay += lat; l->nrpc++; rpcdelay += lat; nrpc++; if (lat > l->maxdelay) l->maxdelay = lat; } // l->x = 0; (*cb) (err); } void locationtable::dorpc_connect_cb(location *l, ptr<axprt_stream> x) { assert(l); l->connecting = false; if (x == NULL) { warnx << "connect_cb: connect failed\n"; doRPC_cbstate *st, *st1; for (st = l->connectlist.first; st; st = st1) { st1 = l->connectlist.next (st); aclnt_cb cb = st->cb; (*cb) (RPC_FAILED); l->connectlist.remove(st); delete st; } // decrefcnt (l); return; } assert (l->refcnt >= 0); l->x = x; l->connecting = false; add_connections (l); nconnections++; // l->timeout_cb = delaycb (360, 0, wrap(this, &locationtable::timeout, l)); doRPC_cbstate *st, *st1; for (st = l->connectlist.first; st; st = st1) { if (st->progno.progno == CHORD_PROGRAM) { ptr<aclnt> c = aclnt::alloc (x, st->progno); c->call (st->procno, st->in, st->out, st->cb); } else { doForeignRPC (st->progno, st->procno, st->in, st->out, st->ID, st->cb); } st1 = l->connectlist.next (st); l->connectlist.remove(st); delete st; } } void locationtable::chord_connect(chordID ID, callback<void, ptr<axprt_stream> >::ref cb) { location *l = getlocation(ID); assert (l); assert (l->refcnt >= 0); l->connecting = true; // increfcnt (ID); ptr<struct timeval> start = new refcounted<struct timeval>(); gettimeofday(start, NULL); if (l->x) { (*cb)(l->x); } else { warnx << "tcpconnect: " << l->addr.hostname << " " << l->addr.port << "\n"; tcpconnect (l->addr.hostname, l->addr.port, wrap (mkref (this), &locationtable::connect_cb, cb)); } } void locationtable::connect_cb (callback<void, ptr<axprt_stream> >::ref cb, int fd) { if (fd < 0) { warn ("connect failed: %m\n"); (*cb)(NULL); } else { tcp_nodelay(fd); ptr<axprt_stream> x = axprt_stream::alloc(fd); (*cb)(x); } } void locationtable::add_connections (location *l) { assert (l->x); if (size_connections >= max_connections) { delete_connections (connections.first); } connections.insert_tail (l); size_connections++; } void locationtable::touch_connections (location *l) { assert (l->x); connections.remove (l); connections.insert_tail (l); } void locationtable::delete_connections (location *l) { assert (l); assert (!l->connecting); if (l->x) { warnx << "delete_connections: delete stream to " << l->n << "\n"; connections.remove (l); size_connections--; l->x = NULL; } } void locationtable::stats () { char buf[1024]; warnx << "LOCATION TABLE STATS: estimate # nodes " << nnodes << "\n"; warnx << "total # of RPCs: good " << nrpc << " failed " << nrpcfailed << "\n"; fprintf(stderr, " Average latency: %f\n", ((float) (rpcdelay/nrpc))); warnx << "total # of connections opened: " << nconnections << "\n"; warnx << " Per link avg. RPC latencies\n"; for (location *l = locs.first (); l ; l = locs.next (l)) { warnx << " link " << l->n << " : # RPCs: " << l->nrpc << "\n"; sprintf (buf, " Average latency: %f\n", ((float)(l->rpcdelay))/l->nrpc); warnx << buf; sprintf (buf, " Max latency: %qd\n", l->maxdelay); warnx << buf; } } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 * * (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <sofa/simulation/common/DefaultAnimationLoop.h> #include <sofa/core/ObjectFactory.h> #include <sofa/simulation/common/PrintVisitor.h> #include <sofa/simulation/common/FindByTypeVisitor.h> #include <sofa/simulation/common/ExportGnuplotVisitor.h> #include <sofa/simulation/common/InitVisitor.h> #include <sofa/simulation/common/AnimateVisitor.h> #include <sofa/simulation/common/MechanicalVisitor.h> #include <sofa/simulation/common/CollisionVisitor.h> #include <sofa/simulation/common/CollisionBeginEvent.h> #include <sofa/simulation/common/CollisionEndEvent.h> #include <sofa/simulation/common/UpdateContextVisitor.h> #include <sofa/simulation/common/UpdateMappingVisitor.h> #include <sofa/simulation/common/ResetVisitor.h> #include <sofa/simulation/common/VisualVisitor.h> #include <sofa/simulation/common/ExportOBJVisitor.h> #include <sofa/simulation/common/WriteStateVisitor.h> #include <sofa/simulation/common/XMLPrintVisitor.h> #include <sofa/simulation/common/PropagateEventVisitor.h> #include <sofa/simulation/common/BehaviorUpdatePositionVisitor.h> #include <sofa/simulation/common/AnimateBeginEvent.h> #include <sofa/simulation/common/AnimateEndEvent.h> #include <sofa/simulation/common/UpdateMappingEndEvent.h> #include <sofa/simulation/common/CleanupVisitor.h> #include <sofa/simulation/common/DeleteVisitor.h> #include <sofa/simulation/common/UpdateBoundingBoxVisitor.h> #include <sofa/simulation/common/xml/NodeElement.h> #include <sofa/helper/system/SetDirectory.h> #include <sofa/helper/system/PipeProcess.h> #include <sofa/helper/AdvancedTimer.h> #include <sofa/core/visual/VisualParams.h> #include <stdlib.h> #include <math.h> #include <algorithm> namespace sofa { namespace simulation { SOFA_DECL_CLASS(DefaultAnimationLoop); int DefaultAnimationLoopClass = core::RegisterObject("The simplest master solver, created by default when user do not put on scene") .add< DefaultAnimationLoop >() ; DefaultAnimationLoop::DefaultAnimationLoop(simulation::Node* _gnode) : Inherit() , gnode(_gnode) { assert(gnode); } DefaultAnimationLoop::~DefaultAnimationLoop() { } void DefaultAnimationLoop::step(const core::ExecParams* params, double dt) { sofa::helper::AdvancedTimer::stepBegin("AnimationStep"); sofa::helper::AdvancedTimer::begin("Animate"); { AnimateBeginEvent ev ( dt ); PropagateEventVisitor act ( params, &ev ); gnode->execute ( act ); } //std::cout << "animate\n"; double startTime = gnode->getTime(); double mechanicalDt = dt/numMechSteps.getValue(); //double nextTime = gnode->getTime() + gnode->getDt(); // CHANGE to support AnimationStep : CollisionVisitor is now activated within AnimateVisitor //gnode->execute<CollisionVisitor>(params); AnimateVisitor act(params); act.setDt ( mechanicalDt ); BehaviorUpdatePositionVisitor beh(params , gnode->getDt()); for( unsigned i=0; i<numMechSteps.getValue(); i++ ) { gnode->execute ( beh ); gnode->execute ( act ); gnode->setTime ( startTime + (i+1)* act.getDt() ); gnode->execute<UpdateSimulationContextVisitor>(params); // propagate time nbMechSteps.setValue(nbMechSteps.getValue() + 1); } { AnimateEndEvent ev ( dt ); PropagateEventVisitor act ( params, &ev ); gnode->execute ( act ); } sofa::helper::AdvancedTimer::stepBegin("UpdateMapping"); //Visual Information update: Ray Pick add a MechanicalMapping used as VisualMapping gnode->execute<UpdateMappingVisitor>(params); sofa::helper::AdvancedTimer::step("UpdateMappingEndEvent"); { UpdateMappingEndEvent ev ( dt ); PropagateEventVisitor act ( params , &ev ); gnode->execute ( act ); } sofa::helper::AdvancedTimer::stepEnd("UpdateMapping"); #ifndef SOFA_NO_UPDATE_BBOX sofa::helper::AdvancedTimer::stepBegin("UpdateBBox"); gnode->execute<UpdateBoundingBoxVisitor>(params); sofa::helper::AdvancedTimer::stepEnd("UpdateBBox"); #endif #ifdef SOFA_DUMP_VISITOR_INFO simulation::Visitor::printCloseNode(std::string("Step")); #endif nbSteps.setValue(nbSteps.getValue() + 1); /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// sofa::helper::AdvancedTimer::end("Animate"); sofa::helper::AdvancedTimer::stepEnd("AnimationStep"); } } // namespace simulation } // namespace sofa <commit_msg>r11110/sofa-dev : FIX : DefaultAnimationLoop was not giving Root Node dt value in case of null dt coming from animation component. ADD : DefaultAnimationLoop code simplification : no more multiple mechanical steps in an animation step.<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 * * (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <sofa/simulation/common/DefaultAnimationLoop.h> #include <sofa/core/ObjectFactory.h> #include <sofa/simulation/common/PrintVisitor.h> #include <sofa/simulation/common/FindByTypeVisitor.h> #include <sofa/simulation/common/ExportGnuplotVisitor.h> #include <sofa/simulation/common/InitVisitor.h> #include <sofa/simulation/common/AnimateVisitor.h> #include <sofa/simulation/common/MechanicalVisitor.h> #include <sofa/simulation/common/CollisionVisitor.h> #include <sofa/simulation/common/CollisionBeginEvent.h> #include <sofa/simulation/common/CollisionEndEvent.h> #include <sofa/simulation/common/UpdateContextVisitor.h> #include <sofa/simulation/common/UpdateMappingVisitor.h> #include <sofa/simulation/common/ResetVisitor.h> #include <sofa/simulation/common/VisualVisitor.h> #include <sofa/simulation/common/ExportOBJVisitor.h> #include <sofa/simulation/common/WriteStateVisitor.h> #include <sofa/simulation/common/XMLPrintVisitor.h> #include <sofa/simulation/common/PropagateEventVisitor.h> #include <sofa/simulation/common/BehaviorUpdatePositionVisitor.h> #include <sofa/simulation/common/AnimateBeginEvent.h> #include <sofa/simulation/common/AnimateEndEvent.h> #include <sofa/simulation/common/UpdateMappingEndEvent.h> #include <sofa/simulation/common/CleanupVisitor.h> #include <sofa/simulation/common/DeleteVisitor.h> #include <sofa/simulation/common/UpdateBoundingBoxVisitor.h> #include <sofa/simulation/common/xml/NodeElement.h> #include <sofa/helper/system/SetDirectory.h> #include <sofa/helper/system/PipeProcess.h> #include <sofa/helper/AdvancedTimer.h> #include <sofa/core/visual/VisualParams.h> #include <stdlib.h> #include <math.h> #include <algorithm> namespace sofa { namespace simulation { SOFA_DECL_CLASS(DefaultAnimationLoop); int DefaultAnimationLoopClass = core::RegisterObject("The simplest master solver, created by default when user do not put on scene") .add< DefaultAnimationLoop >() ; DefaultAnimationLoop::DefaultAnimationLoop(simulation::Node* _gnode) : Inherit() , gnode(_gnode) { assert(gnode); } DefaultAnimationLoop::~DefaultAnimationLoop() { } void DefaultAnimationLoop::step(const core::ExecParams* params, double dt) { if (dt == 0) dt = this->gnode->getDt(); sofa::helper::AdvancedTimer::stepBegin("AnimationStep"); sofa::helper::AdvancedTimer::begin("Animate"); { AnimateBeginEvent ev ( dt ); PropagateEventVisitor act ( params, &ev ); gnode->execute ( act ); } double startTime = gnode->getTime(); BehaviorUpdatePositionVisitor beh(params , dt); gnode->execute ( beh ); AnimateVisitor act(params, dt); gnode->execute ( act ); gnode->setTime ( startTime + dt ); gnode->execute< UpdateSimulationContextVisitor >(params); { AnimateEndEvent ev ( dt ); PropagateEventVisitor act ( params, &ev ); gnode->execute ( act ); } sofa::helper::AdvancedTimer::stepBegin("UpdateMapping"); //Visual Information update: Ray Pick add a MechanicalMapping used as VisualMapping gnode->execute< UpdateMappingVisitor >(params); sofa::helper::AdvancedTimer::step("UpdateMappingEndEvent"); { UpdateMappingEndEvent ev ( dt ); PropagateEventVisitor act ( params , &ev ); gnode->execute ( act ); } sofa::helper::AdvancedTimer::stepEnd("UpdateMapping"); #ifndef SOFA_NO_UPDATE_BBOX sofa::helper::AdvancedTimer::stepBegin("UpdateBBox"); gnode->execute< UpdateBoundingBoxVisitor >(params); sofa::helper::AdvancedTimer::stepEnd("UpdateBBox"); #endif #ifdef SOFA_DUMP_VISITOR_INFO simulation::Visitor::printCloseNode(std::string("Step")); #endif nbSteps.setValue( nbSteps.getValue() + 1 ); /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// sofa::helper::AdvancedTimer::end("Animate"); sofa::helper::AdvancedTimer::stepEnd("AnimationStep"); } } // namespace simulation } // namespace sofa <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /*************************************************************************** * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ /** * * * * * TODO * - Add exception throwing when h == NULL * - Not init h when implicit constructor is launched */ #include <string.h> #include <sstream> #include <iostream> #include <libexttextcat/textcat.h> #include <libexttextcat/common.h> #include <libexttextcat/constants.h> #include <libexttextcat/fingerprint.h> #include <libexttextcat/utf8misc.h> #include <sal/types.h> #include "altstrfunc.hxx" #include "simpleguesser.hxx" #ifndef _UTF8_ #define _UTF8_ #endif using namespace std; /** * This 3 following structures are from fingerprint.c and textcat.c */ typedef struct ngram_t { sint2 rank; char str[MAXNGRAMSIZE+1]; } ngram_t; typedef struct fp_t { const char *name; ngram_t *fprint; uint4 size; } fp_t; typedef struct textcat_t{ void **fprint; char *fprint_disable; uint4 size; uint4 maxsize; char output[MAXOUTPUTSIZE]; } textcat_t; /** end of the 3 structs */ SimpleGuesser::SimpleGuesser() { h = NULL; } void SimpleGuesser::operator=(SimpleGuesser& sg){ if(h){textcat_Done(h);} h = sg.h; } SimpleGuesser::~SimpleGuesser() { if(h){textcat_Done(h);} } /*! \fn SimpleGuesser::GuessLanguage(char* text) */ vector<Guess> SimpleGuesser::GuessLanguage(const char* text) { vector<Guess> guesses; if (!h) return guesses; //calculate le number of unicode charcters (symbols) int len = utfstrlen(text); if (len > MAX_STRING_LENGTH_TO_ANALYSE) len = MAX_STRING_LENGTH_TO_ANALYSE; const char *guess_list = textcat_Classify(h, text, len); if (strcmp(guess_list, _TEXTCAT_RESULT_SHORT) == 0) return guesses; int current_pointer = 0; for(int i = 0; guess_list[current_pointer] != '\0'; i++) { while (guess_list[current_pointer] != GUESS_SEPARATOR_OPEN && guess_list[current_pointer] != '\0') current_pointer++; if(guess_list[current_pointer] != '\0') { Guess g(guess_list + current_pointer); guesses.push_back(g); current_pointer++; } } return guesses; } Guess SimpleGuesser::GuessPrimaryLanguage(const char* text) { vector<Guess> ret = GuessLanguage(text); return ret.empty() ? Guess() : ret[0]; } /** * Is used to know wich language is available, unavailable or both * when mask = 0xF0, return only Available * when mask = 0x0F, return only Unavailable * when mask = 0xFF, return both Available and Unavailable */ vector<Guess> SimpleGuesser::GetManagedLanguages(const char mask) { textcat_t *tables = (textcat_t*)h; vector<Guess> lang; if(!h){return lang;} for (size_t i=0; i<tables->size; ++i) { if (tables->fprint_disable[i] & mask) { string langStr = "["; langStr += fp_Name(tables->fprint[i]); Guess g(langStr.c_str()); lang.push_back(g); } } return lang; } vector<Guess> SimpleGuesser::GetAvailableLanguages() { return GetManagedLanguages( sal::static_int_cast< char >( 0xF0 ) ); } vector<Guess> SimpleGuesser::GetUnavailableLanguages() { return GetManagedLanguages( sal::static_int_cast< char >( 0x0F )); } vector<Guess> SimpleGuesser::GetAllManagedLanguages() { return GetManagedLanguages( sal::static_int_cast< char >( 0xFF )); } void SimpleGuesser::XableLanguage(string lang, char mask) { textcat_t *tables = (textcat_t*)h; if(!h){return;} for (size_t i=0; i<tables->size; i++) { string language(fp_Name(tables->fprint[i])); if (start(language,lang) == 0) tables->fprint_disable[i] = mask; } } void SimpleGuesser::EnableLanguage(string lang) { XableLanguage(lang, sal::static_int_cast< char >( 0xF0 )); } void SimpleGuesser::DisableLanguage(string lang) { XableLanguage(lang, sal::static_int_cast< char >( 0x0F )); } /** * */ void SimpleGuesser::SetDBPath(const char* path, const char* prefix) { if (h) textcat_Done(h); h = special_textcat_Init(path, prefix); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>this is supposed to just be the number of bytes<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /*************************************************************************** * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ /** * * * * * TODO * - Add exception throwing when h == NULL * - Not init h when implicit constructor is launched */ #include <string.h> #include <sstream> #include <iostream> #include <libexttextcat/textcat.h> #include <libexttextcat/common.h> #include <libexttextcat/constants.h> #include <libexttextcat/fingerprint.h> #include <libexttextcat/utf8misc.h> #include <sal/types.h> #include "altstrfunc.hxx" #include "simpleguesser.hxx" #ifndef _UTF8_ #define _UTF8_ #endif using namespace std; /** * This 3 following structures are from fingerprint.c and textcat.c */ typedef struct ngram_t { sint2 rank; char str[MAXNGRAMSIZE+1]; } ngram_t; typedef struct fp_t { const char *name; ngram_t *fprint; uint4 size; } fp_t; typedef struct textcat_t{ void **fprint; char *fprint_disable; uint4 size; uint4 maxsize; char output[MAXOUTPUTSIZE]; } textcat_t; /** end of the 3 structs */ SimpleGuesser::SimpleGuesser() { h = NULL; } void SimpleGuesser::operator=(SimpleGuesser& sg){ if(h){textcat_Done(h);} h = sg.h; } SimpleGuesser::~SimpleGuesser() { if(h){textcat_Done(h);} } /*! \fn SimpleGuesser::GuessLanguage(char* text) */ vector<Guess> SimpleGuesser::GuessLanguage(const char* text) { vector<Guess> guesses; if (!h) return guesses; int len = strlen(text); if (len > MAX_STRING_LENGTH_TO_ANALYSE) len = MAX_STRING_LENGTH_TO_ANALYSE; const char *guess_list = textcat_Classify(h, text, len); if (strcmp(guess_list, _TEXTCAT_RESULT_SHORT) == 0) return guesses; int current_pointer = 0; for(int i = 0; guess_list[current_pointer] != '\0'; i++) { while (guess_list[current_pointer] != GUESS_SEPARATOR_OPEN && guess_list[current_pointer] != '\0') current_pointer++; if(guess_list[current_pointer] != '\0') { Guess g(guess_list + current_pointer); guesses.push_back(g); current_pointer++; } } return guesses; } Guess SimpleGuesser::GuessPrimaryLanguage(const char* text) { vector<Guess> ret = GuessLanguage(text); return ret.empty() ? Guess() : ret[0]; } /** * Is used to know wich language is available, unavailable or both * when mask = 0xF0, return only Available * when mask = 0x0F, return only Unavailable * when mask = 0xFF, return both Available and Unavailable */ vector<Guess> SimpleGuesser::GetManagedLanguages(const char mask) { textcat_t *tables = (textcat_t*)h; vector<Guess> lang; if(!h){return lang;} for (size_t i=0; i<tables->size; ++i) { if (tables->fprint_disable[i] & mask) { string langStr = "["; langStr += fp_Name(tables->fprint[i]); Guess g(langStr.c_str()); lang.push_back(g); } } return lang; } vector<Guess> SimpleGuesser::GetAvailableLanguages() { return GetManagedLanguages( sal::static_int_cast< char >( 0xF0 ) ); } vector<Guess> SimpleGuesser::GetUnavailableLanguages() { return GetManagedLanguages( sal::static_int_cast< char >( 0x0F )); } vector<Guess> SimpleGuesser::GetAllManagedLanguages() { return GetManagedLanguages( sal::static_int_cast< char >( 0xFF )); } void SimpleGuesser::XableLanguage(string lang, char mask) { textcat_t *tables = (textcat_t*)h; if(!h){return;} for (size_t i=0; i<tables->size; i++) { string language(fp_Name(tables->fprint[i])); if (start(language,lang) == 0) tables->fprint_disable[i] = mask; } } void SimpleGuesser::EnableLanguage(string lang) { XableLanguage(lang, sal::static_int_cast< char >( 0xF0 )); } void SimpleGuesser::DisableLanguage(string lang) { XableLanguage(lang, sal::static_int_cast< char >( 0x0F )); } /** * */ void SimpleGuesser::SetDBPath(const char* path, const char* prefix) { if (h) textcat_Done(h); h = special_textcat_Init(path, prefix); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include <gtest/gtest.h> #include <planning_scene_monitor/planning_scene_monitor.h> #include <ompl_interface_ros/ompl_interface_ros.h> #include <moveit_msgs/GetMotionPlan.h> #include <moveit_msgs/DisplayTrajectory.h> #include <kinematic_constraints/utils.h> static const std::string PLANNER_SERVICE_NAME="/ompl_planning/plan_kinematic_path"; static const std::string ROBOT_DESCRIPTION="robot_description"; TEST(OmplPlanning, SimplePlan) { ros::NodeHandle nh; ros::service::waitForService(PLANNER_SERVICE_NAME); ros::Publisher pub = nh.advertise<moveit_msgs::DisplayTrajectory>("display_test_motion_plan", 1); ros::ServiceClient planning_service_client = nh.serviceClient<moveit_msgs::GetMotionPlan>(PLANNER_SERVICE_NAME); EXPECT_TRUE(planning_service_client.exists()); EXPECT_TRUE(planning_service_client.isValid()); moveit_msgs::GetMotionPlan::Request mplan_req; moveit_msgs::GetMotionPlan::Response mplan_res; planning_scene_monitor::PlanningSceneMonitor psm(ROBOT_DESCRIPTION, NULL); planning_scene::PlanningScene &scene = *psm.getPlanningScene(); EXPECT_TRUE(scene.isConfigured()); mplan_req.motion_plan_request.planner_id = "SBLkConfigDefault"; mplan_req.motion_plan_request.group_name = "right_arm"; mplan_req.motion_plan_request.num_planning_attempts = 100; mplan_req.motion_plan_request.allowed_planning_time = ros::Duration(5.0); const std::vector<std::string>& joint_names = scene.getKinematicModel()->getJointModelGroup("right_arm")->getJointModelNames(); mplan_req.motion_plan_request.goal_constraints.resize(1); mplan_req.motion_plan_request.goal_constraints[0].joint_constraints.resize(joint_names.size()); for(unsigned int i = 0; i < joint_names.size(); i++) { mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[i].joint_name = joint_names[i]; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[i].position = 0.0; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[i].tolerance_above = 0.001; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[i].tolerance_below = 0.001; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[i].weight = 1.0; } mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[0].position = -2.0; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[3].position = -.2; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[5].position = -.2; ASSERT_TRUE(planning_service_client.call(mplan_req, mplan_res)); ASSERT_EQ(mplan_res.error_code.val, mplan_res.error_code.SUCCESS); EXPECT_GT(mplan_res.trajectory.joint_trajectory.points.size(), 0); moveit_msgs::DisplayTrajectory d; d.model_id = scene.getKinematicModel()->getName(); d.robot_state = mplan_res.robot_state; d.trajectory = mplan_res.trajectory; pub.publish(d); ros::Duration(0.5).sleep(); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "test_ompl_planning", ros::init_options::AnonymousName); ros::AsyncSpinner spinner(1); spinner.start(); return RUN_ALL_TESTS(); } <commit_msg>fix test<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include <gtest/gtest.h> #include <planning_scene_monitor/planning_scene_monitor.h> #include <ompl_interface_ros/ompl_interface_ros.h> #include <moveit_msgs/GetMotionPlan.h> #include <moveit_msgs/DisplayTrajectory.h> #include <kinematic_constraints/utils.h> static const std::string PLANNER_SERVICE_NAME="/ompl_planning/plan_kinematic_path"; static const std::string ROBOT_DESCRIPTION="robot_description"; TEST(OmplPlanning, SimplePlan) { ros::NodeHandle nh; ros::service::waitForService(PLANNER_SERVICE_NAME); ros::Publisher pub = nh.advertise<moveit_msgs::DisplayTrajectory>("display_motion_plan", 1); ros::ServiceClient planning_service_client = nh.serviceClient<moveit_msgs::GetMotionPlan>(PLANNER_SERVICE_NAME); EXPECT_TRUE(planning_service_client.exists()); EXPECT_TRUE(planning_service_client.isValid()); moveit_msgs::GetMotionPlan::Request mplan_req; moveit_msgs::GetMotionPlan::Response mplan_res; planning_scene_monitor::PlanningSceneMonitor psm(ROBOT_DESCRIPTION, NULL); planning_scene::PlanningScene &scene = *psm.getPlanningScene(); EXPECT_TRUE(scene.isConfigured()); mplan_req.motion_plan_request.planner_id = "LBKPIECEkConfigDefault"; mplan_req.motion_plan_request.group_name = "right_arm"; mplan_req.motion_plan_request.num_planning_attempts = 8; mplan_req.motion_plan_request.allowed_planning_time = ros::Duration(5.0); const std::vector<std::string>& joint_names = scene.getKinematicModel()->getJointModelGroup("right_arm")->getJointModelNames(); mplan_req.motion_plan_request.goal_constraints.resize(1); mplan_req.motion_plan_request.goal_constraints[0].joint_constraints.resize(joint_names.size()); for(unsigned int i = 0; i < joint_names.size(); i++) { mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[i].joint_name = joint_names[i]; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[i].position = 0.0; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[i].tolerance_above = 0.001; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[i].tolerance_below = 0.001; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[i].weight = 1.0; } mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[0].position = -2.0; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[3].position = -.2; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[5].position = -.2; ASSERT_TRUE(planning_service_client.call(mplan_req, mplan_res)); ASSERT_EQ(mplan_res.error_code.val, mplan_res.error_code.SUCCESS); EXPECT_GT(mplan_res.trajectory.joint_trajectory.points.size(), 0); moveit_msgs::DisplayTrajectory d; d.model_id = scene.getKinematicModel()->getName(); d.robot_state = mplan_res.robot_state; d.trajectory = mplan_res.trajectory; pub.publish(d); ros::Duration(0.5).sleep(); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "test_ompl_planning", ros::init_options::AnonymousName); ros::AsyncSpinner spinner(1); spinner.start(); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "Listener.h" NS_MARATON_BEGIN Listener::Listener( std::string addr , int port ) : Operator( addr , port ) { this->uv_tcp_.data = this; } Listener::~Listener() { } void Listener::do_work() { auto result = uv_tcp_init( this->uv_loop_ , &this->uv_tcp_ ); LOG_DEBUG_UV( result ); result = uv_tcp_bind( &this->uv_tcp_ , ( const struct sockaddr* )&this->addr_in_ , 0 ); LOG_DEBUG_UV( result ); result = uv_listen ( ( uv_stream_t* ) &this->uv_tcp_ , MAX_CONNECTION_SIZE , Listener::uv_new_connection_callback ); LOG_DEBUG_UV( result ); } void Listener::uv_new_connection_callback( uv_stream_t * server , int status ) { Listener* listener = scast<Listener*>( server->data ); if ( status < 0 ) { LOG_DEBUG_UV( status ); return; } if ( listener == nullptr ) { LOG_DEBUG( "Listener is nullptr!" ); return; } auto session = listener->create_session( ); uv_tcp_init ( listener->uv_loop_ , &session->uv_tcp_ ); session->uv_tcp_.data = session; session->opt_ = listener; auto r = uv_accept( server , ( uv_stream_t* ) &session->uv_tcp_ ); struct sockaddr peername; struct sockaddr_in* peer_addr; int namelen; memset(&peername, -1, sizeof peername); namelen = sizeof peername; r = uv_tcp_getpeername(&session->uv_tcp_, &peername, &namelen); peer_addr = (sockaddr_in*)&peername; auto ip = inet_ntoa( peer_addr->sin_addr ); session->ip_address_ = ip; session->port_ = peer_addr->sin_port; if ( r == 0 ) { //for ( size_t i = 0; i <= listener->session_list_index_; i++ ) //{ // if ( listener->session_list_[i] == nullptr ) // { // listener->session_list_[i] = session; // if ( listener->session_list_index_ == i ) // { // listener->session_list_index_ = // ( listener->session_list_index_ + 1 ) % // MAX_CONNECTION_SIZE; // } // break; // } //} r = uv_read_start( (uv_stream_t*)&session->uv_tcp_ , Listener::uv_alloc_callback , Listener::uv_read_callback ); LOG_DEBUG_UV( r ); listener->on_session_open( session ); session->on_connect( ); } else { uv_close( ( uv_handle_t* ) &session->uv_tcp_ , Listener::uv_close_callback ); } } void Listener::uv_alloc_callback( uv_handle_t * handle , size_t suggested_size , uv_buf_t * buf ) { buf->base = new char[suggested_size]; buf->len = suggested_size; } void Listener::uv_read_callback( uv_stream_t * stream , ssize_t nread , const uv_buf_t * buf ) { Session* session = scast<Session*>( stream->data ); if ( session == nullptr ) { LOG_DEBUG( "Session is nullptr!" ); return; } if ( nread < 0 ) { LOG_DEBUG_UV( nread ); uv_close( ( uv_handle_t* ) &session->uv_tcp_ , Listener::uv_close_callback ); return; } uptr<Buffer> pbuf = make_uptr( Buffer , buf->base , nread ); session->on_read( move_ptr( pbuf ) ); delete buf->base; } void Listener::uv_close_callback( uv_handle_t * handle ) { Session* session = scast<Session*>( handle->data ); if ( session == nullptr ) { LOG_DEBUG( "Session is nullptr!" ); return; } Listener* listener = scast<Listener*>( session->opt_ ); if ( listener == nullptr ) { LOG_DEBUG( "Listener is nullptr!" ); return; } session->on_close ( ); listener->on_session_close ( session ); //for ( size_t i = 0; i < listener->session_list_index_; i++ ) //{ // if( listener->session_list_[i] == session ) // { // SAFE_DELETE( listener->session_list_[i] ); // if( (listener->session_list_index_ - 1) == i ) // { // --listener->session_list_index_; // } // break; // } //} } void Listener::close_session( Session * session ) { uv_close( ( uv_handle_t* ) &session->uv_tcp_ , Listener::uv_close_callback ); } NS_MARATON_END <commit_msg>kill compiling errors<commit_after>#include "Listener.h" #ifndef _WIN32 #include <string.h> #endif NS_MARATON_BEGIN Listener::Listener( std::string addr , int port ) : Operator( addr , port ) { this->uv_tcp_.data = this; } Listener::~Listener() { } void Listener::do_work() { auto result = uv_tcp_init( this->uv_loop_ , &this->uv_tcp_ ); LOG_DEBUG_UV( result ); result = uv_tcp_bind( &this->uv_tcp_ , ( const struct sockaddr* )&this->addr_in_ , 0 ); LOG_DEBUG_UV( result ); result = uv_listen ( ( uv_stream_t* ) &this->uv_tcp_ , MAX_CONNECTION_SIZE , Listener::uv_new_connection_callback ); LOG_DEBUG_UV( result ); } void Listener::uv_new_connection_callback( uv_stream_t * server , int status ) { Listener* listener = scast<Listener*>( server->data ); if ( status < 0 ) { LOG_DEBUG_UV( status ); return; } if ( listener == nullptr ) { LOG_DEBUG( "Listener is nullptr!" ); return; } auto session = listener->create_session( ); uv_tcp_init ( listener->uv_loop_ , &session->uv_tcp_ ); session->uv_tcp_.data = session; session->opt_ = listener; auto r = uv_accept( server , ( uv_stream_t* ) &session->uv_tcp_ ); struct sockaddr peername; struct sockaddr_in* peer_addr; int namelen; memset(&peername, -1, sizeof peername); namelen = sizeof peername; r = uv_tcp_getpeername(&session->uv_tcp_, &peername, &namelen); peer_addr = (sockaddr_in*)&peername; auto ip = inet_ntoa( peer_addr->sin_addr ); session->ip_address_ = ip; session->port_ = peer_addr->sin_port; if ( r == 0 ) { //for ( size_t i = 0; i <= listener->session_list_index_; i++ ) //{ // if ( listener->session_list_[i] == nullptr ) // { // listener->session_list_[i] = session; // if ( listener->session_list_index_ == i ) // { // listener->session_list_index_ = // ( listener->session_list_index_ + 1 ) % // MAX_CONNECTION_SIZE; // } // break; // } //} r = uv_read_start( (uv_stream_t*)&session->uv_tcp_ , Listener::uv_alloc_callback , Listener::uv_read_callback ); LOG_DEBUG_UV( r ); listener->on_session_open( session ); session->on_connect( ); } else { uv_close( ( uv_handle_t* ) &session->uv_tcp_ , Listener::uv_close_callback ); } } void Listener::uv_alloc_callback( uv_handle_t * handle , size_t suggested_size , uv_buf_t * buf ) { buf->base = new char[suggested_size]; buf->len = suggested_size; } void Listener::uv_read_callback( uv_stream_t * stream , ssize_t nread , const uv_buf_t * buf ) { Session* session = scast<Session*>( stream->data ); if ( session == nullptr ) { LOG_DEBUG( "Session is nullptr!" ); return; } if ( nread < 0 ) { LOG_DEBUG_UV( nread ); uv_close( ( uv_handle_t* ) &session->uv_tcp_ , Listener::uv_close_callback ); return; } uptr<Buffer> pbuf = make_uptr( Buffer , buf->base , nread ); session->on_read( move_ptr( pbuf ) ); delete buf->base; } void Listener::uv_close_callback( uv_handle_t * handle ) { Session* session = scast<Session*>( handle->data ); if ( session == nullptr ) { LOG_DEBUG( "Session is nullptr!" ); return; } Listener* listener = scast<Listener*>( session->opt_ ); if ( listener == nullptr ) { LOG_DEBUG( "Listener is nullptr!" ); return; } session->on_close ( ); listener->on_session_close ( session ); //for ( size_t i = 0; i < listener->session_list_index_; i++ ) //{ // if( listener->session_list_[i] == session ) // { // SAFE_DELETE( listener->session_list_[i] ); // if( (listener->session_list_index_ - 1) == i ) // { // --listener->session_list_index_; // } // break; // } //} } void Listener::close_session( Session * session ) { uv_close( ( uv_handle_t* ) &session->uv_tcp_ , Listener::uv_close_callback ); } NS_MARATON_END <|endoftext|>
<commit_before>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/opOverlay.h> #include <geos/io.h> #include <stdio.h> #define DEBUG 0 #define COMPUTE_Z 0 namespace geos { LineBuilder::LineBuilder(OverlayOp *newOp, const GeometryFactory *newGeometryFactory, PointLocator *newPtLocator) { op=newOp; geometryFactory=newGeometryFactory; ptLocator=newPtLocator; lineEdgesList=new vector<Edge*>(); resultLineList=new vector<LineString*>(); } LineBuilder::~LineBuilder() { delete lineEdgesList; } /* * @return a list of the LineStrings in the result of the * specified overlay operation */ vector<LineString*>* LineBuilder::build(int opCode) { findCoveredLineEdges(); collectLines(opCode); //labelIsolatedLines(lineEdgesList); buildLines(opCode); return resultLineList; } /* * Find and mark L edges which are "covered" by the result area (if any). * L edges at nodes which also have A edges can be checked by checking * their depth at that node. * L edges at nodes which do not have A edges can be checked by doing a * point-in-polygon test with the previously computed result areas. */ void LineBuilder::findCoveredLineEdges() { // first set covered for all L edges at nodes which have A edges too map<Coordinate,Node*,CoordLT> *nodeMap=op->getGraph()->getNodeMap()->nodeMap; map<Coordinate,Node*,CoordLT>::iterator it=nodeMap->begin(); for (;it!=nodeMap->end();it++) { Node *node=it->second; //node.print(System.out); ((DirectedEdgeStar*)node->getEdges())->findCoveredLineEdges(); } /* * For all L edges which weren't handled by the above, * use a point-in-poly test to determine whether they are covered */ vector<EdgeEnd*> *ee=op->getGraph()->getEdgeEnds(); for(int i=0;i<(int)ee->size();i++) { DirectedEdge *de=(DirectedEdge*) (*ee)[i]; Edge *e=de->getEdge(); if (de->isLineEdge() && !e->isCoveredSet()) { bool isCovered=op->isCoveredByA(de->getCoordinate()); e->setCovered(isCovered); } } } void LineBuilder::collectLines(int opCode) { vector<EdgeEnd*> *ee=op->getGraph()->getEdgeEnds(); for(int i=0;i<(int)ee->size();i++) { DirectedEdge *de=(DirectedEdge*) (*ee)[i]; collectLineEdge(de,opCode,lineEdgesList); collectBoundaryTouchEdge(de,opCode,lineEdgesList); } } void LineBuilder::collectLineEdge(DirectedEdge *de,int opCode,vector<Edge*> *edges) { Label *label=de->getLabel(); Edge *e=de->getEdge(); // include L edges which are in the result if (de->isLineEdge()) { if (!de->isVisited() && OverlayOp::isResultOfOp(label,opCode) && !e->isCovered()) { //Debug.println("de: "+de.getLabel()); //Debug.println("edge: "+e.getLabel()); edges->push_back(e); de->setVisitedEdge(true); } } } /* * Collect edges from Area inputs which should be in the result but * which have not been included in a result area. * This happens ONLY: * - during an intersection when the boundaries of two * areas touch in a line segment * - OR as a result of a dimensional collapse. */ void LineBuilder::collectBoundaryTouchEdge(DirectedEdge *de,int opCode,vector<Edge*> *edges) { Label *label=de->getLabel(); // this smells like a bit of a hack, but it seems to work... if (!de->isLineEdge() && !de->isInteriorAreaEdge() // added to handle dimensional collapses && !de->getEdge()->isInResult() && !de->isVisited() && OverlayOp::isResultOfOp(label,opCode) && opCode==OverlayOp::INTERSECTION) { edges->push_back(de->getEdge()); de->setVisitedEdge(true); } } void LineBuilder::buildLines(int opCode) { // need to simplify lines? for(int i=0;i<(int)lineEdgesList->size();i++) { Edge *e=(*lineEdgesList)[i]; //Label *label=e->getLabel(); CoordinateSequence *cs = e->getCoordinates()->clone(); #if COMPUTE_Z propagateZ(cs); #endif LineString *line=geometryFactory->createLineString(cs); resultLineList->push_back(line); e->setInResult(true); } } /* * If the given CoordinateSequence has mixed 3d/2d vertexes * set Z for all vertexes missing it. * The Z value is interpolated between 3d vertexes and copied * from a 3d vertex to the end. */ void LineBuilder::propagateZ(CoordinateSequence *cs) { unsigned int i; #if DEBUG cerr<<"LineBuilder::propagateZ() called"<<endl; #endif vector<int>v3d; // vertex 3d unsigned int cssize = cs->getSize(); for (i=0; i<cssize; i++) { if ( cs->getAt(i).z != DoubleNotANumber ) v3d.push_back(i); } #if DEBUG cerr<<" found "<<v3d.size()<<" 3d vertexes"<<endl; #endif if ( v3d.size() == 0 ) { #if DEBUG cerr<<" nothing to do"<<endl; #endif return; } Coordinate buf; // fill initial part if ( v3d[0] != 0 ) { double z = cs->getAt(v3d[0]).z; for (int j=0; j<v3d[0]; j++) { buf = cs->getAt(j); buf.z = z; cs->setAt(buf, j); } } // interpolate inbetweens int prev=v3d[0]; for (i=1; i<v3d.size(); i++) { int curr=v3d[i]; int dist = curr-prev; if (dist > 1) { const Coordinate &cto = cs->getAt(curr); const Coordinate &cfrom = cs->getAt(prev); double gap = cto.z-cfrom.z; double zstep = gap/dist; double z = cfrom.z; for (int j=prev+1; j<curr; j++) { buf = cs->getAt(j); z+=zstep; buf.z = z; cs->setAt(buf, j); } } prev = curr; } // fill final part if ( prev < cssize-1 ) { double z = cs->getAt(prev).z; for (int j=prev+1; j<cssize; j++) { buf = cs->getAt(j); buf.z = z; cs->setAt(buf, j); } } } void LineBuilder::labelIsolatedLines(vector<Edge*> *edgesList) { for(int i=0;i<(int)edgesList->size();i++) { Edge *e=(*edgesList)[i]; Label *label=e->getLabel(); //n.print(System.out); if (e->isIsolated()) { if (label->isNull(0)) labelIsolatedLine(e,0); else labelIsolatedLine(e,1); } } } /* * Label an isolated node with its relationship to the target geometry. */ void LineBuilder::labelIsolatedLine(Edge *e,int targetIndex) { int loc=ptLocator->locate(e->getCoordinate(),op->getArgGeometry(targetIndex)); e->getLabel()->setLocation(targetIndex,loc); } } /********************************************************************** * $Log$ * Revision 1.15 2004/11/23 19:53:07 strk * Had LineIntersector compute Z by interpolation. * * Revision 1.14 2004/11/20 18:17:26 strk * Added Z propagation for overlay lines output. * * Revision 1.13 2004/10/20 17:32:14 strk * Initial approach to 2.5d intersection() * * Revision 1.12 2004/07/02 13:28:28 strk * Fixed all #include lines to reflect headers layout change. * Added client application build tips in README. * * Revision 1.11 2004/07/01 14:12:44 strk * * Geometry constructors come now in two flavors: * - deep-copy args (pass-by-reference) * - take-ownership of args (pass-by-pointer) * Same functionality is available through GeometryFactory, * including buildGeometry(). * * Revision 1.10 2004/06/30 20:59:13 strk * Removed GeoemtryFactory copy from geometry constructors. * Enforced const-correctness on GeometryFactory arguments. * * Revision 1.9 2003/11/07 01:23:42 pramsey * Add standard CVS headers licence notices and copyrights to all cpp and h * files. * * Revision 1.8 2003/10/16 08:50:00 strk * Memory leak fixes. Improved performance by mean of more calls * to new getCoordinatesRO() when applicable. * **********************************************************************/ <commit_msg>Re-enabled Z propagation in output lines.<commit_after>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/opOverlay.h> #include <geos/io.h> #include <stdio.h> #define DEBUG 0 #define COMPUTE_Z 1 namespace geos { LineBuilder::LineBuilder(OverlayOp *newOp, const GeometryFactory *newGeometryFactory, PointLocator *newPtLocator) { op=newOp; geometryFactory=newGeometryFactory; ptLocator=newPtLocator; lineEdgesList=new vector<Edge*>(); resultLineList=new vector<LineString*>(); } LineBuilder::~LineBuilder() { delete lineEdgesList; } /* * @return a list of the LineStrings in the result of the * specified overlay operation */ vector<LineString*>* LineBuilder::build(int opCode) { findCoveredLineEdges(); collectLines(opCode); //labelIsolatedLines(lineEdgesList); buildLines(opCode); return resultLineList; } /* * Find and mark L edges which are "covered" by the result area (if any). * L edges at nodes which also have A edges can be checked by checking * their depth at that node. * L edges at nodes which do not have A edges can be checked by doing a * point-in-polygon test with the previously computed result areas. */ void LineBuilder::findCoveredLineEdges() { // first set covered for all L edges at nodes which have A edges too map<Coordinate,Node*,CoordLT> *nodeMap=op->getGraph()->getNodeMap()->nodeMap; map<Coordinate,Node*,CoordLT>::iterator it=nodeMap->begin(); for (;it!=nodeMap->end();it++) { Node *node=it->second; //node.print(System.out); ((DirectedEdgeStar*)node->getEdges())->findCoveredLineEdges(); } /* * For all L edges which weren't handled by the above, * use a point-in-poly test to determine whether they are covered */ vector<EdgeEnd*> *ee=op->getGraph()->getEdgeEnds(); for(int i=0;i<(int)ee->size();i++) { DirectedEdge *de=(DirectedEdge*) (*ee)[i]; Edge *e=de->getEdge(); if (de->isLineEdge() && !e->isCoveredSet()) { bool isCovered=op->isCoveredByA(de->getCoordinate()); e->setCovered(isCovered); } } } void LineBuilder::collectLines(int opCode) { vector<EdgeEnd*> *ee=op->getGraph()->getEdgeEnds(); for(int i=0;i<(int)ee->size();i++) { DirectedEdge *de=(DirectedEdge*) (*ee)[i]; collectLineEdge(de,opCode,lineEdgesList); collectBoundaryTouchEdge(de,opCode,lineEdgesList); } } void LineBuilder::collectLineEdge(DirectedEdge *de,int opCode,vector<Edge*> *edges) { Label *label=de->getLabel(); Edge *e=de->getEdge(); // include L edges which are in the result if (de->isLineEdge()) { if (!de->isVisited() && OverlayOp::isResultOfOp(label,opCode) && !e->isCovered()) { //Debug.println("de: "+de.getLabel()); //Debug.println("edge: "+e.getLabel()); edges->push_back(e); de->setVisitedEdge(true); } } } /* * Collect edges from Area inputs which should be in the result but * which have not been included in a result area. * This happens ONLY: * - during an intersection when the boundaries of two * areas touch in a line segment * - OR as a result of a dimensional collapse. */ void LineBuilder::collectBoundaryTouchEdge(DirectedEdge *de,int opCode,vector<Edge*> *edges) { Label *label=de->getLabel(); // this smells like a bit of a hack, but it seems to work... if (!de->isLineEdge() && !de->isInteriorAreaEdge() // added to handle dimensional collapses && !de->getEdge()->isInResult() && !de->isVisited() && OverlayOp::isResultOfOp(label,opCode) && opCode==OverlayOp::INTERSECTION) { edges->push_back(de->getEdge()); de->setVisitedEdge(true); } } void LineBuilder::buildLines(int opCode) { // need to simplify lines? for(int i=0;i<(int)lineEdgesList->size();i++) { Edge *e=(*lineEdgesList)[i]; //Label *label=e->getLabel(); CoordinateSequence *cs = e->getCoordinates()->clone(); #if COMPUTE_Z propagateZ(cs); #endif LineString *line=geometryFactory->createLineString(cs); resultLineList->push_back(line); e->setInResult(true); } } /* * If the given CoordinateSequence has mixed 3d/2d vertexes * set Z for all vertexes missing it. * The Z value is interpolated between 3d vertexes and copied * from a 3d vertex to the end. */ void LineBuilder::propagateZ(CoordinateSequence *cs) { unsigned int i; #if DEBUG cerr<<"LineBuilder::propagateZ() called"<<endl; #endif vector<int>v3d; // vertex 3d unsigned int cssize = cs->getSize(); for (i=0; i<cssize; i++) { if ( cs->getAt(i).z != DoubleNotANumber ) v3d.push_back(i); } #if DEBUG cerr<<" found "<<v3d.size()<<" 3d vertexes"<<endl; #endif if ( v3d.size() == 0 ) { #if DEBUG cerr<<" nothing to do"<<endl; #endif return; } Coordinate buf; // fill initial part if ( v3d[0] != 0 ) { double z = cs->getAt(v3d[0]).z; for (int j=0; j<v3d[0]; j++) { buf = cs->getAt(j); buf.z = z; cs->setAt(buf, j); } } // interpolate inbetweens int prev=v3d[0]; for (i=1; i<v3d.size(); i++) { int curr=v3d[i]; int dist = curr-prev; if (dist > 1) { const Coordinate &cto = cs->getAt(curr); const Coordinate &cfrom = cs->getAt(prev); double gap = cto.z-cfrom.z; double zstep = gap/dist; double z = cfrom.z; for (int j=prev+1; j<curr; j++) { buf = cs->getAt(j); z+=zstep; buf.z = z; cs->setAt(buf, j); } } prev = curr; } // fill final part if ( prev < cssize-1 ) { double z = cs->getAt(prev).z; for (int j=prev+1; j<cssize; j++) { buf = cs->getAt(j); buf.z = z; cs->setAt(buf, j); } } } void LineBuilder::labelIsolatedLines(vector<Edge*> *edgesList) { for(int i=0;i<(int)edgesList->size();i++) { Edge *e=(*edgesList)[i]; Label *label=e->getLabel(); //n.print(System.out); if (e->isIsolated()) { if (label->isNull(0)) labelIsolatedLine(e,0); else labelIsolatedLine(e,1); } } } /* * Label an isolated node with its relationship to the target geometry. */ void LineBuilder::labelIsolatedLine(Edge *e,int targetIndex) { int loc=ptLocator->locate(e->getCoordinate(),op->getArgGeometry(targetIndex)); e->getLabel()->setLocation(targetIndex,loc); } } /********************************************************************** * $Log$ * Revision 1.16 2004/11/24 11:32:39 strk * Re-enabled Z propagation in output lines. * * Revision 1.15 2004/11/23 19:53:07 strk * Had LineIntersector compute Z by interpolation. * * Revision 1.14 2004/11/20 18:17:26 strk * Added Z propagation for overlay lines output. * * Revision 1.13 2004/10/20 17:32:14 strk * Initial approach to 2.5d intersection() * * Revision 1.12 2004/07/02 13:28:28 strk * Fixed all #include lines to reflect headers layout change. * Added client application build tips in README. * * Revision 1.11 2004/07/01 14:12:44 strk * * Geometry constructors come now in two flavors: * - deep-copy args (pass-by-reference) * - take-ownership of args (pass-by-pointer) * Same functionality is available through GeometryFactory, * including buildGeometry(). * * Revision 1.10 2004/06/30 20:59:13 strk * Removed GeoemtryFactory copy from geometry constructors. * Enforced const-correctness on GeometryFactory arguments. * * Revision 1.9 2003/11/07 01:23:42 pramsey * Add standard CVS headers licence notices and copyrights to all cpp and h * files. * * Revision 1.8 2003/10/16 08:50:00 strk * Memory leak fixes. Improved performance by mean of more calls * to new getCoordinatesRO() when applicable. * **********************************************************************/ <|endoftext|>
<commit_before>//A ROOT macro that prepares Tree for TMVA training //---------------------------------------------- //Author: Maxwell Cui //Date: Aug 19, 2017 //---------------------------------------------- #include<iostream> #include<cstdlib> #include<string> #include<fstream> void create(TFile* inputTree, TString outputName) { TTree *oldTree=new TTree; inputTree->GetObject("nominal_Loose",oldTree); //Deactive all branches oldTree->SetBranchStatus("*",0); //Active the interested branches oldTree->SetBranchStatus("ht",1); oldTree->SetBranchStatus("met_met",1); oldTree->SetBranchStatus("met_sumet",1); oldTree->SetBranchStatus("mu_pt",1); oldTree->SetBranchStatus("el_pt",1); oldTree->SetBranchStatus("mu",1); oldTree->SetBranchStatus("jet_pt",1); oldTree->SetBranchStatus("met_phi",1); oldTree->SetBranchStatus("SSee_2016",1); oldTree->SetBranchStatus("SSmm_2016",1); oldTree->SetBranchStatus("SSem_2016",1); oldTree->SetBranchStatus("eee_2016",1); oldTree->SetBranchStatus("eem_2016",1); oldTree->SetBranchStatus("emm_2016",1); oldTree->SetBranchStatus("mmm_2016",1); oldTree->SetBranchStatus("lep_pt",1); oldTree->SetBranchStatus("jet_mv2c10",1); //Using MV2c10 for b-tagging //oldTree->SetBranchStatus("weight_mc",1); //====================Output file========================== // TFile *outputFile=new TFile(outputName,"recreate"); // //========================================================= //Copy to new tree TTree *newTree=oldTree->CloneTree(); //Working with b-jet // // Declaration of leaf types Float_t mu; vector<float> *el_pt; vector<float> *mu_pt; vector<float> *jet_pt; vector<float> *jet_mv2c10; Float_t met_met; Float_t met_phi; Float_t met_sumet; Int_t SSee_2016; Int_t SSmm_2016; Int_t SSem_2016; Int_t eee_2016; Int_t eem_2016; Int_t emm_2016; Int_t mmm_2016; vector<float> *lep_pt; Float_t ht; // List of branches TBranch *b_mu; //! TBranch *b_el_pt; //! TBranch *b_mu_pt; //! TBranch *b_jet_pt; //! TBranch *b_jet_mv2c10; //! TBranch *b_met_met; //! TBranch *b_met_sumet; TBranch *b_met_phi; //! TBranch *b_SSee_2016; //! TBranch *b_SSmm_2016; //! TBranch *b_SSem_2016; //! TBranch *b_eee_2016; //! TBranch *b_eem_2016; //! TBranch *b_emm_2016; //! TBranch *b_mmm_2016; //! TBranch *b_lep_pt; //! TBranch *b_ht; //! //Set object pointer el_pt = 0; mu_pt = 0; jet_pt = 0; jet_mv2c10 = 0; lep_pt = 0; //Set branch addresses and brunch pointers oldTree->SetBranchAddress("mu", &mu, &b_mu); oldTree->SetBranchAddress("el_pt", &el_pt, &b_el_pt); oldTree->SetBranchAddress("mu_pt", &mu_pt, &b_mu_pt); oldTree->SetBranchAddress("jet_pt", &jet_pt, &b_jet_pt); oldTree->SetBranchAddress("jet_mv2c10", &jet_mv2c10, &b_jet_mv2c10); oldTree->SetBranchAddress("met_met", &met_met, &b_met_met); oldTree->SetBranchAddress("met_phi", &met_phi, &b_met_phi); oldTree->SetBranchAddress("met_sumet", &met_sumet, &b_met_sumet); oldTree->SetBranchAddress("SSee_2016", &SSee_2016, &b_SSee_2016); oldTree->SetBranchAddress("SSmm_2016", &SSmm_2016, &b_SSmm_2016); oldTree->SetBranchAddress("SSem_2016", &SSem_2016, &b_SSem_2016); oldTree->SetBranchAddress("eee_2016", &eee_2016, &b_eee_2016); oldTree->SetBranchAddress("eem_2016", &eem_2016, &b_eem_2016); oldTree->SetBranchAddress("emm_2016", &emm_2016, &b_emm_2016); oldTree->SetBranchAddress("mmm_2016", &mmm_2016, &b_mmm_2016); oldTree->SetBranchAddress("lep_pt", &lep_pt, &b_lep_pt); oldTree->SetBranchAddress("ht", &ht, &b_ht); //Declare bjet variable Int_t bjet; //Add new branch TBranch *bjetBranch=newTree->Branch("bjet",&bjet,"bjet/I"); Int_t nentries=(Int_t)oldTree->GetEntries(); //Calculate bjet, algorithm is provided by Prof. Varnes for(Int_t i=0;i<nentries;i++) { oldTree->GetEntry(i); bj=0; if(SSee_2016 || SSem_2016 || SSmm_2016 || eee_2016 || eem_2016 || emm_2016 || mmm_2016) { for(unsigned int ibjet=0;ibjet<jet_mv2c10->size();ibjet++) { /// if (jet_mv2c10->at(ibjet) > 0.1758475) { // 85% WP if (jet_mv2c10->at(ibjet) > 0.645925) { // 77% WP //if (jet_mv2c10->at(ibjet) > 0.8244273) { // 70% WP bjet++; } } } bjetBranch->Fill(); } newTree->Print(); newTree->Write(); outputFile->Close(); delete oldTree; } void prepTree() { //Variable 'envName' can be the environmental variable on the system that //includes the path to the directory of the data files. //Please make sure that the variable is exported. const char* envName="MCDATA"; std::string dataPATH=std::getenv(envName); std::ifstream inputFile("datafiles.txt"); std::string fileName; while(std::getline(inputFile,fileName)) { std::cout<<"Readig file: "<<dataPATH+fileName<<std::endl; TString combine; combine=dataPATH+fileName; TFile *bg=new TFile(combine); create(bg,fileName); delete bg; } inputFile.close(); } <commit_msg>update<commit_after>//A ROOT macro that prepares Tree for TMVA training //---------------------------------------------- //Author: Maxwell Cui //Date: Aug 19, 2017 //---------------------------------------------- #include<iostream> #include<cstdlib> #include<string> #include<fstream> void create(TFile* inputTree, TString outputName) { TTree *oldTree=new TTree; inputTree->GetObject("nominal_Loose",oldTree); //Deactive all branches oldTree->SetBranchStatus("*",0); //Active the interested branches oldTree->SetBranchStatus("ht",1); oldTree->SetBranchStatus("met_met",1); oldTree->SetBranchStatus("met_sumet",1); oldTree->SetBranchStatus("mu_pt",1); oldTree->SetBranchStatus("el_pt",1); oldTree->SetBranchStatus("mu",1); oldTree->SetBranchStatus("jet_pt",1); oldTree->SetBranchStatus("met_phi",1); oldTree->SetBranchStatus("SSee_2016",1); oldTree->SetBranchStatus("SSmm_2016",1); oldTree->SetBranchStatus("SSem_2016",1); oldTree->SetBranchStatus("eee_2016",1); oldTree->SetBranchStatus("eem_2016",1); oldTree->SetBranchStatus("emm_2016",1); oldTree->SetBranchStatus("mmm_2016",1); oldTree->SetBranchStatus("lep_pt",1); oldTree->SetBranchStatus("jet_mv2c10",1); //Using MV2c10 for b-tagging //oldTree->SetBranchStatus("weight_mc",1); //====================Output file========================== // TFile *outputFile=new TFile(outputName,"recreate"); // //========================================================= //Copy to new tree TTree *newTree=oldTree->CloneTree(); //Working with b-jet // // Declaration of leaf types Float_t mu; vector<float> *el_pt; vector<float> *mu_pt; vector<float> *jet_pt; vector<float> *jet_mv2c10; Float_t met_met; Float_t met_phi; Float_t met_sumet; Int_t SSee_2016; Int_t SSmm_2016; Int_t SSem_2016; Int_t eee_2016; Int_t eem_2016; Int_t emm_2016; Int_t mmm_2016; vector<float> *lep_pt; Float_t ht; // List of branches TBranch *b_mu; //! TBranch *b_el_pt; //! TBranch *b_mu_pt; //! TBranch *b_jet_pt; //! TBranch *b_jet_mv2c10; //! TBranch *b_met_met; //! TBranch *b_met_sumet; TBranch *b_met_phi; //! TBranch *b_SSee_2016; //! TBranch *b_SSmm_2016; //! TBranch *b_SSem_2016; //! TBranch *b_eee_2016; //! TBranch *b_eem_2016; //! TBranch *b_emm_2016; //! TBranch *b_mmm_2016; //! TBranch *b_lep_pt; //! TBranch *b_ht; //! //Set object pointer el_pt = 0; mu_pt = 0; jet_pt = 0; jet_mv2c10 = 0; lep_pt = 0; //Set branch addresses and brunch pointers oldTree->SetBranchAddress("mu", &mu, &b_mu); oldTree->SetBranchAddress("el_pt", &el_pt, &b_el_pt); oldTree->SetBranchAddress("mu_pt", &mu_pt, &b_mu_pt); oldTree->SetBranchAddress("jet_pt", &jet_pt, &b_jet_pt); oldTree->SetBranchAddress("jet_mv2c10", &jet_mv2c10, &b_jet_mv2c10); oldTree->SetBranchAddress("met_met", &met_met, &b_met_met); oldTree->SetBranchAddress("met_phi", &met_phi, &b_met_phi); oldTree->SetBranchAddress("met_sumet", &met_sumet, &b_met_sumet); oldTree->SetBranchAddress("SSee_2016", &SSee_2016, &b_SSee_2016); oldTree->SetBranchAddress("SSmm_2016", &SSmm_2016, &b_SSmm_2016); oldTree->SetBranchAddress("SSem_2016", &SSem_2016, &b_SSem_2016); oldTree->SetBranchAddress("eee_2016", &eee_2016, &b_eee_2016); oldTree->SetBranchAddress("eem_2016", &eem_2016, &b_eem_2016); oldTree->SetBranchAddress("emm_2016", &emm_2016, &b_emm_2016); oldTree->SetBranchAddress("mmm_2016", &mmm_2016, &b_mmm_2016); oldTree->SetBranchAddress("lep_pt", &lep_pt, &b_lep_pt); oldTree->SetBranchAddress("ht", &ht, &b_ht); //Declare bjet variable Int_t bjet; //Add new branch TBranch *bjetBranch=newTree->Branch("bjet",&bjet,"bjet/I"); Int_t nentries=(Int_t)oldTree->GetEntries(); //Calculate bjet, algorithm is provided by Prof. Varnes for(Int_t i=0;i<nentries;i++) { oldTree->GetEntry(i); bjet=0; if(SSee_2016 || SSem_2016 || SSmm_2016 || eee_2016 || eem_2016 || emm_2016 || mmm_2016) { for(unsigned int ibjet=0;ibjet<jet_mv2c10->size();ibjet++) { /// if (jet_mv2c10->at(ibjet) > 0.1758475) { // 85% WP if (jet_mv2c10->at(ibjet) > 0.645925) { // 77% WP //if (jet_mv2c10->at(ibjet) > 0.8244273) { // 70% WP bjet++; } } } bjetBranch->Fill(); } newTree->Print(); newTree->Write(); outputFile->Close(); delete oldTree; } void prepTree() { //Variable 'envName' can be the environmental variable on the system that //includes the path to the directory of the data files. //Please make sure that the variable is exported. const char* envName="MCDATA"; std::string dataPATH=std::getenv(envName); std::ifstream inputFile("datafiles.txt"); std::string fileName; while(std::getline(inputFile,fileName)) { std::cout<<"Readig file: "<<dataPATH+fileName<<std::endl; TString combine; combine=dataPATH+fileName; TFile *bg=new TFile(combine); create(bg,fileName); delete bg; } inputFile.close(); } <|endoftext|>
<commit_before>/* * NicoW * 27.05.12 */ #include <iostream> #include <sstream> #include "Human.hpp" #include "SaveManager.hpp" #include "LoadSave.hpp" LoadSave::LoadSave(GameManager& game, std::vector<Profile*>& profiles, Profile* guest) : AMenu("menu/background/backgroundLoadSave.jpg", "menu/background/backgroundLoadSave.jpg", 3200.0f, -1.0f, 800.0f, game), _profiles(profiles), _guest(guest), _index(0), _timerL(-1.0f), _timerR(-1.0f) { this->_tags.push_back(new Tag("menu/tags/LoadNormal.png", "menu/tags/LoadHighlit.png", true, false, TokenMenu::LAST, 3629.0f, 0.0f, 1150.0f)); this->_tags.push_back(new Tag("menu/tags/DoneNormal.png", "menu/tags/DoneHighlit.png", false, false, TokenMenu::CREATEGAME, 3629.0f, 0.0f, 1265.0f)); this->_tags.push_back(new Tag("menu/tags/BackNormal.png", "menu/tags/BackHighlit.png", false, false, TokenMenu::PROFILE, 3629.0f, 0.0f, 1330.0f)); } LoadSave::~LoadSave(void) { } double LoadSave::getCenterX(void) const { return (4000.0f); } double LoadSave::getCenterY(void) const { return (1200.0f); } void LoadSave::loadSave() { size_t id; bool flag = false; std::stringstream ss; APlayer* pl1 = 0; APlayer* pl2 = 0; ss << this->_save[this->_index]; ss >> id; if (!SaveManager::getSave(id, this->_gameManager._match)) this->_curToken = TokenMenu::LAST; else { this->_gameManager._originMap = 0; this->_gameManager._typeAI = AIType::LAST; this->_gameManager._nbPlayers = -1; this->_gameManager._nbTeams = -1; this->_gameManager._secondProfile = 0; for (std::vector<APlayer*>::iterator it = this->_gameManager._match._players.begin(); it != this->_gameManager._match._players.end(); ++it) if ((*it)->getId() == this->_gameManager._mainProfile->getId()) pl1 = (*it); else if ((*it)->getId() != static_cast<size_t>(-1)) { for (std::vector<Profile*>::iterator it2 = this->_profiles.begin(); it2 != this->_profiles.end(); ++it2) if ((*it2)->getId() == (*it)->getId()) { this->_gameManager._secondProfile = (*it2); pl2 = (*it); flag = true; break; } if (!flag && this->_gameManager._match._gameMode != GameMode::SOLO) { this->_gameManager._secondProfile = this->_guest; (*it)->setId(this->_guest->getId()); pl2 = (*it); } break; } if (this->_gameManager._match._gameMode == GameMode::SOLO) { std::cout << "Set config J1" << std::endl; dynamic_cast<Human*>(pl1)->setConfig(this->_gameManager._mainProfile->getConfig()); std::cout << "x = " << pl1->getPos()._pos.x << " y = " << pl1->getPos()._pos.y << " z = " << pl1->getPos()._pos.z << std::endl; } else { dynamic_cast<Human*>(pl1)->setConfig(this->_gameManager._configJ1); dynamic_cast<Human*>(pl2)->setConfig(this->_gameManager._configJ2); } } } void LoadSave::updateText() const { if (this->_save.size()) { this->_tags[0]->createText(this->_save[this->_index], 20, 750, 360); this->_tags[1]->createText("info", 20, 500, 411); } else { this->_tags[0]->createText("", 20, 750, 360); this->_tags[1]->createText("", 20, 500, 411); } } void LoadSave::changeSave(gdl::GameClock const& clock, gdl::Input& input) { if (clock.getTotalGameTime() >= this->_timerL && input.isKeyDown(gdl::Keys::Left)) { --this->_index; if (static_cast<int>(this->_index) < 0) this->_index = this->_save.size() - 1; this->_timerL = clock.getTotalGameTime() + 0.15f; } else if (clock.getTotalGameTime() >= this->_timerR && input.isKeyDown(gdl::Keys::Right)) { ++this->_index; if (this->_index >= this->_save.size()) this->_index = 0; this->_timerR = clock.getTotalGameTime() + 0.15f; } } void LoadSave::update(gdl::GameClock const& clock, gdl::Input& input) { if (!this->_save.size()) this->_save = this->_gameManager._mainProfile->getSave(); this->updateText(); for (size_t i = 0; i < this->_keyEvent.size(); ++i) if (input.isKeyDown(this->_keyEvent[i].first)) (this->*_keyEvent[i].second)(clock); if (this->_cursor == 0) this->changeSave(clock, input); if (this->_curToken == TokenMenu::CREATEGAME) { if (this->_save.size()) this->loadSave(); else this->_curToken = TokenMenu::LAST; } } <commit_msg>debug du load pour un solo<commit_after>/* * NicoW * 27.05.12 */ #include <iostream> #include <sstream> #include "Human.hpp" #include "SaveManager.hpp" #include "LoadSave.hpp" LoadSave::LoadSave(GameManager& game, std::vector<Profile*>& profiles, Profile* guest) : AMenu("menu/background/backgroundLoadSave.jpg", "menu/background/backgroundLoadSave.jpg", 3200.0f, -1.0f, 800.0f, game), _profiles(profiles), _guest(guest), _index(0), _timerL(-1.0f), _timerR(-1.0f) { this->_tags.push_back(new Tag("menu/tags/LoadNormal.png", "menu/tags/LoadHighlit.png", true, false, TokenMenu::LAST, 3629.0f, 0.0f, 1150.0f)); this->_tags.push_back(new Tag("menu/tags/DoneNormal.png", "menu/tags/DoneHighlit.png", false, false, TokenMenu::CREATEGAME, 3629.0f, 0.0f, 1265.0f)); this->_tags.push_back(new Tag("menu/tags/BackNormal.png", "menu/tags/BackHighlit.png", false, false, TokenMenu::PROFILE, 3629.0f, 0.0f, 1330.0f)); } LoadSave::~LoadSave(void) { } double LoadSave::getCenterX(void) const { return (4000.0f); } double LoadSave::getCenterY(void) const { return (1200.0f); } void LoadSave::loadSave() { size_t id; bool flag = false; std::stringstream ss; APlayer* pl1 = 0; APlayer* pl2 = 0; ss << this->_save[this->_index]; ss >> id; if (!SaveManager::getSave(id, this->_gameManager._match)) this->_curToken = TokenMenu::LAST; else { this->_gameManager._originMap = 0; this->_gameManager._typeAI = AIType::LAST; this->_gameManager._nbPlayers = -1; this->_gameManager._nbTeams = -1; this->_gameManager._secondProfile = 0; std::cout << "Load Save " << std::endl; for (std::vector<APlayer*>::iterator it = this->_gameManager._match._players.begin(); it != this->_gameManager._match._players.end(); ++it) if ((*it)->getId() == this->_gameManager._mainProfile->getId()) pl1 = (*it); else if ((*it)->getId() != static_cast<size_t>(-1)) { for (std::vector<Profile*>::iterator it2 = this->_profiles.begin(); it2 != this->_profiles.end(); ++it2) if ((*it2)->getId() == (*it)->getId()) { this->_gameManager._secondProfile = (*it2); pl2 = (*it); flag = true; break; } if (!flag && this->_gameManager._match._gameMode != GameMode::SOLO) { this->_gameManager._secondProfile = this->_guest; (*it)->setId(this->_guest->getId()); pl2 = (*it); } break; } if (this->_gameManager._match._gameMode == GameMode::SOLO) { std::cout << "Set config J1" << std::endl; dynamic_cast<Human*>(pl1)->setConfig(this->_gameManager._mainProfile->getConfig()); std::cout << "x = " << pl1->getPos()._pos.x << " y = " << pl1->getPos()._pos.y << " z = " << pl1->getPos()._pos.z << std::endl; } else { dynamic_cast<Human*>(pl1)->setConfig(this->_gameManager._configJ1); dynamic_cast<Human*>(pl2)->setConfig(this->_gameManager._configJ2); } } } void LoadSave::updateText() const { if (this->_save.size()) { this->_tags[0]->createText(this->_save[this->_index], 20, 750, 360); this->_tags[1]->createText("info", 20, 500, 411); } else { this->_tags[0]->createText("", 20, 750, 360); this->_tags[1]->createText("", 20, 500, 411); } } void LoadSave::changeSave(gdl::GameClock const& clock, gdl::Input& input) { if (clock.getTotalGameTime() >= this->_timerL && input.isKeyDown(gdl::Keys::Left)) { --this->_index; if (static_cast<int>(this->_index) < 0) this->_index = this->_save.size() - 1; this->_timerL = clock.getTotalGameTime() + 0.15f; } else if (clock.getTotalGameTime() >= this->_timerR && input.isKeyDown(gdl::Keys::Right)) { ++this->_index; if (this->_index >= this->_save.size()) this->_index = 0; this->_timerR = clock.getTotalGameTime() + 0.15f; } } void LoadSave::update(gdl::GameClock const& clock, gdl::Input& input) { if (!this->_save.size()) this->_save = this->_gameManager._mainProfile->getSave(); this->updateText(); for (size_t i = 0; i < this->_keyEvent.size(); ++i) if (input.isKeyDown(this->_keyEvent[i].first)) (this->*_keyEvent[i].second)(clock); if (this->_cursor == 0) this->changeSave(clock, input); if (this->_curToken == TokenMenu::CREATEGAME) { if (this->_save.size()) this->loadSave(); else this->_curToken = TokenMenu::LAST; } } <|endoftext|>
<commit_before>/* Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "ofMain.h" #include "ofApp.h" //======================================================================== int main(){ ofSetupOpenGL(1024, 768, OF_WINDOW); ofRunApp(new ofApp()); } <commit_msg>Decrease window size to use less screen space<commit_after>/* Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "ofMain.h" #include "ofApp.h" //======================================================================== int main(){ ofSetupOpenGL(126, 64, OF_WINDOW); ofRunApp(new ofApp()); } <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////// // = NMatrix // // A linear algebra library for scientific computation in Ruby. // NMatrix is part of SciRuby. // // NMatrix was originally inspired by and derived from NArray, by // Masahiro Tanaka: http://narray.rubyforge.org // // == Copyright Information // // SciRuby is Copyright (c) 2010 - 2013, Ruby Science Foundation // NMatrix is Copyright (c) 2013, Ruby Science Foundation // // Please see LICENSE.txt for additional copyright notices. // // == Contributing // // By contributing source code to SciRuby, you agree to be bound by // our Contributor Agreement: // // * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement // // == data.cpp // // Functions and data for dealing the data types. /* * Standard Includes */ #include <ruby.h> /* * Project Includes */ #include "types.h" #include "data.h" /* * Global Variables */ namespace nm { const char* const EWOP_OPS[nm::NUM_EWOPS] = { "+", "-", "*", "/", "**", "%", "==", "!=", "<", ">", "<=", ">=" }; const std::string EWOP_NAMES[nm::NUM_EWOPS] = { "add", "sub", "mul", "div", "pow", "mod", "eqeq", "neq", "lt", "gt", "leq", "geq" }; const std::string NONCOM_EWOP_NAMES[nm::NUM_NONCOM_EWOPS] = { "atan2", "ldexp", "hypot" }; const std::string UNARYOPS[nm::NUM_UNARYOPS] = { "sin", "cos", "tan", "asin", "acos", "atan", "sinh", "cosh", "tanh", "asinh", "acosh", "atanh", "exp", "log2", "log10", "sqrt", "erf", "erfc", "cbrt", "gamma" }; template <typename Type> Complex<Type>::Complex(const RubyObject& other) { switch(TYPE(other.rval)) { case T_COMPLEX: r = NUM2DBL(rb_funcall(other.rval, rb_intern("real"), 0)); i = NUM2DBL(rb_funcall(other.rval, rb_intern("imag"), 0)); break; case T_FLOAT: case T_RATIONAL: case T_FIXNUM: case T_BIGNUM: r = NUM2DBL(other.rval); i = 0.0; break; default: rb_raise(rb_eTypeError, "not sure how to convert this type of VALUE to a complex"); } } template <typename Type> Rational<Type>::Rational(const RubyObject& other) { switch (TYPE(other.rval)) { case T_RATIONAL: n = NUM2LONG(rb_funcall(other.rval, rb_intern("numerator"), 0)); d = NUM2LONG(rb_funcall(other.rval, rb_intern("denominator"), 0)); break; case T_FIXNUM: case T_BIGNUM: n = NUM2LONG(other.rval); d = 1; break; case T_COMPLEX: case T_FLOAT: rb_raise(rb_eTypeError, "cannot convert float to a rational"); break; default: rb_raise(rb_eTypeError, "not sure how to convert this type of VALUE to a rational"); } } } // end of namespace nm extern "C" { const char* const DTYPE_NAMES[nm::NUM_DTYPES] = { "byte", "int8", "int16", "int32", "int64", "float32", "float64", "complex64", "complex128", "rational32", "rational64", "rational128", "object" }; const size_t DTYPE_SIZES[nm::NUM_DTYPES] = { sizeof(uint8_t), sizeof(int8_t), sizeof(int16_t), sizeof(int32_t), sizeof(int64_t), sizeof(float32_t), sizeof(float64_t), sizeof(nm::Complex64), sizeof(nm::Complex128), sizeof(nm::Rational32), sizeof(nm::Rational64), sizeof(nm::Rational128), sizeof(nm::RubyObject) }; const nm::dtype_t Upcast[nm::NUM_DTYPES][nm::NUM_DTYPES] = { { nm::BYTE, nm::INT16, nm::INT16, nm::INT32, nm::INT64, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RATIONAL32, nm::RATIONAL64, nm::RATIONAL128, nm::RUBYOBJ}, { nm::INT16, nm::INT8, nm::INT16, nm::INT32, nm::INT64, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RATIONAL32, nm::RATIONAL64, nm::RATIONAL128, nm::RUBYOBJ}, { nm::INT16, nm::INT16, nm::INT16, nm::INT32, nm::INT64, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RATIONAL32, nm::RATIONAL64, nm::RATIONAL128, nm::RUBYOBJ}, { nm::INT32, nm::INT32, nm::INT32, nm::INT32, nm::INT64, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RATIONAL32, nm::RATIONAL64, nm::RATIONAL128, nm::RUBYOBJ}, { nm::INT64, nm::INT64, nm::INT64, nm::INT64, nm::INT64, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RATIONAL32, nm::RATIONAL64, nm::RATIONAL128, nm::RUBYOBJ}, { nm::FLOAT32, nm::FLOAT32, nm::FLOAT32, nm::FLOAT32, nm::FLOAT32, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::RUBYOBJ}, { nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::COMPLEX128, nm::COMPLEX128, nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::RUBYOBJ}, { nm::COMPLEX64, nm::COMPLEX64, nm::COMPLEX64, nm::COMPLEX64, nm::COMPLEX64, nm::COMPLEX64, nm::COMPLEX128, nm::COMPLEX64, nm::COMPLEX128, nm::COMPLEX64, nm::COMPLEX64, nm::COMPLEX64, nm::RUBYOBJ}, { nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::RUBYOBJ}, { nm::RATIONAL32, nm::RATIONAL32, nm::RATIONAL32, nm::RATIONAL32, nm::RATIONAL32, nm::FLOAT64, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RATIONAL32, nm::RATIONAL64, nm::RATIONAL128, nm::RUBYOBJ}, { nm::RATIONAL64, nm::RATIONAL64, nm::RATIONAL64, nm::RATIONAL64, nm::RATIONAL64, nm::FLOAT64, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RATIONAL64, nm::RATIONAL64, nm::RATIONAL128, nm::RUBYOBJ}, { nm::RATIONAL128, nm::RATIONAL128, nm::RATIONAL128, nm::RATIONAL128, nm::RATIONAL128, nm::FLOAT64, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RATIONAL128, nm::RATIONAL128, nm::RATIONAL128, nm::RUBYOBJ}, { nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ} }; /* * Forward Declarations */ /* * Functions */ /* * Converts a RubyObject */ void rubyval_to_cval(VALUE val, nm::dtype_t dtype, void* loc) { using namespace nm; switch (dtype) { case BYTE: *reinterpret_cast<uint8_t*>(loc) = static_cast<uint8_t>(RubyObject(val)); break; case INT8: *reinterpret_cast<int8_t*>(loc) = static_cast<int8_t>(RubyObject(val)); break; case INT16: *reinterpret_cast<int16_t*>(loc) = static_cast<int16_t>(RubyObject(val)); break; case INT32: *reinterpret_cast<int32_t*>(loc) = static_cast<int32_t>(RubyObject(val)); break; case INT64: *reinterpret_cast<int64_t*>(loc) = static_cast<int64_t>(RubyObject(val)); break; case FLOAT32: *reinterpret_cast<float32_t*>(loc) = static_cast<float32_t>(RubyObject(val)); break; case FLOAT64: *reinterpret_cast<float64_t*>(loc) = static_cast<float64_t>(RubyObject(val)); break; case COMPLEX64: *reinterpret_cast<Complex64*>(loc) = RubyObject(val).to<Complex64>(); break; case COMPLEX128: *reinterpret_cast<Complex128*>(loc) = RubyObject(val).to<Complex64>(); break; case RATIONAL32: *reinterpret_cast<Rational32*>(loc) = RubyObject(val).to<Rational32>(); break; case RATIONAL64: *reinterpret_cast<Rational64*>(loc) = RubyObject(val).to<Rational64>(); break; case RATIONAL128: *reinterpret_cast<Rational128*>(loc) = RubyObject(val).to<Rational128>(); break; case RUBYOBJ: *reinterpret_cast<VALUE*>(loc) = val; //rb_raise(rb_eTypeError, "Attempting a bad conversion from a Ruby value."); break; default: rb_raise(rb_eTypeError, "Attempting a bad conversion."); break; } } /* * Create a RubyObject from a regular C value (given a dtype). Does not return a VALUE! To get a VALUE, you need to * look at the rval property of what this function returns. */ nm::RubyObject rubyobj_from_cval(void* val, nm::dtype_t dtype) { using namespace nm; switch (dtype) { case BYTE: return RubyObject(*reinterpret_cast<uint8_t*>(val)); case INT8: return RubyObject(*reinterpret_cast<int8_t*>(val)); case INT16: return RubyObject(*reinterpret_cast<int16_t*>(val)); case INT32: return RubyObject(*reinterpret_cast<int32_t*>(val)); case INT64: return RubyObject(*reinterpret_cast<int64_t*>(val)); case FLOAT32: return RubyObject(*reinterpret_cast<float32_t*>(val)); case FLOAT64: return RubyObject(*reinterpret_cast<float64_t*>(val)); case COMPLEX64: return RubyObject(*reinterpret_cast<Complex64*>(val)); case COMPLEX128: return RubyObject(*reinterpret_cast<Complex128*>(val)); case RATIONAL32: return RubyObject(*reinterpret_cast<Rational32*>(val)); case RATIONAL64: return RubyObject(*reinterpret_cast<Rational64*>(val)); case RATIONAL128: return RubyObject(*reinterpret_cast<Rational128*>(val)); default: throw; rb_raise(nm_eDataTypeError, "Conversion to RubyObject requested from unknown/invalid data type (did you try to convert from a VALUE?)"); } return Qnil; } /* * Allocate and return a piece of data of the correct dtype, converted from a * given RubyObject. */ void* rubyobj_to_cval(VALUE val, nm::dtype_t dtype) { size_t size = DTYPE_SIZES[dtype]; nm_register_value(val); void* ret_val = NM_ALLOC_N(char, size); rubyval_to_cval(val, dtype, ret_val); nm_unregister_value(val); return ret_val; } void nm_init_data() { nm::RubyObject obj(INT2FIX(1)); nm::Rational32 x(obj); nm::Rational64 y(obj); nm::Rational128 z(obj); volatile nm::Complex64 a(obj); volatile nm::Complex128 b(obj); } } // end of extern "C" block <commit_msg>Conservative registration in data.cpp<commit_after>///////////////////////////////////////////////////////////////////// // = NMatrix // // A linear algebra library for scientific computation in Ruby. // NMatrix is part of SciRuby. // // NMatrix was originally inspired by and derived from NArray, by // Masahiro Tanaka: http://narray.rubyforge.org // // == Copyright Information // // SciRuby is Copyright (c) 2010 - 2013, Ruby Science Foundation // NMatrix is Copyright (c) 2013, Ruby Science Foundation // // Please see LICENSE.txt for additional copyright notices. // // == Contributing // // By contributing source code to SciRuby, you agree to be bound by // our Contributor Agreement: // // * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement // // == data.cpp // // Functions and data for dealing the data types. /* * Standard Includes */ #include <ruby.h> /* * Project Includes */ #include "types.h" #include "data.h" /* * Global Variables */ namespace nm { const char* const EWOP_OPS[nm::NUM_EWOPS] = { "+", "-", "*", "/", "**", "%", "==", "!=", "<", ">", "<=", ">=" }; const std::string EWOP_NAMES[nm::NUM_EWOPS] = { "add", "sub", "mul", "div", "pow", "mod", "eqeq", "neq", "lt", "gt", "leq", "geq" }; const std::string NONCOM_EWOP_NAMES[nm::NUM_NONCOM_EWOPS] = { "atan2", "ldexp", "hypot" }; const std::string UNARYOPS[nm::NUM_UNARYOPS] = { "sin", "cos", "tan", "asin", "acos", "atan", "sinh", "cosh", "tanh", "asinh", "acosh", "atanh", "exp", "log2", "log10", "sqrt", "erf", "erfc", "cbrt", "gamma" }; template <typename Type> Complex<Type>::Complex(const RubyObject& other) { switch(TYPE(other.rval)) { case T_COMPLEX: r = NUM2DBL(rb_funcall(other.rval, rb_intern("real"), 0)); i = NUM2DBL(rb_funcall(other.rval, rb_intern("imag"), 0)); break; case T_FLOAT: case T_RATIONAL: case T_FIXNUM: case T_BIGNUM: r = NUM2DBL(other.rval); i = 0.0; break; default: rb_raise(rb_eTypeError, "not sure how to convert this type of VALUE to a complex"); } } template <typename Type> Rational<Type>::Rational(const RubyObject& other) { switch (TYPE(other.rval)) { case T_RATIONAL: n = NUM2LONG(rb_funcall(other.rval, rb_intern("numerator"), 0)); d = NUM2LONG(rb_funcall(other.rval, rb_intern("denominator"), 0)); break; case T_FIXNUM: case T_BIGNUM: n = NUM2LONG(other.rval); d = 1; break; case T_COMPLEX: case T_FLOAT: rb_raise(rb_eTypeError, "cannot convert float to a rational"); break; default: rb_raise(rb_eTypeError, "not sure how to convert this type of VALUE to a rational"); } } } // end of namespace nm extern "C" { const char* const DTYPE_NAMES[nm::NUM_DTYPES] = { "byte", "int8", "int16", "int32", "int64", "float32", "float64", "complex64", "complex128", "rational32", "rational64", "rational128", "object" }; const size_t DTYPE_SIZES[nm::NUM_DTYPES] = { sizeof(uint8_t), sizeof(int8_t), sizeof(int16_t), sizeof(int32_t), sizeof(int64_t), sizeof(float32_t), sizeof(float64_t), sizeof(nm::Complex64), sizeof(nm::Complex128), sizeof(nm::Rational32), sizeof(nm::Rational64), sizeof(nm::Rational128), sizeof(nm::RubyObject) }; const nm::dtype_t Upcast[nm::NUM_DTYPES][nm::NUM_DTYPES] = { { nm::BYTE, nm::INT16, nm::INT16, nm::INT32, nm::INT64, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RATIONAL32, nm::RATIONAL64, nm::RATIONAL128, nm::RUBYOBJ}, { nm::INT16, nm::INT8, nm::INT16, nm::INT32, nm::INT64, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RATIONAL32, nm::RATIONAL64, nm::RATIONAL128, nm::RUBYOBJ}, { nm::INT16, nm::INT16, nm::INT16, nm::INT32, nm::INT64, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RATIONAL32, nm::RATIONAL64, nm::RATIONAL128, nm::RUBYOBJ}, { nm::INT32, nm::INT32, nm::INT32, nm::INT32, nm::INT64, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RATIONAL32, nm::RATIONAL64, nm::RATIONAL128, nm::RUBYOBJ}, { nm::INT64, nm::INT64, nm::INT64, nm::INT64, nm::INT64, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RATIONAL32, nm::RATIONAL64, nm::RATIONAL128, nm::RUBYOBJ}, { nm::FLOAT32, nm::FLOAT32, nm::FLOAT32, nm::FLOAT32, nm::FLOAT32, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::RUBYOBJ}, { nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::COMPLEX128, nm::COMPLEX128, nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::RUBYOBJ}, { nm::COMPLEX64, nm::COMPLEX64, nm::COMPLEX64, nm::COMPLEX64, nm::COMPLEX64, nm::COMPLEX64, nm::COMPLEX128, nm::COMPLEX64, nm::COMPLEX128, nm::COMPLEX64, nm::COMPLEX64, nm::COMPLEX64, nm::RUBYOBJ}, { nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::RUBYOBJ}, { nm::RATIONAL32, nm::RATIONAL32, nm::RATIONAL32, nm::RATIONAL32, nm::RATIONAL32, nm::FLOAT64, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RATIONAL32, nm::RATIONAL64, nm::RATIONAL128, nm::RUBYOBJ}, { nm::RATIONAL64, nm::RATIONAL64, nm::RATIONAL64, nm::RATIONAL64, nm::RATIONAL64, nm::FLOAT64, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RATIONAL64, nm::RATIONAL64, nm::RATIONAL128, nm::RUBYOBJ}, { nm::RATIONAL128, nm::RATIONAL128, nm::RATIONAL128, nm::RATIONAL128, nm::RATIONAL128, nm::FLOAT64, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RATIONAL128, nm::RATIONAL128, nm::RATIONAL128, nm::RUBYOBJ}, { nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ} }; /* * Forward Declarations */ /* * Functions */ /* * Converts a RubyObject */ void rubyval_to_cval(VALUE val, nm::dtype_t dtype, void* loc) { using namespace nm; switch (dtype) { case BYTE: *reinterpret_cast<uint8_t*>(loc) = static_cast<uint8_t>(RubyObject(val)); break; case INT8: *reinterpret_cast<int8_t*>(loc) = static_cast<int8_t>(RubyObject(val)); break; case INT16: *reinterpret_cast<int16_t*>(loc) = static_cast<int16_t>(RubyObject(val)); break; case INT32: *reinterpret_cast<int32_t*>(loc) = static_cast<int32_t>(RubyObject(val)); break; case INT64: *reinterpret_cast<int64_t*>(loc) = static_cast<int64_t>(RubyObject(val)); break; case FLOAT32: *reinterpret_cast<float32_t*>(loc) = static_cast<float32_t>(RubyObject(val)); break; case FLOAT64: *reinterpret_cast<float64_t*>(loc) = static_cast<float64_t>(RubyObject(val)); break; case COMPLEX64: *reinterpret_cast<Complex64*>(loc) = RubyObject(val).to<Complex64>(); break; case COMPLEX128: *reinterpret_cast<Complex128*>(loc) = RubyObject(val).to<Complex64>(); break; case RATIONAL32: *reinterpret_cast<Rational32*>(loc) = RubyObject(val).to<Rational32>(); break; case RATIONAL64: *reinterpret_cast<Rational64*>(loc) = RubyObject(val).to<Rational64>(); break; case RATIONAL128: *reinterpret_cast<Rational128*>(loc) = RubyObject(val).to<Rational128>(); break; case RUBYOBJ: *reinterpret_cast<VALUE*>(loc) = val; //rb_raise(rb_eTypeError, "Attempting a bad conversion from a Ruby value."); break; default: rb_raise(rb_eTypeError, "Attempting a bad conversion."); break; } } /* * Create a RubyObject from a regular C value (given a dtype). Does not return a VALUE! To get a VALUE, you need to * look at the rval property of what this function returns. */ nm::RubyObject rubyobj_from_cval(void* val, nm::dtype_t dtype) { using namespace nm; switch (dtype) { case BYTE: return RubyObject(*reinterpret_cast<uint8_t*>(val)); case INT8: return RubyObject(*reinterpret_cast<int8_t*>(val)); case INT16: return RubyObject(*reinterpret_cast<int16_t*>(val)); case INT32: return RubyObject(*reinterpret_cast<int32_t*>(val)); case INT64: return RubyObject(*reinterpret_cast<int64_t*>(val)); case FLOAT32: return RubyObject(*reinterpret_cast<float32_t*>(val)); case FLOAT64: return RubyObject(*reinterpret_cast<float64_t*>(val)); case COMPLEX64: return RubyObject(*reinterpret_cast<Complex64*>(val)); case COMPLEX128: return RubyObject(*reinterpret_cast<Complex128*>(val)); case RATIONAL32: return RubyObject(*reinterpret_cast<Rational32*>(val)); case RATIONAL64: return RubyObject(*reinterpret_cast<Rational64*>(val)); case RATIONAL128: return RubyObject(*reinterpret_cast<Rational128*>(val)); default: throw; rb_raise(nm_eDataTypeError, "Conversion to RubyObject requested from unknown/invalid data type (did you try to convert from a VALUE?)"); } return Qnil; } /* * Allocate and return a piece of data of the correct dtype, converted from a * given RubyObject. */ void* rubyobj_to_cval(VALUE val, nm::dtype_t dtype) { size_t size = DTYPE_SIZES[dtype]; NM_CONSERVATIVE(nm_register_value(val)); void* ret_val = NM_ALLOC_N(char, size); rubyval_to_cval(val, dtype, ret_val); NM_CONSERVATIVE(nm_unregister_value(val)); return ret_val; } void nm_init_data() { nm::RubyObject obj(INT2FIX(1)); nm::Rational32 x(obj); nm::Rational64 y(obj); nm::Rational128 z(obj); volatile nm::Complex64 a(obj); volatile nm::Complex128 b(obj); } } // end of extern "C" block <|endoftext|>
<commit_before>#include "clustering/administration/main/json_import.hpp" #include <limits.h> #include <set> #include "errors.hpp" #include <boost/bind.hpp> #include "arch/runtime/thread_pool.hpp" #include "arch/types.hpp" #include "containers/archive/file_stream.hpp" #include "containers/bitset.hpp" #include "http/json.hpp" #include "stl_utils.hpp" csv_to_json_importer_t::csv_to_json_importer_t(std::string separators, std::string filepath) : position_(0), num_ignored_rows_(0) { thread_pool_t::run_in_blocker_pool(boost::bind(&csv_to_json_importer_t::import_json_from_file, this, separators, filepath)); } bool detect_number(const char *s, double *out) { char *endptr; errno = 0; double res = strtod(s, &endptr); if (errno != 0) { return false; } if (endptr == s) { return false; } // Make sure the rest of the string is whitespace. while (isspace(*endptr)) { ++endptr; } if (*endptr == '\0') { *out = res; return true; } return false; } bool csv_to_json_importer_t::next_json(scoped_cJSON_t *out) { guarantee_unreviewed(out->get() == NULL); int64_t num_ignored_rows = 0; try_next_row: if (position_ == rows_.size()) { num_ignored_rows_ += num_ignored_rows; return false; } const std::vector<std::string> &row = rows_[position_]; ++ position_; if (row.size() != column_names_.size()) { ++num_ignored_rows; goto try_next_row; } out->reset(cJSON_CreateObject()); for (size_t i = 0; i < row.size(); ++i) { cJSON *item; double number; if (detect_number(row[i].c_str(), &number)) { item = cJSON_CreateNumber(number); } else { item = cJSON_CreateString(row[i].c_str()); } out->AddItemToObject(column_names_[i].c_str(), item); } num_ignored_rows_ += num_ignored_rows; return true; } bool csv_to_json_importer_t::might_support_primary_key(const std::string &primary_key) { rassert_unreviewed(!primary_key.empty()); return std::find(column_names_.begin(), column_names_.end(), primary_key) != column_names_.end(); } std::vector<std::string> split_buf(const bitset_t &seps, const char *buf, int64_t size) { std::vector<std::string> ret; int64_t p = 0; for (;;) { int64_t i = p; if (i == size) { ret.push_back(std::string(buf + p, buf + i)); break; } else if (buf[i] == '"') { ++i; // TODO: support \" escapes? while (i < size && (buf[i] != '"' || (buf[i] == '"' && i + 1 < size && !seps.test(buf[i + 1])))) { ++i; } if (i == size) { ret.push_back(std::string(buf + p, buf + i)); break; } else if (i + 1 == size) { ret.push_back(std::string(buf + p + 1, buf + i)); break; } else { ret.push_back(std::string(buf + p + 1, buf + i)); rassert_unreviewed(seps.test(buf[i + 1])); p = i + 2; } } else { while (i < size && !seps.test(buf[i])) { ++i; } ret.push_back(std::string(buf + p, buf + i)); if (i == size) { break; } p = i + 1; } } return ret; } void separators_to_bitset(const std::string &separators, bitset_t *out) { rassert_unreviewed(out->count() == 0); for (size_t i = 0; i < separators.size(); ++i) { out->set(static_cast<unsigned char>(separators[i])); } } std::vector<std::string> read_lines_from_file(std::string filepath) { rassert_unreviewed(i_am_in_blocker_pool_thread()); blocking_read_file_stream_t file; bool success = file.init(filepath.c_str()); if (!success) { // TODO: Fail more cleanly. printf("Trouble opening file %s\n", filepath.c_str()); exit(EXIT_FAILURE); } std::vector<char> buf; int64_t size = 0; for (;;) { const int64_t chunksize = 8192; buf.resize(size + chunksize); int64_t res = file.read(buf.data() + size, chunksize); if (res == 0) { break; } if (res == -1) { // TODO: Fail more cleanly. printf("Error when reading file %s.\n", filepath.c_str()); exit(EXIT_FAILURE); } rassert_unreviewed(res > 0); size += res; } buf.resize(size); bitset_t bitset(static_cast<int>(UCHAR_MAX) + 1); separators_to_bitset("\n", &bitset); return split_buf(bitset, buf.data(), size); } std::string rltrim(const std::string &s) { size_t i = 0, j = s.size(); while (i < s.size() && isspace(s[i])) { ++i; } while (j > i && isspace(s[j - 1])) { --j; } return std::string(s.data() + i, s.data() + j); } std::vector<std::string> reprocess_column_names(std::vector<std::string> cols) { // TODO: Avoid allowing super-weird characters in column names like \0. // Trim spaces. for (size_t i = 0; i < cols.size(); ++i) { cols[i] = rltrim(cols[i]); } std::set<std::string> used; for (size_t i = 0; i < cols.size(); ++i) { if (cols[i].empty()) { cols[i] = "unnamed"; } if (used.find(cols[i]) != used.end()) { int suffix = 2; std::string candidate; while (candidate = cols[i] + strprintf("%d", suffix), used.find(candidate) != used.end()) { ++suffix; // If there are 2 billion header fields, it's okay to crash. guarantee_unreviewed(suffix != INT_MAX); } cols[i] = candidate; used.insert(candidate); } else { used.insert(cols[i]); } } rassert_unreviewed(used.size() == cols.size()); return cols; } bool is_empty_line(const std::string &line) { return line.empty(); } void csv_to_json_importer_t::import_json_from_file(std::string separators, std::string filepath) { std::vector<std::string> lines = read_lines_from_file(filepath); lines.erase(std::remove_if(lines.begin(), lines.end(), is_empty_line)); if (lines.size() == 0) { return; } rassert_unreviewed(column_names_.empty()); rassert_unreviewed(rows_.empty()); std::string line0 = lines[0]; if (!line0.empty() && line0[0] == '#') { line0 = std::string(line0.data() + 1, line0.size() - 1); } bitset_t set(1 << CHAR_BIT); separators_to_bitset(separators, &set); std::vector<std::string> header_line = split_buf(set, line0.data(), line0.size()); for (size_t i = 1; i < lines.size(); ++i) { rows_.push_back(split_buf(set, lines[i].data(), lines[i].size())); } column_names_ = reprocess_column_names(header_line); } std::string csv_to_json_importer_t::get_error_information() const { return strprintf("%ld malformed row%s ignored.", num_ignored_rows_, num_ignored_rows_ == 1 ? "" : "s"); } <commit_msg>Reviewed assertions in json_import.cc.<commit_after>#include "clustering/administration/main/json_import.hpp" #include <limits.h> #include <set> #include "errors.hpp" #include <boost/bind.hpp> #include "arch/runtime/thread_pool.hpp" #include "arch/types.hpp" #include "containers/archive/file_stream.hpp" #include "containers/bitset.hpp" #include "http/json.hpp" #include "stl_utils.hpp" csv_to_json_importer_t::csv_to_json_importer_t(std::string separators, std::string filepath) : position_(0), num_ignored_rows_(0) { thread_pool_t::run_in_blocker_pool(boost::bind(&csv_to_json_importer_t::import_json_from_file, this, separators, filepath)); } bool detect_number(const char *s, double *out) { char *endptr; errno = 0; double res = strtod(s, &endptr); if (errno != 0) { return false; } if (endptr == s) { return false; } // Make sure the rest of the string is whitespace. while (isspace(*endptr)) { ++endptr; } if (*endptr == '\0') { *out = res; return true; } return false; } bool csv_to_json_importer_t::next_json(scoped_cJSON_t *out) { guarantee_reviewed(out->get() == NULL); int64_t num_ignored_rows = 0; try_next_row: if (position_ == rows_.size()) { num_ignored_rows_ += num_ignored_rows; return false; } const std::vector<std::string> &row = rows_[position_]; ++ position_; if (row.size() != column_names_.size()) { ++num_ignored_rows; goto try_next_row; } out->reset(cJSON_CreateObject()); for (size_t i = 0; i < row.size(); ++i) { cJSON *item; double number; if (detect_number(row[i].c_str(), &number)) { item = cJSON_CreateNumber(number); } else { item = cJSON_CreateString(row[i].c_str()); } out->AddItemToObject(column_names_[i].c_str(), item); } num_ignored_rows_ += num_ignored_rows; return true; } bool csv_to_json_importer_t::might_support_primary_key(const std::string &primary_key) { guarantee_reviewed(!primary_key.empty()); return std::find(column_names_.begin(), column_names_.end(), primary_key) != column_names_.end(); } std::vector<std::string> split_buf(const bitset_t &seps, const char *buf, int64_t size) { std::vector<std::string> ret; int64_t p = 0; for (;;) { int64_t i = p; if (i == size) { ret.push_back(std::string(buf + p, buf + i)); break; } else if (buf[i] == '"') { ++i; // TODO: support \" escapes? while (i < size && (buf[i] != '"' || (buf[i] == '"' && i + 1 < size && !seps.test(buf[i + 1])))) { ++i; } if (i == size) { ret.push_back(std::string(buf + p, buf + i)); break; } else if (i + 1 == size) { ret.push_back(std::string(buf + p + 1, buf + i)); break; } else { ret.push_back(std::string(buf + p + 1, buf + i)); rassert_reviewed(seps.test(buf[i + 1])); p = i + 2; } } else { while (i < size && !seps.test(buf[i])) { ++i; } ret.push_back(std::string(buf + p, buf + i)); if (i == size) { break; } p = i + 1; } } return ret; } void separators_to_bitset(const std::string &separators, bitset_t *out) { guarantee_reviewed(out->count() == 0); for (size_t i = 0; i < separators.size(); ++i) { out->set(static_cast<unsigned char>(separators[i])); } } std::vector<std::string> read_lines_from_file(std::string filepath) { guarantee_reviewed(i_am_in_blocker_pool_thread()); blocking_read_file_stream_t file; bool success = file.init(filepath.c_str()); if (!success) { // TODO: Fail more cleanly. printf("Trouble opening file %s\n", filepath.c_str()); exit(EXIT_FAILURE); } std::vector<char> buf; int64_t size = 0; for (;;) { const int64_t chunksize = 8192; buf.resize(size + chunksize); int64_t res = file.read(buf.data() + size, chunksize); if (res == 0) { break; } if (res == -1) { // TODO: Fail more cleanly. printf("Error when reading file %s.\n", filepath.c_str()); exit(EXIT_FAILURE); } guarantee_reviewed(res > 0); size += res; } buf.resize(size); bitset_t bitset(static_cast<int>(UCHAR_MAX) + 1); separators_to_bitset("\n", &bitset); return split_buf(bitset, buf.data(), size); } std::string rltrim(const std::string &s) { size_t i = 0, j = s.size(); while (i < s.size() && isspace(s[i])) { ++i; } while (j > i && isspace(s[j - 1])) { --j; } return std::string(s.data() + i, s.data() + j); } std::vector<std::string> reprocess_column_names(std::vector<std::string> cols) { // TODO: Avoid allowing super-weird characters in column names like \0. // Trim spaces. for (size_t i = 0; i < cols.size(); ++i) { cols[i] = rltrim(cols[i]); } std::set<std::string> used; for (size_t i = 0; i < cols.size(); ++i) { if (cols[i].empty()) { cols[i] = "unnamed"; } if (used.find(cols[i]) != used.end()) { int suffix = 2; std::string candidate; while (candidate = cols[i] + strprintf("%d", suffix), used.find(candidate) != used.end()) { ++suffix; // If there are 2 billion header fields, it's okay to crash. guarantee_reviewed(suffix != INT_MAX); } cols[i] = candidate; used.insert(candidate); } else { used.insert(cols[i]); } } guarantee_reviewed(used.size() == cols.size()); return cols; } bool is_empty_line(const std::string &line) { return line.empty(); } void csv_to_json_importer_t::import_json_from_file(std::string separators, std::string filepath) { std::vector<std::string> lines = read_lines_from_file(filepath); lines.erase(std::remove_if(lines.begin(), lines.end(), is_empty_line)); if (lines.size() == 0) { return; } guarantee_reviewed(column_names_.empty()); guarantee_reviewed(rows_.empty()); std::string line0 = lines[0]; if (!line0.empty() && line0[0] == '#') { line0 = std::string(line0.data() + 1, line0.size() - 1); } bitset_t set(1 << CHAR_BIT); separators_to_bitset(separators, &set); std::vector<std::string> header_line = split_buf(set, line0.data(), line0.size()); for (size_t i = 1; i < lines.size(); ++i) { rows_.push_back(split_buf(set, lines[i].data(), lines[i].size())); } column_names_ = reprocess_column_names(header_line); } std::string csv_to_json_importer_t::get_error_information() const { return strprintf("%ld malformed row%s ignored.", num_ignored_rows_, num_ignored_rows_ == 1 ? "" : "s"); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/scoped_ptr.h" #include "base/string_util.h" #include "base/values.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/json_value_serializer.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "googleurl/src/gurl.h" #include "net/base/net_util.h" namespace { static const FilePath::CharType kBaseUrl[] = FILE_PATH_LITERAL("http://localhost:8000/"); static const FilePath::CharType kTestDirectory[] = FILE_PATH_LITERAL("dom_checker/"); static const FilePath::CharType kStartFile[] = FILE_PATH_LITERAL("dom_checker.html"); const wchar_t kRunDomCheckerTest[] = L"run-dom-checker-test"; class DomCheckerTest : public UITest { public: typedef std::list<std::string> ResultsList; typedef std::set<std::string> ResultsSet; DomCheckerTest() { dom_automation_enabled_ = true; enable_file_cookies_ = false; show_window_ = true; launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking); } void RunTest(bool use_http, ResultsList* new_passes, ResultsList* new_failures) { int test_count = 0; ResultsSet expected_failures, current_failures; std::string failures_file = use_http ? "expected_failures-http.txt" : "expected_failures-file.txt"; GetExpectedFailures(failures_file, &expected_failures); RunDomChecker(use_http, &test_count, &current_failures); printf("\nTests run: %d\n", test_count); // Compute the list of new passes and failures. CompareSets(current_failures, expected_failures, new_passes); CompareSets(expected_failures, current_failures, new_failures); } void PrintResults(const ResultsList& new_passes, const ResultsList& new_failures) { PrintResults(new_failures, "new tests failing", true); PrintResults(new_passes, "new tests passing", false); } private: void PrintResults(const ResultsList& results, const char* message, bool add_failure) { if (!results.empty()) { if (add_failure) ADD_FAILURE(); printf("%s:\n", message); ResultsList::const_iterator it = results.begin(); for (; it != results.end(); ++it) printf(" %s\n", it->c_str()); printf("\n"); } } // Find the elements of "b" that are not in "a". void CompareSets(const ResultsSet& a, const ResultsSet& b, ResultsList* only_in_b) { ResultsSet::const_iterator it = b.begin(); for (; it != b.end(); ++it) { if (a.find(*it) == a.end()) only_in_b->push_back(*it); } } // Return the path to the DOM checker directory on the local filesystem. FilePath GetDomCheckerDir() { FilePath test_dir; PathService::Get(chrome::DIR_TEST_DATA, &test_dir); return test_dir.AppendASCII("dom_checker"); } bool ReadExpectedResults(const std::string& failures_file, std::string* results) { FilePath results_path = GetDomCheckerDir(); results_path = results_path.AppendASCII(failures_file); return file_util::ReadFileToString(results_path, results); } void ParseExpectedFailures(const std::string& input, ResultsSet* output) { if (input.empty()) return; std::vector<std::string> tokens; SplitString(input, '\n', &tokens); std::vector<std::string>::const_iterator it = tokens.begin(); for (; it != tokens.end(); ++it) { // Allow comments (lines that start with #). if (it->length() > 0 && it->at(0) != '#') output->insert(*it); } } void GetExpectedFailures(const std::string& failures_file, ResultsSet* expected_failures) { std::string expected_failures_text; bool have_expected_results = ReadExpectedResults(failures_file, &expected_failures_text); ASSERT_TRUE(have_expected_results); ParseExpectedFailures(expected_failures_text, expected_failures); } bool WaitUntilTestCompletes(TabProxy* tab) { return WaitUntilJavaScriptCondition(tab, L"", L"window.domAutomationController.send(automation.IsDone());", 1000, UITest::test_timeout_ms()); } bool GetTestCount(TabProxy* tab, int* test_count) { return tab->ExecuteAndExtractInt(L"", L"window.domAutomationController.send(automation.GetTestCount());", test_count); } bool GetTestsFailed(TabProxy* tab, ResultsSet* tests_failed) { std::wstring json_wide; bool succeeded = tab->ExecuteAndExtractString(L"", L"window.domAutomationController.send(" L" JSON.stringify(automation.GetFailures()));", &json_wide); // Note that we don't use ASSERT_TRUE here (and in some other places) as it // doesn't work inside a function with a return type other than void. EXPECT_TRUE(succeeded); if (!succeeded) return false; std::string json = WideToUTF8(json_wide); JSONStringValueSerializer deserializer(json); scoped_ptr<Value> value(deserializer.Deserialize(NULL)); EXPECT_TRUE(value.get()); if (!value.get()) return false; EXPECT_TRUE(value->IsType(Value::TYPE_LIST)); if (!value->IsType(Value::TYPE_LIST)) return false; ListValue* list_value = static_cast<ListValue*>(value.get()); // The parsed JSON object will be an array of strings, each of which is a // test failure. Add those strings to the results set. ListValue::const_iterator it = list_value->begin(); for (; it != list_value->end(); ++it) { EXPECT_TRUE((*it)->IsType(Value::TYPE_STRING)); if ((*it)->IsType(Value::TYPE_STRING)) { std::string test_name; succeeded = (*it)->GetAsString(&test_name); EXPECT_TRUE(succeeded); if (succeeded) tests_failed->insert(test_name); } } return true; } void RunDomChecker(bool use_http, int* test_count, ResultsSet* tests_failed) { GURL test_url; FilePath::StringType start_file(kStartFile); if (use_http) { FilePath::StringType test_directory(kTestDirectory); FilePath::StringType url_string(kBaseUrl); url_string.append(test_directory); url_string.append(start_file); test_url = GURL(url_string); } else { FilePath test_path = GetDomCheckerDir(); test_path = test_path.Append(start_file); test_url = net::FilePathToFileURL(test_path); } scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); tab->NavigateToURL(test_url); // Wait for the test to finish. ASSERT_TRUE(WaitUntilTestCompletes(tab.get())); // Get the test results. ASSERT_TRUE(GetTestCount(tab.get(), test_count)); ASSERT_TRUE(GetTestsFailed(tab.get(), tests_failed)); ASSERT_GT(*test_count, 0); } DISALLOW_COPY_AND_ASSIGN(DomCheckerTest); }; TEST_F(DomCheckerTest, File) { if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDomCheckerTest)) return; ResultsList new_passes, new_failures; RunTest(false, &new_passes, &new_failures); PrintResults(new_passes, new_failures); } TEST_F(DomCheckerTest, Http) { if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDomCheckerTest)) return; ResultsList new_passes, new_failures; RunTest(true, &new_passes, &new_failures); PrintResults(new_passes, new_failures); } } // namespace <commit_msg>Disable DomCheckerTest.Http due to flakiness.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/scoped_ptr.h" #include "base/string_util.h" #include "base/values.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/json_value_serializer.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "googleurl/src/gurl.h" #include "net/base/net_util.h" namespace { static const FilePath::CharType kBaseUrl[] = FILE_PATH_LITERAL("http://localhost:8000/"); static const FilePath::CharType kTestDirectory[] = FILE_PATH_LITERAL("dom_checker/"); static const FilePath::CharType kStartFile[] = FILE_PATH_LITERAL("dom_checker.html"); const wchar_t kRunDomCheckerTest[] = L"run-dom-checker-test"; class DomCheckerTest : public UITest { public: typedef std::list<std::string> ResultsList; typedef std::set<std::string> ResultsSet; DomCheckerTest() { dom_automation_enabled_ = true; enable_file_cookies_ = false; show_window_ = true; launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking); } void RunTest(bool use_http, ResultsList* new_passes, ResultsList* new_failures) { int test_count = 0; ResultsSet expected_failures, current_failures; std::string failures_file = use_http ? "expected_failures-http.txt" : "expected_failures-file.txt"; GetExpectedFailures(failures_file, &expected_failures); RunDomChecker(use_http, &test_count, &current_failures); printf("\nTests run: %d\n", test_count); // Compute the list of new passes and failures. CompareSets(current_failures, expected_failures, new_passes); CompareSets(expected_failures, current_failures, new_failures); } void PrintResults(const ResultsList& new_passes, const ResultsList& new_failures) { PrintResults(new_failures, "new tests failing", true); PrintResults(new_passes, "new tests passing", false); } private: void PrintResults(const ResultsList& results, const char* message, bool add_failure) { if (!results.empty()) { if (add_failure) ADD_FAILURE(); printf("%s:\n", message); ResultsList::const_iterator it = results.begin(); for (; it != results.end(); ++it) printf(" %s\n", it->c_str()); printf("\n"); } } // Find the elements of "b" that are not in "a". void CompareSets(const ResultsSet& a, const ResultsSet& b, ResultsList* only_in_b) { ResultsSet::const_iterator it = b.begin(); for (; it != b.end(); ++it) { if (a.find(*it) == a.end()) only_in_b->push_back(*it); } } // Return the path to the DOM checker directory on the local filesystem. FilePath GetDomCheckerDir() { FilePath test_dir; PathService::Get(chrome::DIR_TEST_DATA, &test_dir); return test_dir.AppendASCII("dom_checker"); } bool ReadExpectedResults(const std::string& failures_file, std::string* results) { FilePath results_path = GetDomCheckerDir(); results_path = results_path.AppendASCII(failures_file); return file_util::ReadFileToString(results_path, results); } void ParseExpectedFailures(const std::string& input, ResultsSet* output) { if (input.empty()) return; std::vector<std::string> tokens; SplitString(input, '\n', &tokens); std::vector<std::string>::const_iterator it = tokens.begin(); for (; it != tokens.end(); ++it) { // Allow comments (lines that start with #). if (it->length() > 0 && it->at(0) != '#') output->insert(*it); } } void GetExpectedFailures(const std::string& failures_file, ResultsSet* expected_failures) { std::string expected_failures_text; bool have_expected_results = ReadExpectedResults(failures_file, &expected_failures_text); ASSERT_TRUE(have_expected_results); ParseExpectedFailures(expected_failures_text, expected_failures); } bool WaitUntilTestCompletes(TabProxy* tab) { return WaitUntilJavaScriptCondition(tab, L"", L"window.domAutomationController.send(automation.IsDone());", 1000, UITest::test_timeout_ms()); } bool GetTestCount(TabProxy* tab, int* test_count) { return tab->ExecuteAndExtractInt(L"", L"window.domAutomationController.send(automation.GetTestCount());", test_count); } bool GetTestsFailed(TabProxy* tab, ResultsSet* tests_failed) { std::wstring json_wide; bool succeeded = tab->ExecuteAndExtractString(L"", L"window.domAutomationController.send(" L" JSON.stringify(automation.GetFailures()));", &json_wide); // Note that we don't use ASSERT_TRUE here (and in some other places) as it // doesn't work inside a function with a return type other than void. EXPECT_TRUE(succeeded); if (!succeeded) return false; std::string json = WideToUTF8(json_wide); JSONStringValueSerializer deserializer(json); scoped_ptr<Value> value(deserializer.Deserialize(NULL)); EXPECT_TRUE(value.get()); if (!value.get()) return false; EXPECT_TRUE(value->IsType(Value::TYPE_LIST)); if (!value->IsType(Value::TYPE_LIST)) return false; ListValue* list_value = static_cast<ListValue*>(value.get()); // The parsed JSON object will be an array of strings, each of which is a // test failure. Add those strings to the results set. ListValue::const_iterator it = list_value->begin(); for (; it != list_value->end(); ++it) { EXPECT_TRUE((*it)->IsType(Value::TYPE_STRING)); if ((*it)->IsType(Value::TYPE_STRING)) { std::string test_name; succeeded = (*it)->GetAsString(&test_name); EXPECT_TRUE(succeeded); if (succeeded) tests_failed->insert(test_name); } } return true; } void RunDomChecker(bool use_http, int* test_count, ResultsSet* tests_failed) { GURL test_url; FilePath::StringType start_file(kStartFile); if (use_http) { FilePath::StringType test_directory(kTestDirectory); FilePath::StringType url_string(kBaseUrl); url_string.append(test_directory); url_string.append(start_file); test_url = GURL(url_string); } else { FilePath test_path = GetDomCheckerDir(); test_path = test_path.Append(start_file); test_url = net::FilePathToFileURL(test_path); } scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); tab->NavigateToURL(test_url); // Wait for the test to finish. ASSERT_TRUE(WaitUntilTestCompletes(tab.get())); // Get the test results. ASSERT_TRUE(GetTestCount(tab.get(), test_count)); ASSERT_TRUE(GetTestsFailed(tab.get(), tests_failed)); ASSERT_GT(*test_count, 0); } DISALLOW_COPY_AND_ASSIGN(DomCheckerTest); }; TEST_F(DomCheckerTest, File) { if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDomCheckerTest)) return; ResultsList new_passes, new_failures; RunTest(false, &new_passes, &new_failures); PrintResults(new_passes, new_failures); } // TODO(arv): http://code.google.com/p/chromium/issues/detail?id=21321 TEST_F(DomCheckerTest, DISABLED_Http) { if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDomCheckerTest)) return; ResultsList new_passes, new_failures; RunTest(true, &new_passes, &new_failures); PrintResults(new_passes, new_failures); } } // namespace <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkContourModelSetGLMapper2D.h" #include "mitkPlaneGeometry.h" #include "mitkColorProperty.h" #include "mitkProperties.h" #include "mitkContourModelSet.h" #include <vtkLinearTransform.h> #include "mitkContourModel.h" #include "mitkBaseRenderer.h" #include "mitkOverlayManager.h" #include "mitkTextOverlay2D.h" #include "mitkGL.h" mitk::ContourModelGLMapper2DBase::ContourModelGLMapper2DBase() { m_PointNumbersOverlay = mitk::TextOverlay2D::New(); m_ControlPointNumbersOverlay = mitk::TextOverlay2D::New(); } mitk::ContourModelGLMapper2DBase::~ContourModelGLMapper2DBase() { RendererListType::const_iterator iter; for ( iter=m_RendererList.begin(); iter != m_RendererList.end(); ++iter) { (*iter)->GetOverlayManager()->RemoveOverlay( m_PointNumbersOverlay.GetPointer() ); (*iter)->GetOverlayManager()->RemoveOverlay( m_ControlPointNumbersOverlay.GetPointer() ); } m_RendererList.clear(); } void mitk::ContourModelGLMapper2DBase::DrawContour(mitk::ContourModel* renderingContour, mitk::BaseRenderer* renderer) { if ( std::find( m_RendererList.begin(), m_RendererList.end(), renderer ) == m_RendererList.end() ) { m_RendererList.push_back( renderer ); } renderer->GetOverlayManager()->AddOverlay( m_PointNumbersOverlay.GetPointer(), renderer ); m_PointNumbersOverlay->SetVisibility( false, renderer ); renderer->GetOverlayManager()->AddOverlay( m_ControlPointNumbersOverlay.GetPointer(), renderer ); m_ControlPointNumbersOverlay->SetVisibility( false, renderer ); InternalDrawContour( renderingContour, renderer ); } void mitk::ContourModelGLMapper2DBase::InternalDrawContour(mitk::ContourModel* renderingContour, mitk::BaseRenderer* renderer) { if(!renderingContour) return; mitk::DataNode* dataNode = this->GetDataNode(); renderingContour->UpdateOutputInformation(); unsigned int timestep = renderer->GetTimeStep(); if ( !renderingContour->IsEmptyTimeStep(timestep) ) { mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry(); assert(displayGeometry.IsNotNull()); //apply color and opacity read from the PropertyList ApplyColorAndOpacityProperties(renderer); mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty*>(dataNode->GetProperty("contour.color", renderer)); float opacity = 0.5; dataNode->GetFloatProperty("opacity", opacity, renderer); if(colorprop) { //set the color of the contour double red = colorprop->GetColor().GetRed(); double green = colorprop->GetColor().GetGreen(); double blue = colorprop->GetColor().GetBlue(); glColor4f(red, green, blue, opacity); } mitk::ColorProperty::Pointer selectedcolor = dynamic_cast<mitk::ColorProperty*>(dataNode->GetProperty("contour.points.color", renderer)); if(!selectedcolor) { selectedcolor = mitk::ColorProperty::New(1.0,0.0,0.1); } vtkLinearTransform* transform = dataNode->GetVtkTransform(); // ContourModel::OutputType point; mitk::Point3D point; mitk::Point3D p, projected_p; float vtkp[3]; float lineWidth = 3.0; bool drawit=false; bool isHovering = false; dataNode->GetBoolProperty("contour.hovering", isHovering); if (isHovering) dataNode->GetFloatProperty("contour.hovering.width", lineWidth); else dataNode->GetFloatProperty("contour.width", lineWidth); bool showSegments = false; dataNode->GetBoolProperty("contour.segments.show", showSegments); bool showControlPoints = false; dataNode->GetBoolProperty("contour.controlpoints.show", showControlPoints); bool showPoints = false; dataNode->GetBoolProperty("contour.points.show", showPoints); bool showPointsNumbers = false; dataNode->GetBoolProperty("contour.points.text", showPointsNumbers); bool showControlPointsNumbers = false; dataNode->GetBoolProperty("contour.controlpoints.text", showControlPointsNumbers); bool projectmode=false; dataNode->GetVisibility(projectmode, renderer, "contour.project-onto-plane"); mitk::ContourModel::VertexIterator pointsIt = renderingContour->IteratorBegin(timestep); Point2D pt2d; // projected_p in display coordinates Point2D lastPt2d; int index = 0; mitk::ScalarType maxDiff = 0.25; while ( pointsIt != renderingContour->IteratorEnd(timestep) ) { lastPt2d = pt2d; point = (*pointsIt)->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp,p); displayGeometry->Project(p, projected_p); displayGeometry->Map(projected_p, pt2d); displayGeometry->WorldToDisplay(pt2d, pt2d); Vector3D diff=p-projected_p; ScalarType scalardiff = diff.GetNorm(); //project to plane if(projectmode) { drawit=true; } else if(scalardiff<maxDiff)//point is close enough to be drawn { drawit=true; } else { drawit = false; } //draw line if(drawit) { if (showSegments) { //lastPt2d is not valid in first step if( !(pointsIt == renderingContour->IteratorBegin(timestep)) ) { glLineWidth(lineWidth); glBegin (GL_LINES); glVertex2f(pt2d[0], pt2d[1]); glVertex2f(lastPt2d[0], lastPt2d[1]); glEnd(); glLineWidth(1); } } if (showControlPoints) { //draw ontrol points if ((*pointsIt)->IsControlPoint) { float pointsize = 4; Point2D tmp; Vector2D horz,vert; horz[1]=0; vert[0]=0; horz[0]=pointsize; vert[1]=pointsize; glColor3f(selectedcolor->GetColor().GetRed(), selectedcolor->GetColor().GetBlue(), selectedcolor->GetColor().GetGreen()); glLineWidth(1); //a rectangle around the point with the selected color glBegin (GL_LINE_LOOP); tmp=pt2d-horz; glVertex2dv(&tmp[0]); tmp=pt2d+vert; glVertex2dv(&tmp[0]); tmp=pt2d+horz; glVertex2dv(&tmp[0]); tmp=pt2d-vert; glVertex2dv(&tmp[0]); glEnd(); glLineWidth(1); //the actual point in the specified color to see the usual color of the point glColor3f(colorprop->GetColor().GetRed(),colorprop->GetColor().GetGreen(),colorprop->GetColor().GetBlue()); glPointSize(1); glBegin (GL_POINTS); tmp=pt2d; glVertex2dv(&tmp[0]); glEnd (); } } if (showPoints) { float pointsize = 3; Point2D tmp; Vector2D horz,vert; horz[1]=0; vert[0]=0; horz[0]=pointsize; vert[1]=pointsize; glColor3f(0.0, 0.0, 0.0); glLineWidth(1); //a rectangle around the point with the selected color glBegin (GL_LINE_LOOP); tmp=pt2d-horz; glVertex2dv(&tmp[0]); tmp=pt2d+vert; glVertex2dv(&tmp[0]); tmp=pt2d+horz; glVertex2dv(&tmp[0]); tmp=pt2d-vert; glVertex2dv(&tmp[0]); glEnd(); glLineWidth(1); //the actual point in the specified color to see the usual color of the point glColor3f(colorprop->GetColor().GetRed(),colorprop->GetColor().GetGreen(),colorprop->GetColor().GetBlue()); glPointSize(1); glBegin (GL_POINTS); tmp=pt2d; glVertex2dv(&tmp[0]); glEnd (); } if (showPointsNumbers) { std::string l; std::stringstream ss; ss << index; l.append(ss.str()); float rgb[3]; rgb[0] = 0.0; rgb[1] = 0.0; rgb[2] = 0.0; WriteTextWithOverlay( m_PointNumbersOverlay, l.c_str(), rgb, pt2d, renderer ); } if (showControlPointsNumbers && (*pointsIt)->IsControlPoint) { std::string l; std::stringstream ss; ss << index; l.append(ss.str()); float rgb[3]; rgb[0] = 1.0; rgb[1] = 1.0; rgb[2] = 0.0; WriteTextWithOverlay( m_ControlPointNumbersOverlay, l.c_str(), rgb, pt2d, renderer ); } index++; } pointsIt++; }//end while iterate over controlpoints //close contour if necessary if(renderingContour->IsClosed(timestep) && drawit && showSegments) { lastPt2d = pt2d; point = renderingContour->GetVertexAt(0,timestep)->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp,p); displayGeometry->Project(p, projected_p); displayGeometry->Map(projected_p, pt2d); displayGeometry->WorldToDisplay(pt2d, pt2d); glLineWidth(lineWidth); glBegin (GL_LINES); glVertex2f(lastPt2d[0], lastPt2d[1]); glVertex2f( pt2d[0], pt2d[1] ); glEnd(); glLineWidth(1); } //draw selected vertex if exists if(renderingContour->GetSelectedVertex()) { //transform selected vertex point = renderingContour->GetSelectedVertex()->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp,p); displayGeometry->Project(p, projected_p); displayGeometry->Map(projected_p, pt2d); displayGeometry->WorldToDisplay(pt2d, pt2d); Vector3D diff=p-projected_p; ScalarType scalardiff = diff.GetNorm(); //---------------------------------- //draw point if close to plane if(scalardiff<maxDiff) { float pointsize = 5; Point2D tmp; glColor3f(0.0, 1.0, 0.0); glLineWidth(1); //a diamond around the point glBegin (GL_LINE_LOOP); //begin from upper left corner and paint clockwise tmp[0]=pt2d[0]-pointsize; tmp[1]=pt2d[1]+pointsize; glVertex2dv(&tmp[0]); tmp[0]=pt2d[0]+pointsize; tmp[1]=pt2d[1]+pointsize; glVertex2dv(&tmp[0]); tmp[0]=pt2d[0]+pointsize; tmp[1]=pt2d[1]-pointsize; glVertex2dv(&tmp[0]); tmp[0]=pt2d[0]-pointsize; tmp[1]=pt2d[1]-pointsize; glVertex2dv(&tmp[0]); glEnd (); } //------------------------------------ } } } void mitk::ContourModelGLMapper2DBase::WriteTextWithOverlay( TextOverlayPointerType textOverlay, const char* text, float rgb[3], Point2D pt2d, mitk::BaseRenderer* renderer ) { textOverlay->SetText( text ); textOverlay->SetColor( rgb ); textOverlay->SetOpacity( 1 ); textOverlay->SetFontSize( 16 ); textOverlay->SetBoolProperty( "drawShadow", false ); textOverlay->SetVisibility( true, renderer ); } <commit_msg>commented code that causes crashes when closing the application<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkContourModelSetGLMapper2D.h" #include "mitkPlaneGeometry.h" #include "mitkColorProperty.h" #include "mitkProperties.h" #include "mitkContourModelSet.h" #include <vtkLinearTransform.h> #include "mitkContourModel.h" #include "mitkBaseRenderer.h" #include "mitkOverlayManager.h" #include "mitkTextOverlay2D.h" #include "mitkGL.h" mitk::ContourModelGLMapper2DBase::ContourModelGLMapper2DBase() { m_PointNumbersOverlay = mitk::TextOverlay2D::New(); m_ControlPointNumbersOverlay = mitk::TextOverlay2D::New(); } mitk::ContourModelGLMapper2DBase::~ContourModelGLMapper2DBase() { // RendererListType::const_iterator iter; // for ( iter=m_RendererList.begin(); iter != m_RendererList.end(); ++iter) // { // (*iter)->GetOverlayManager()->RemoveOverlay( m_PointNumbersOverlay.GetPointer() ); // (*iter)->GetOverlayManager()->RemoveOverlay( m_ControlPointNumbersOverlay.GetPointer() ); // } // m_RendererList.clear(); } void mitk::ContourModelGLMapper2DBase::DrawContour(mitk::ContourModel* renderingContour, mitk::BaseRenderer* renderer) { if ( std::find( m_RendererList.begin(), m_RendererList.end(), renderer ) == m_RendererList.end() ) { m_RendererList.push_back( renderer ); } renderer->GetOverlayManager()->AddOverlay( m_PointNumbersOverlay.GetPointer(), renderer ); m_PointNumbersOverlay->SetVisibility( false, renderer ); renderer->GetOverlayManager()->AddOverlay( m_ControlPointNumbersOverlay.GetPointer(), renderer ); m_ControlPointNumbersOverlay->SetVisibility( false, renderer ); InternalDrawContour( renderingContour, renderer ); } void mitk::ContourModelGLMapper2DBase::InternalDrawContour(mitk::ContourModel* renderingContour, mitk::BaseRenderer* renderer) { if(!renderingContour) return; mitk::DataNode* dataNode = this->GetDataNode(); renderingContour->UpdateOutputInformation(); unsigned int timestep = renderer->GetTimeStep(); if ( !renderingContour->IsEmptyTimeStep(timestep) ) { mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry(); assert(displayGeometry.IsNotNull()); //apply color and opacity read from the PropertyList ApplyColorAndOpacityProperties(renderer); mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty*>(dataNode->GetProperty("contour.color", renderer)); float opacity = 0.5; dataNode->GetFloatProperty("opacity", opacity, renderer); if(colorprop) { //set the color of the contour double red = colorprop->GetColor().GetRed(); double green = colorprop->GetColor().GetGreen(); double blue = colorprop->GetColor().GetBlue(); glColor4f(red, green, blue, opacity); } mitk::ColorProperty::Pointer selectedcolor = dynamic_cast<mitk::ColorProperty*>(dataNode->GetProperty("contour.points.color", renderer)); if(!selectedcolor) { selectedcolor = mitk::ColorProperty::New(1.0,0.0,0.1); } vtkLinearTransform* transform = dataNode->GetVtkTransform(); // ContourModel::OutputType point; mitk::Point3D point; mitk::Point3D p, projected_p; float vtkp[3]; float lineWidth = 3.0; bool drawit=false; bool isHovering = false; dataNode->GetBoolProperty("contour.hovering", isHovering); if (isHovering) dataNode->GetFloatProperty("contour.hovering.width", lineWidth); else dataNode->GetFloatProperty("contour.width", lineWidth); bool showSegments = false; dataNode->GetBoolProperty("contour.segments.show", showSegments); bool showControlPoints = false; dataNode->GetBoolProperty("contour.controlpoints.show", showControlPoints); bool showPoints = false; dataNode->GetBoolProperty("contour.points.show", showPoints); bool showPointsNumbers = false; dataNode->GetBoolProperty("contour.points.text", showPointsNumbers); bool showControlPointsNumbers = false; dataNode->GetBoolProperty("contour.controlpoints.text", showControlPointsNumbers); bool projectmode=false; dataNode->GetVisibility(projectmode, renderer, "contour.project-onto-plane"); mitk::ContourModel::VertexIterator pointsIt = renderingContour->IteratorBegin(timestep); Point2D pt2d; // projected_p in display coordinates Point2D lastPt2d; int index = 0; mitk::ScalarType maxDiff = 0.25; while ( pointsIt != renderingContour->IteratorEnd(timestep) ) { lastPt2d = pt2d; point = (*pointsIt)->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp,p); displayGeometry->Project(p, projected_p); displayGeometry->Map(projected_p, pt2d); displayGeometry->WorldToDisplay(pt2d, pt2d); Vector3D diff=p-projected_p; ScalarType scalardiff = diff.GetNorm(); //project to plane if(projectmode) { drawit=true; } else if(scalardiff<maxDiff)//point is close enough to be drawn { drawit=true; } else { drawit = false; } //draw line if(drawit) { if (showSegments) { //lastPt2d is not valid in first step if( !(pointsIt == renderingContour->IteratorBegin(timestep)) ) { glLineWidth(lineWidth); glBegin (GL_LINES); glVertex2f(pt2d[0], pt2d[1]); glVertex2f(lastPt2d[0], lastPt2d[1]); glEnd(); glLineWidth(1); } } if (showControlPoints) { //draw ontrol points if ((*pointsIt)->IsControlPoint) { float pointsize = 4; Point2D tmp; Vector2D horz,vert; horz[1]=0; vert[0]=0; horz[0]=pointsize; vert[1]=pointsize; glColor3f(selectedcolor->GetColor().GetRed(), selectedcolor->GetColor().GetBlue(), selectedcolor->GetColor().GetGreen()); glLineWidth(1); //a rectangle around the point with the selected color glBegin (GL_LINE_LOOP); tmp=pt2d-horz; glVertex2dv(&tmp[0]); tmp=pt2d+vert; glVertex2dv(&tmp[0]); tmp=pt2d+horz; glVertex2dv(&tmp[0]); tmp=pt2d-vert; glVertex2dv(&tmp[0]); glEnd(); glLineWidth(1); //the actual point in the specified color to see the usual color of the point glColor3f(colorprop->GetColor().GetRed(),colorprop->GetColor().GetGreen(),colorprop->GetColor().GetBlue()); glPointSize(1); glBegin (GL_POINTS); tmp=pt2d; glVertex2dv(&tmp[0]); glEnd (); } } if (showPoints) { float pointsize = 3; Point2D tmp; Vector2D horz,vert; horz[1]=0; vert[0]=0; horz[0]=pointsize; vert[1]=pointsize; glColor3f(0.0, 0.0, 0.0); glLineWidth(1); //a rectangle around the point with the selected color glBegin (GL_LINE_LOOP); tmp=pt2d-horz; glVertex2dv(&tmp[0]); tmp=pt2d+vert; glVertex2dv(&tmp[0]); tmp=pt2d+horz; glVertex2dv(&tmp[0]); tmp=pt2d-vert; glVertex2dv(&tmp[0]); glEnd(); glLineWidth(1); //the actual point in the specified color to see the usual color of the point glColor3f(colorprop->GetColor().GetRed(),colorprop->GetColor().GetGreen(),colorprop->GetColor().GetBlue()); glPointSize(1); glBegin (GL_POINTS); tmp=pt2d; glVertex2dv(&tmp[0]); glEnd (); } if (showPointsNumbers) { std::string l; std::stringstream ss; ss << index; l.append(ss.str()); float rgb[3]; rgb[0] = 0.0; rgb[1] = 0.0; rgb[2] = 0.0; WriteTextWithOverlay( m_PointNumbersOverlay, l.c_str(), rgb, pt2d, renderer ); } if (showControlPointsNumbers && (*pointsIt)->IsControlPoint) { std::string l; std::stringstream ss; ss << index; l.append(ss.str()); float rgb[3]; rgb[0] = 1.0; rgb[1] = 1.0; rgb[2] = 0.0; WriteTextWithOverlay( m_ControlPointNumbersOverlay, l.c_str(), rgb, pt2d, renderer ); } index++; } pointsIt++; }//end while iterate over controlpoints //close contour if necessary if(renderingContour->IsClosed(timestep) && drawit && showSegments) { lastPt2d = pt2d; point = renderingContour->GetVertexAt(0,timestep)->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp,p); displayGeometry->Project(p, projected_p); displayGeometry->Map(projected_p, pt2d); displayGeometry->WorldToDisplay(pt2d, pt2d); glLineWidth(lineWidth); glBegin (GL_LINES); glVertex2f(lastPt2d[0], lastPt2d[1]); glVertex2f( pt2d[0], pt2d[1] ); glEnd(); glLineWidth(1); } //draw selected vertex if exists if(renderingContour->GetSelectedVertex()) { //transform selected vertex point = renderingContour->GetSelectedVertex()->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp,p); displayGeometry->Project(p, projected_p); displayGeometry->Map(projected_p, pt2d); displayGeometry->WorldToDisplay(pt2d, pt2d); Vector3D diff=p-projected_p; ScalarType scalardiff = diff.GetNorm(); //---------------------------------- //draw point if close to plane if(scalardiff<maxDiff) { float pointsize = 5; Point2D tmp; glColor3f(0.0, 1.0, 0.0); glLineWidth(1); //a diamond around the point glBegin (GL_LINE_LOOP); //begin from upper left corner and paint clockwise tmp[0]=pt2d[0]-pointsize; tmp[1]=pt2d[1]+pointsize; glVertex2dv(&tmp[0]); tmp[0]=pt2d[0]+pointsize; tmp[1]=pt2d[1]+pointsize; glVertex2dv(&tmp[0]); tmp[0]=pt2d[0]+pointsize; tmp[1]=pt2d[1]-pointsize; glVertex2dv(&tmp[0]); tmp[0]=pt2d[0]-pointsize; tmp[1]=pt2d[1]-pointsize; glVertex2dv(&tmp[0]); glEnd (); } //------------------------------------ } } } void mitk::ContourModelGLMapper2DBase::WriteTextWithOverlay( TextOverlayPointerType textOverlay, const char* text, float rgb[3], Point2D pt2d, mitk::BaseRenderer* renderer ) { textOverlay->SetText( text ); textOverlay->SetColor( rgb ); textOverlay->SetOpacity( 1 ); textOverlay->SetFontSize( 16 ); textOverlay->SetBoolProperty( "drawShadow", false ); textOverlay->SetVisibility( true, renderer ); } <|endoftext|>
<commit_before>#include <cassert> #include <unordered_map> #include "IMGFile.h" #include "Compression.h" #include "../Math/Int2.h" #include "../Utilities/Bytes.h" #include "../Utilities/Debug.h" #include "components/vfs/manager.hpp" namespace { // These IMG files are actually headerless/raw files with hardcoded dimensions. const std::unordered_map<std::string, Int2> RawImgOverride = { { "ARENARW.IMG", { 16, 16 } }, { "CITY.IMG", { 16, 11 } }, { "DITHER.IMG", { 16, 50 } }, { "DITHER2.IMG", { 16, 50 } }, { "DUNGEON.IMG", { 14, 8 } }, { "DZTTAV.IMG", { 32, 34 } }, { "NOCAMP.IMG", { 25, 19 } }, { "NOSPELL.IMG", { 25, 19 } }, { "P1.IMG", { 320, 53 } }, { "POPTALK.IMG", { 320, 77 } }, { "S2.IMG", { 320, 36 } }, { "SLIDER.IMG", { 289, 7 } }, { "TOWN.IMG", { 9, 10 } }, { "UPDOWN.IMG", { 8, 16 } }, { "VILLAGE.IMG", { 8, 8 } } }; } IMGFile::IMGFile(const std::string &filename, const Palette *palette) { VFS::IStreamPtr stream = VFS::Manager::get().open(filename.c_str()); Debug::check(stream != nullptr, "IMGFile", "Could not open \"" + filename + "\"."); stream->seekg(0, std::ios::end); const auto fileSize = stream->tellg(); stream->seekg(0, std::ios::beg); std::vector<uint8_t> srcData(fileSize); stream->read(reinterpret_cast<char*>(srcData.data()), srcData.size()); uint16_t xoff, yoff, width, height, flags, len; // Read header data if not raw (this does not include walls). const auto rawOverride = RawImgOverride.find(filename); const bool isRaw = rawOverride != RawImgOverride.end(); if (isRaw) { xoff = 0; yoff = 0; width = rawOverride->second.getX(); height = rawOverride->second.getY(); flags = 0; len = width * height; } else { xoff = Bytes::getLE16(srcData.data()); yoff = Bytes::getLE16(srcData.data() + 2); width = Bytes::getLE16(srcData.data() + 4); height = Bytes::getLE16(srcData.data() + 6); flags = Bytes::getLE16(srcData.data() + 8); len = Bytes::getLE16(srcData.data() + 10); } const int headerSize = 12; // Try and read the IMG's built-in palette if the given palette is null. Palette builtInPalette; const bool useBuiltInPalette = palette == nullptr; if (useBuiltInPalette) { // This code might run even if the IMG doesn't have a palette, because // some IMGs have no header and are not "raw" (like walls, for instance). Debug::check((flags & 0x0100) != 0, "IMGFile", "\"" + filename + "\" does not have a built-in palette."); // Read the palette data and write it to the destination palette. IMGFile::readPalette(srcData.data() + headerSize + len, builtInPalette); } // Choose which palette to use. const Palette &paletteRef = useBuiltInPalette ? builtInPalette : (*palette); // Lambda for setting IMGFile members and constructing the final image. auto makeImage = [this, &paletteRef](int width, int height, const uint8_t *data) { this->width = width; this->height = height; this->pixels = std::unique_ptr<uint32_t>(new uint32_t[width * height]); std::transform(data, data + (width * height), this->pixels.get(), [&paletteRef](uint8_t col) -> uint32_t { return paletteRef[col].toARGB(); }); }; // Decide how to use the data based on whether the IMG uses a raw override. if (isRaw) { // Uncompressed IMG with no header (does not include walls). makeImage(width, height, srcData.data()); } else { // Decode the pixel data according to the IMG type. if ((flags & 0x00FF) == 0) { // Uncompressed IMG with header. makeImage(width, height, srcData.data() + headerSize); } else if ((flags & 0x00FF) == 0x0004) { // Type 4 compression. std::vector<uint8_t> decomp(width * height); Compression::decodeType04(srcData.begin() + headerSize, srcData.begin() + headerSize + len, decomp); // Create 32-bit image. makeImage(width, height, decomp.data()); } else if ((flags & 0x00FF) == 0x0008) { // Type 8 compression. Contains a 2 byte decompressed length after // the header, so skip that (should be equivalent to width * height). std::vector<uint8_t> decomp(width * height); Compression::decodeType08(srcData.begin() + headerSize + 2, srcData.begin() + headerSize + len, decomp); // Create 32-bit image. makeImage(width, height, decomp.data()); } else { // Wall texture (the flags variable is garbage). makeImage(64, 64, srcData.data()); } } } IMGFile::~IMGFile() { } void IMGFile::readPalette(const uint8_t *paletteData, Palette &dstPalette) { // The palette data is 768 bytes, starting after the pixel data ends. // Unlike COL files, embedded palettes are stored with components in // the range of 0...63 rather than 0...255 (this was because old VGA // hardware only had 6-bit DACs, giving a maximum intensity value of // 63, while newer hardware had 8-bit DACs for up to 255. uint8_t r = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63; uint8_t g = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63; uint8_t b = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63; dstPalette[0] = Color(r, g, b, 0); // Remaining are solid, so give them 255 alpha. std::generate(dstPalette.begin() + 1, dstPalette.end(), [&paletteData]() -> Color { uint8_t r = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63; uint8_t g = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63; uint8_t b = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63; return Color(r, g, b, 255); }); } void IMGFile::extractPalette(const std::string &filename, Palette &dstPalette) { VFS::IStreamPtr stream = VFS::Manager::get().open(filename.c_str()); Debug::check(stream != nullptr, "IMGFile", "Could not open \"" + filename + "\"."); stream->seekg(0, std::ios::end); const auto fileSize = stream->tellg(); stream->seekg(0, std::ios::beg); std::vector<uint8_t> srcData(fileSize); stream->read(reinterpret_cast<char*>(srcData.data()), srcData.size()); // No need to check for raw override. All given filenames should point to IMGs // with "built-in" palettes, and none of those IMGs are in the raw override. uint16_t xoff = Bytes::getLE16(srcData.data()); uint16_t yoff = Bytes::getLE16(srcData.data() + 2); uint16_t width = Bytes::getLE16(srcData.data() + 4); uint16_t height = Bytes::getLE16(srcData.data() + 6); uint16_t flags = Bytes::getLE16(srcData.data() + 8); uint16_t len = Bytes::getLE16(srcData.data() + 10); const int headerSize = 12; // Don't try to read a built-in palette is there isn't one. Debug::check((flags & 0x0100) != 0, "IMGFile", "\"" + filename + "\" has no built-in palette to extract."); // Read the palette data and write it to the destination palette. IMGFile::readPalette(srcData.data() + headerSize + len, dstPalette); } int IMGFile::getWidth() const { return this->width; } int IMGFile::getHeight() const { return this->height; } uint32_t *IMGFile::getPixels() const { return this->pixels.get(); } <commit_msg>Fixed some edge cases in IMGFile.<commit_after>#include <unordered_map> #include "IMGFile.h" #include "Compression.h" #include "../Math/Int2.h" #include "../Utilities/Bytes.h" #include "../Utilities/Debug.h" #include "components/vfs/manager.hpp" namespace { // These IMG files are actually headerless/raw files with hardcoded dimensions. const std::unordered_map<std::string, Int2> RawImgOverride = { { "ARENARW.IMG", { 16, 16 } }, { "CITY.IMG", { 16, 11 } }, { "DITHER.IMG", { 16, 50 } }, { "DITHER2.IMG", { 16, 50 } }, { "DUNGEON.IMG", { 14, 8 } }, { "DZTTAV.IMG", { 32, 34 } }, { "NOCAMP.IMG", { 25, 19 } }, { "NOSPELL.IMG", { 25, 19 } }, { "P1.IMG", { 320, 53 } }, { "POPTALK.IMG", { 320, 77 } }, { "S2.IMG", { 320, 36 } }, { "SLIDER.IMG", { 289, 7 } }, { "TOWN.IMG", { 9, 10 } }, { "UPDOWN.IMG", { 8, 16 } }, { "VILLAGE.IMG", { 8, 8 } } }; } IMGFile::IMGFile(const std::string &filename, const Palette *palette) { VFS::IStreamPtr stream = VFS::Manager::get().open(filename.c_str()); Debug::check(stream != nullptr, "IMGFile", "Could not open \"" + filename + "\"."); stream->seekg(0, std::ios::end); const auto fileSize = stream->tellg(); stream->seekg(0, std::ios::beg); std::vector<uint8_t> srcData(fileSize); stream->read(reinterpret_cast<char*>(srcData.data()), srcData.size()); uint16_t xoff, yoff, width, height, flags, len; // Read header data if not raw. Wall IMGs have no header and are 4096 bytes. const auto rawOverride = RawImgOverride.find(filename); const bool isRaw = rawOverride != RawImgOverride.end(); if (isRaw) { xoff = 0; yoff = 0; width = rawOverride->second.getX(); height = rawOverride->second.getY(); flags = 0; len = width * height; } else if (srcData.size() == 4096) { // Some wall IMGs have rows of black (transparent) pixels near the // beginning, so the header would just be zeroes. This is a guess to // try and fix that issue as well as cover all other wall IMGs. xoff = 0; yoff = 0; width = 64; height = 64; flags = 0; len = width * height; } else { // Read header data. xoff = Bytes::getLE16(srcData.data()); yoff = Bytes::getLE16(srcData.data() + 2); width = Bytes::getLE16(srcData.data() + 4); height = Bytes::getLE16(srcData.data() + 6); flags = Bytes::getLE16(srcData.data() + 8); len = Bytes::getLE16(srcData.data() + 10); } const int headerSize = 12; // Try and read the IMG's built-in palette if the given palette is null. Palette builtInPalette; const bool useBuiltInPalette = palette == nullptr; if (useBuiltInPalette) { // This code might run even if the IMG doesn't have a palette, because // some IMGs have no header and are not "raw" (like walls, for instance). Debug::check((flags & 0x0100) != 0, "IMGFile", "\"" + filename + "\" does not have a built-in palette."); // Read the palette data and write it to the destination palette. IMGFile::readPalette(srcData.data() + headerSize + len, builtInPalette); } // Choose which palette to use. const Palette &paletteRef = useBuiltInPalette ? builtInPalette : (*palette); // Lambda for setting IMGFile members and constructing the final image. auto makeImage = [this, &paletteRef](int width, int height, const uint8_t *data) { this->width = width; this->height = height; this->pixels = std::unique_ptr<uint32_t>(new uint32_t[width * height]); std::transform(data, data + (width * height), this->pixels.get(), [&paletteRef](uint8_t col) -> uint32_t { return paletteRef[col].toARGB(); }); }; // Decide how to use the pixel data. if (isRaw) { // Uncompressed IMG with no header (excluding walls). makeImage(width, height, srcData.data()); } else if ((srcData.size() == 4096) && (width == 64) && (height == 64)) { // Wall texture (the flags variable is garbage). makeImage(64, 64, srcData.data()); } else { // Decode the pixel data according to the IMG flags. if ((flags & 0x00FF) == 0) { // Uncompressed IMG with header. makeImage(width, height, srcData.data() + headerSize); } else if ((flags & 0x00FF) == 0x0004) { // Type 4 compression. std::vector<uint8_t> decomp(width * height); Compression::decodeType04(srcData.begin() + headerSize, srcData.begin() + headerSize + len, decomp); // Create 32-bit image. makeImage(width, height, decomp.data()); } else if ((flags & 0x00FF) == 0x0008) { // Type 8 compression. Contains a 2 byte decompressed length after // the header, so skip that (should be equivalent to width * height). std::vector<uint8_t> decomp(width * height); Compression::decodeType08(srcData.begin() + headerSize + 2, srcData.begin() + headerSize + len, decomp); // Create 32-bit image. makeImage(width, height, decomp.data()); } else { Debug::crash("IMGFile", "Unrecognized IMG \"" + filename + "\"."); } } } IMGFile::~IMGFile() { } void IMGFile::readPalette(const uint8_t *paletteData, Palette &dstPalette) { // The palette data is 768 bytes, starting after the pixel data ends. // Unlike COL files, embedded palettes are stored with components in // the range of 0...63 rather than 0...255 (this was because old VGA // hardware only had 6-bit DACs, giving a maximum intensity value of // 63, while newer hardware had 8-bit DACs for up to 255. uint8_t r = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63; uint8_t g = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63; uint8_t b = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63; dstPalette[0] = Color(r, g, b, 0); // Remaining are solid, so give them 255 alpha. std::generate(dstPalette.begin() + 1, dstPalette.end(), [&paletteData]() -> Color { uint8_t r = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63; uint8_t g = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63; uint8_t b = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63; return Color(r, g, b, 255); }); } void IMGFile::extractPalette(const std::string &filename, Palette &dstPalette) { VFS::IStreamPtr stream = VFS::Manager::get().open(filename.c_str()); Debug::check(stream != nullptr, "IMGFile", "Could not open \"" + filename + "\"."); stream->seekg(0, std::ios::end); const auto fileSize = stream->tellg(); stream->seekg(0, std::ios::beg); std::vector<uint8_t> srcData(fileSize); stream->read(reinterpret_cast<char*>(srcData.data()), srcData.size()); // No need to check for raw override. All given filenames should point to IMGs // with "built-in" palettes, and none of those IMGs are in the raw override. uint16_t xoff = Bytes::getLE16(srcData.data()); uint16_t yoff = Bytes::getLE16(srcData.data() + 2); uint16_t width = Bytes::getLE16(srcData.data() + 4); uint16_t height = Bytes::getLE16(srcData.data() + 6); uint16_t flags = Bytes::getLE16(srcData.data() + 8); uint16_t len = Bytes::getLE16(srcData.data() + 10); const int headerSize = 12; // Don't try to read a built-in palette is there isn't one. Debug::check((flags & 0x0100) != 0, "IMGFile", "\"" + filename + "\" has no built-in palette to extract."); // Read the palette data and write it to the destination palette. IMGFile::readPalette(srcData.data() + headerSize + len, dstPalette); } int IMGFile::getWidth() const { return this->width; } int IMGFile::getHeight() const { return this->height; } uint32_t *IMGFile::getPixels() const { return this->pixels.get(); } <|endoftext|>
<commit_before>// // Exponent.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "Exponential.h" Exponential::Exponential(Expression* base, Rational* exponent){ this->type = "exponential"; this->base = base; this->exponent = exponent; this->exde = new Integer(exponent->getDenominator()); if (exde->getValue() != 1) { //if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1 Integer* baseAsInteger = (Integer *) base; base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1); Integer* one = new Integer(1); exponent->setDenominator(one); } this->exnu = new Integer(exponent->getNumerator()); if (canExponentiate()) { exponentiate(); } } Exponential::~Exponential(){ } bool Exponential::canExponentiate() { if(base->type == "euler"){ return false; }else if(base->type == "exponential"){ Exponential* ex = (Exponential *) base; this->exponent->multiply(ex->getExponent()); Integer* numSum = new Integer (1); ex->getExponent()->setNumerator(numSum); return false; // false is returned because the base itself would have already been exponentiated if it were possible }else if(base->type == "integer"){ return true; }else if(base->type == "logarithm"){ return false; }else if(base->type == "nthRoot"){ nthRoot* nr = (nthRoot *) base; Rational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator()); //makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one this->exponent = r; nr->setRoot(1); return false; }else if(base->type == "pi"){ return false; }else if(base->type == "rational"){ Rational* r = (Rational *) base; if (r->geteNumerator()->type == "integer" && r->geteDenominator()->type == "integer") { Exponential* nu = new Exponential(r->geteNumerator(), this->exponent); r->setNumerator(nu); Exponential* de = new Exponential(r->geteDenominator(), this->exponent); r->setDenominator(de); } }else{ cout << "type not recognized" << endl; } return false; } void Exponential::exponentiate(){ if (this->exponent->getNumerator()==0) { Integer* oneInt = new Integer(1); Rational* oneRat = new Rational(1, 1); this->exponent=oneRat; this->base=oneInt; } bool toFlip = false; if (exnu->getValue()<0) { exnu->setValue(exnu->getValue()*-1); toFlip = true; //handles negative exponents } Expression* constantBase = 0; if (base->type == "integer") { //fixed the problem for integers but nothing else Integer *a = (Integer *)base; constantBase = new Integer(a->getValue()); } while (exponent->getNumerator()>1) { base->multiply(constantBase); Integer* one = new Integer(1); exponent->setNumerator(exponent->geteNumerator()->subtract(one)); } if (toFlip) { Integer* one = new Integer(1); Rational* mouse = new Rational(one, base); base = mouse; } } Expression* Exponential::add(Expression* a){ if(a->type == "euler"){ }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (ex->getBase()==this->base) { if (ex->getExponent()==this->exponent) { Integer* two = new Integer(2); this->multiply(two); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ }else if(a->type == "rational"){ }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::subtract(Expression* a){ if(a->type == "euler"){ }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (ex->getBase()==this->base) { if (ex->getExponent()==this->exponent) { Integer* zero = new Integer(0); this->multiply(zero); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ }else if(a->type == "rational"){ }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::multiply(Expression* a){ if(a->type == "euler"){ if (this->base->type == "euler") { if (this->base->getCoefficient() == a->getCoefficient()) { Rational* oneRat = new Rational(1, 1); this->exponent->add(oneRat); } } }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (this->base == ex->getBase()) { this->exponent->add(ex->getExponent()); } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ if (this->base->type == "pi") { if (this->base->getCoefficient() == a->getCoefficient()) { Rational* oneRat = new Rational(1, 1); this->exponent->add(oneRat); } } }else if(a->type == "rational"){ Rational* r = (Rational *) a; r->setNumerator(r->geteNumerator()->multiply(this)); //Error: expected expression return r; }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::divide(Expression* a){ if(a->type == "euler"){ if (this->base->type == "euler") { if (this->base->getCoefficient() == a->getCoefficient()) { Rational* oneRat = new Rational(1, 1); this->exponent->subtract(oneRat); } } }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (this->base == ex->getBase()) { this->exponent->subtract(ex->getExponent()); } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ if (this->base->type == "pi") { if (this->base->getCoefficient() == a->getCoefficient()) { Rational* oneRat = new Rational(1, 1); this->exponent->subtract(oneRat); } } }else if(a->type == "rational"){ Rational* r = (Rational *) a; r->setDenominator(r->geteDenominator()->multiply(this)); //Error: member reference type 'int' is not a pointer return r; }else{ cout << "type not recognized" << endl; } return this; } Rational* Exponential::getExponent() { return exponent; } Expression* Exponential::getBase() { return base; } Integer* Exponential::getExnu() { return exnu; } Integer* Exponential::getExde() { return exde; } void Exponential::setExnu(Integer* n) { exnu = n; } void Exponential::setExde(Integer* n) { exde = n; } void Exponential::setExponent(Rational* e) { exponent = e; } void Exponential::setBase(Expression* e) { base = e; } string Exponential::toString() { stringstream str; if(exponent->getDenominator() == 1){ str << *base << "^" << *exponent->geteNumerator(); }else{ str << *base << "^" << *exponent; } return str.str(); } ostream& Exponential::print(std::ostream& output) const{ output << *base << "^" << "("<< *exponent << ")"; return output; } bool Exponential::canAdd(Expression* b){ //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression) if (this->type == b->type && this->type != "logarithm") { if (this->type == "nthRoot") { } return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canSubtract(Expression* b){ if (this->type == b->type) { return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canMultiply(Expression* b){ if (this->type == b->type) { return true; } else if(this->type == "integer" && b->type == "rational") return true; else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canDivide(Expression* b){ if (this->type == b->type) { return true; } else if(this->type == "integer"){ if( b->type == "rational") return true; } else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } <commit_msg>Fixed for removal of coefficients<commit_after>// // Exponent.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "Exponential.h" Exponential::Exponential(Expression* base, Rational* exponent){ this->type = "exponential"; this->base = base; this->exponent = exponent; this->exde = new Integer(exponent->getDenominator()); if (exde->getValue() != 1) { //if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1 Integer* baseAsInteger = (Integer *) base; base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1); Integer* one = new Integer(1); exponent->setDenominator(one); } this->exnu = new Integer(exponent->getNumerator()); if (canExponentiate()) { exponentiate(); } } Exponential::~Exponential(){ } bool Exponential::canExponentiate() { if(base->type == "euler"){ return false; }else if(base->type == "exponential"){ Exponential* ex = (Exponential *) base; this->exponent->multiply(ex->getExponent()); Integer* numSum = new Integer (1); ex->getExponent()->setNumerator(numSum); return false; // false is returned because the base itself would have already been exponentiated if it were possible }else if(base->type == "integer"){ return true; }else if(base->type == "logarithm"){ return false; }else if(base->type == "nthRoot"){ nthRoot* nr = (nthRoot *) base; Rational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator()); //makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one this->exponent = r; nr->setRoot(1); return false; }else if(base->type == "pi"){ return false; }else if(base->type == "rational"){ Rational* r = (Rational *) base; if (r->geteNumerator()->type == "integer" && r->geteDenominator()->type == "integer") { Exponential* nu = new Exponential(r->geteNumerator(), this->exponent); r->setNumerator(nu); Exponential* de = new Exponential(r->geteDenominator(), this->exponent); r->setDenominator(de); } }else{ cout << "type not recognized" << endl; } return false; } void Exponential::exponentiate(){ if (this->exponent->getNumerator()==0) { Integer* oneInt = new Integer(1); Rational* oneRat = new Rational(1, 1); this->exponent=oneRat; this->base=oneInt; } bool toFlip = false; if (exnu->getValue()<0) { exnu->setValue(exnu->getValue()*-1); toFlip = true; //handles negative exponents } Expression* constantBase = 0; if (base->type == "integer") { //fixed the problem for integers but nothing else Integer *a = (Integer *)base; constantBase = new Integer(a->getValue()); } while (exponent->getNumerator()>1) { base->multiply(constantBase); Integer* one = new Integer(1); exponent->setNumerator(exponent->geteNumerator()->subtract(one)); } if (toFlip) { Integer* one = new Integer(1); Rational* mouse = new Rational(one, base); base = mouse; } } Expression* Exponential::add(Expression* a){ if(a->type == "euler"){ }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (ex->getBase()==this->base) { if (ex->getExponent()==this->exponent) { Integer* two = new Integer(2); this->multiply(two); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ }else if(a->type == "rational"){ }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::subtract(Expression* a){ if(a->type == "euler"){ }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (ex->getBase()==this->base) { if (ex->getExponent()==this->exponent) { Integer* zero = new Integer(0); this->multiply(zero); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ }else if(a->type == "rational"){ }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::multiply(Expression* a){ if(a->type == "euler"){ if (this->base->type == "euler") { Rational* oneRat = new Rational(1, 1); this->exponent->add(oneRat); } }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (this->base == ex->getBase()) { this->exponent->add(ex->getExponent()); } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ if (this->base->type == "pi") { Rational* oneRat = new Rational(1, 1); this->exponent->add(oneRat); } }else if(a->type == "rational"){ Rational* r = (Rational *) a; r->setNumerator(r->geteNumerator()->multiply(this)); //Error: expected expression return r; }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::divide(Expression* a){ if(a->type == "euler"){ if (this->base->type == "euler") { Rational* oneRat = new Rational(1, 1); this->exponent->subtract(oneRat); } }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (this->base == ex->getBase()) { this->exponent->subtract(ex->getExponent()); } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ if (this->base->type == "pi") { Rational* oneRat = new Rational(1, 1); this->exponent->subtract(oneRat); } }else if(a->type == "rational"){ Rational* r = (Rational *) a; r->setDenominator(r->geteDenominator()->multiply(this)); //Error: member reference type 'int' is not a pointer return r; }else{ cout << "type not recognized" << endl; } return this; } Rational* Exponential::getExponent() { return exponent; } Expression* Exponential::getBase() { return base; } Integer* Exponential::getExnu() { return exnu; } Integer* Exponential::getExde() { return exde; } void Exponential::setExnu(Integer* n) { exnu = n; } void Exponential::setExde(Integer* n) { exde = n; } void Exponential::setExponent(Rational* e) { exponent = e; } void Exponential::setBase(Expression* e) { base = e; } string Exponential::toString() { stringstream str; if(exponent->getDenominator() == 1){ str << *base << "^" << *exponent->geteNumerator(); }else{ str << *base << "^" << *exponent; } return str.str(); } ostream& Exponential::print(std::ostream& output) const{ output << *base << "^" << "("<< *exponent << ")"; return output; } bool Exponential::canAdd(Expression* b){ //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression) if (this->type == b->type && this->type != "logarithm") { if (this->type == "nthRoot") { } return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canSubtract(Expression* b){ if (this->type == b->type) { return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canMultiply(Expression* b){ if (this->type == b->type) { return true; } else if(this->type == "integer" && b->type == "rational") return true; else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canDivide(Expression* b){ if (this->type == b->type) { return true; } else if(this->type == "integer"){ if( b->type == "rational") return true; } else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } <|endoftext|>
<commit_before>/* $Id$ */ /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-06 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Common Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin CopyBase.cpp$$ $spell Cpp $$ $section AD Constructor From Base Type: Example and Test$$ $index construct, from base type$$ $index base, convert to AD$$ $index example, construct from base$$ $index test, construct from base$$ $code $verbatim%example/copy_base.cpp%0%// BEGIN PROGRAM%// END PROGRAM%1%$$ $$ $end */ // BEGIN PROGRAM # include <cppad/cppad.hpp> bool CopyBase(void) { bool ok = true; // initialize test result flag using CppAD::AD; // so can use AD in place of CppAD::AD // construct directly from Base where Base is double AD<double> x(1.); // construct from a type that converts to Base where Base is double AD<double> y = 2; // construct from a type that converts to Base where Base = AD<double> AD< AD<double> > z(3); // check that resulting objects are parameters ok &= Parameter(x); ok &= Parameter(y); ok &= Parameter(z); // check values of objects (compare AD<double> with double) ok &= ( x == 1.); ok &= ( y == 2.); ok &= ( Value(z) == 3.); // user constructor through the static_cast template function x = static_cast < AD<double> >( 4 ); z = static_cast < AD< AD<double> > >( 5 ); ok &= ( x == 4. ); ok &= ( Value(z) == 5. ); return ok; } // END PROGRAM <commit_msg>Missing from previous commit. copy_base.cpp: delete this file.<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2010 - 2013 Leap Motion. All rights reserved. Proprietary and confidential. #include "stdafx.h" #include "FactoryTest.h" #include "AutoFactory.h" #include "TestFixtures/SimpleInterface.h" #include <iostream> using namespace std; class ClassWithStaticNew { public: ClassWithStaticNew(bool madeByFactory = false): m_madeByFactory(madeByFactory) {} bool m_madeByFactory; // Factory method, for trivial factory construction: static ClassWithStaticNew* New(void) { return new ClassWithStaticNew(true); } }; TEST_F(FactoryTest, VerifyFactoryCall) { static_assert(has_simple_constructor<ClassWithStaticNew>::value, "Class with default-argument constructor was not correctly detected as such "); static_assert(has_static_new<ClassWithStaticNew>::value, "Class with static allocator was not correctly detected as having one"); // Try to create the static new type: AutoRequired<ClassWithStaticNew> si; // Verify the correct version was called: ASSERT_TRUE(si->m_madeByFactory) << "A factory method was not called on a type which provided a static factory New method"; } TEST_F(FactoryTest, VerifyCanRequireAbstract) { /// <summary> /// Compile-time check to ensure that unconstructable types are identified correctly /// </summary> class ClassWithIntegralCtor: public SimpleInterface { public: ClassWithIntegralCtor(int) {} void Method(void) override {} }; static_assert(!has_simple_constructor<ClassWithIntegralCtor>::value, "A class without a simple constructor was incorrectly identified as having one"); /// <summary> /// A factory for SimpleInterface /// </summary> class SimpleInterfaceFactory: public AutoFactory<SimpleInterface> { public: SimpleInterface* New(void) {return new ClassWithIntegralCtor(1);} }; // Insert the factory type into the context: AutoRequired<SimpleInterfaceFactory> factory; // Now request that the factory be used to create a new SimpleInterface type Autowired<SimpleInterface> si; ASSERT_TRUE(si.IsAutowired()) << "Autowiring a type for which a factory exists did not correctly result in the construction of that type"; // Verify that the type of the constructed item is what we expect, too: ASSERT_EQ(typeid(ClassWithIntegralCtor), typeid(*si)) << "The factory-constructed type was not the type the factory should have constructed."; }<commit_msg>Adding another static assert to validate common ground<commit_after>// Copyright (c) 2010 - 2013 Leap Motion. All rights reserved. Proprietary and confidential. #include "stdafx.h" #include "FactoryTest.h" #include "AutoFactory.h" #include "TestFixtures/SimpleInterface.h" #include <iostream> using namespace std; class ClassWithStaticNew { public: ClassWithStaticNew(bool madeByFactory = false): m_madeByFactory(madeByFactory) {} bool m_madeByFactory; // Factory method, for trivial factory construction: static ClassWithStaticNew* New(void) { return new ClassWithStaticNew(true); } }; TEST_F(FactoryTest, VerifyFactoryCall) { static_assert(has_simple_constructor<ClassWithStaticNew>::value, "Class with default-argument constructor was not correctly detected as such "); static_assert(has_static_new<ClassWithStaticNew>::value, "Class with static allocator was not correctly detected as having one"); // Try to create the static new type: AutoRequired<ClassWithStaticNew> si; // Verify the correct version was called: ASSERT_TRUE(si->m_madeByFactory) << "A factory method was not called on a type which provided a static factory New method"; } TEST_F(FactoryTest, VerifyCanRequireAbstract) { /// <summary> /// Compile-time check to ensure that unconstructable types are identified correctly /// </summary> class ClassWithIntegralCtor: public SimpleInterface { public: ClassWithIntegralCtor(int) {} void Method(void) override {} }; static_assert(!has_simple_constructor<ClassWithIntegralCtor>::value, "A class without a simple constructor was incorrectly identified as having one"); /// <summary> /// A factory for SimpleInterface /// </summary> class SimpleInterfaceFactory: public AutoFactory<SimpleInterface> { public: SimpleInterface* New(void) {return new ClassWithIntegralCtor(1);} }; // Ground validation: static_assert(std::is_same<AutoFactoryBase, typename ground_type_of<SimpleInterfaceFactory>::type>::value, "Interface factory had an unexpected ground type"); // Insert the factory type into the context: AutoRequired<SimpleInterfaceFactory> factory; // Now request that the factory be used to create a new SimpleInterface type Autowired<SimpleInterface> si; ASSERT_TRUE(si.IsAutowired()) << "Autowiring a type for which a factory exists did not correctly result in the construction of that type"; // Verify that the type of the constructed item is what we expect, too: ASSERT_EQ(typeid(ClassWithIntegralCtor), typeid(*si)) << "The factory-constructed type was not the type the factory should have constructed."; }<|endoftext|>
<commit_before>#include <babylon/layers/glow_layer.h> #include <nlohmann/json.hpp> #include <babylon/babylon_stl_util.h> #include <babylon/buffers/vertex_buffer.h> #include <babylon/engines/engine.h> #include <babylon/engines/scene.h> #include <babylon/materials/effect.h> #include <babylon/materials/ieffect_creation_options.h> #include <babylon/materials/material.h> #include <babylon/materials/pbr/pbr_material.h> #include <babylon/materials/standard_material.h> #include <babylon/materials/textures/base_texture.h> #include <babylon/materials/textures/render_target_texture.h> #include <babylon/meshes/abstract_mesh.h> #include <babylon/meshes/mesh.h> #include <babylon/meshes/sub_mesh.h> #include <babylon/postprocesses/blur_post_process.h> #include <babylon/postprocesses/post_process_manager.h> namespace BABYLON { GlowLayer::GlowLayer(const std::string& iName, Scene* scene) : GlowLayer(iName, scene, IGlowLayerOptions{ GlowLayer::DefaultTextureRatio, // mainTextureRatio; std::nullopt, // mainTextureFixedSize 32, // blurKernelSize nullptr, // camera 1, // mainTextureSamples -1 // renderingGroupId }) { } GlowLayer::GlowLayer(const std::string& iName, Scene* scene, const IGlowLayerOptions& options) : EffectLayer{iName, scene} , customEmissiveColorSelector{nullptr} , customEmissiveTextureSelector{nullptr} , blurKernelSize{this, &GlowLayer::get_blurKernelSize, &GlowLayer::set_blurKernelSize} , intensity{this, &GlowLayer::get_intensity, &GlowLayer::set_intensity} , _intensity{1.f} , _horizontalBlurPostprocess1{nullptr} , _verticalBlurPostprocess1{nullptr} , _horizontalBlurPostprocess2{nullptr} , _verticalBlurPostprocess2{nullptr} , _blurTexture1{nullptr} , _blurTexture2{nullptr} { neutralColor = Color4(0.f, 0.f, 0.f, 1.f); // Adapt options _options.mainTextureRatio = options.mainTextureRatio; _options.blurKernelSize = options.blurKernelSize; _options.mainTextureFixedSize = options.mainTextureFixedSize; _options.camera = options.camera; _options.mainTextureSamples = options.mainTextureSamples; // Initialize the layer IEffectLayerOptions effectLayerOptions; effectLayerOptions.alphaBlendingMode = Constants::ALPHA_ADD; effectLayerOptions.camera = _options.camera; effectLayerOptions.mainTextureFixedSize = _options.mainTextureFixedSize; effectLayerOptions.mainTextureRatio = _options.mainTextureRatio; effectLayerOptions.renderingGroupId = _options.renderingGroupId; _init(effectLayerOptions); } GlowLayer::~GlowLayer() = default; void GlowLayer::set_blurKernelSize(float value) { _horizontalBlurPostprocess1->kernel = value; _verticalBlurPostprocess1->kernel = value; _horizontalBlurPostprocess2->kernel = value; _verticalBlurPostprocess2->kernel = value; } float GlowLayer::get_blurKernelSize() const { return _horizontalBlurPostprocess1->kernel(); } void GlowLayer::set_intensity(float value) { _intensity = value; } float GlowLayer::get_intensity() const { return _intensity; } std::string GlowLayer::getEffectName() const { return GlowLayer::EffectName; } EffectPtr GlowLayer::_createMergeEffect() { // Effect IEffectCreationOptions effectCreationOptions; effectCreationOptions.attributes = {VertexBuffer::PositionKind}; effectCreationOptions.uniformBuffersNames = {"offset"}; effectCreationOptions.samplers = {"textureSampler", "textureSampler2"}; effectCreationOptions.defines = "#define EMISSIVE \n"; return _engine->createEffect("glowMapMerge", effectCreationOptions, _scene->getEngine()); } void GlowLayer::_createTextureAndPostProcesses() { auto blurTextureWidth = _mainTextureDesiredSize.width; auto blurTextureHeight = _mainTextureDesiredSize.height; blurTextureWidth = _engine->needPOTTextures() ? Engine::GetExponentOfTwo(blurTextureWidth, _maxSize) : blurTextureWidth; blurTextureHeight = _engine->needPOTTextures() ? Engine::GetExponentOfTwo(blurTextureHeight, _maxSize) : blurTextureHeight; auto textureType = 0u; if (_engine->getCaps().textureHalfFloatRender) { textureType = Constants::TEXTURETYPE_HALF_FLOAT; } else { textureType = Constants::TEXTURETYPE_UNSIGNED_INT; } _blurTexture1 = RenderTargetTexture::New("GlowLayerBlurRTT", RenderTargetSize{blurTextureWidth, blurTextureHeight}, _scene, false, true, textureType); _blurTexture1->wrapU = TextureConstants::CLAMP_ADDRESSMODE; _blurTexture1->wrapV = TextureConstants::CLAMP_ADDRESSMODE; _blurTexture1->updateSamplingMode(TextureConstants::BILINEAR_SAMPLINGMODE); _blurTexture1->renderParticles = false; _blurTexture1->ignoreCameraViewport = true; const auto blurTextureWidth2 = static_cast<int>(std::floor(blurTextureWidth / 2)); const auto blurTextureHeight2 = static_cast<int>(std::floor(blurTextureHeight / 2)); _blurTexture2 = RenderTargetTexture::New("GlowLayerBlurRTT2", RenderTargetSize{blurTextureWidth2, blurTextureHeight2}, _scene, false, true, textureType); _blurTexture2->wrapU = TextureConstants::CLAMP_ADDRESSMODE; _blurTexture2->wrapV = TextureConstants::CLAMP_ADDRESSMODE; _blurTexture2->updateSamplingMode(TextureConstants::BILINEAR_SAMPLINGMODE); _blurTexture2->renderParticles = false; _blurTexture2->ignoreCameraViewport = true; _textures = {_blurTexture1, _blurTexture2}; _horizontalBlurPostprocess1 = BlurPostProcess::New( "GlowLayerHBP1", Vector2(1.f, 0.f), _options.blurKernelSize / 2.f, PostProcessOptions{blurTextureWidth, blurTextureHeight}, nullptr, TextureConstants::BILINEAR_SAMPLINGMODE, _scene->getEngine(), false, textureType); _horizontalBlurPostprocess1->width = blurTextureWidth; _horizontalBlurPostprocess1->height = blurTextureHeight; _horizontalBlurPostprocess1->onApplyObservable.add([this](Effect* effect, EventState /*es*/) { effect->setTexture("textureSampler", _mainTexture); }); _verticalBlurPostprocess1 = BlurPostProcess::New( "GlowLayerVBP1", Vector2(0.f, 1.f), _options.blurKernelSize / 2.f, PostProcessOptions{blurTextureWidth, blurTextureHeight}, nullptr, TextureConstants::BILINEAR_SAMPLINGMODE, _scene->getEngine(), false, textureType); _horizontalBlurPostprocess2 = BlurPostProcess::New( "GlowLayerHBP2", Vector2(1.f, 0.f), _options.blurKernelSize / 2.f, PostProcessOptions{blurTextureWidth2, blurTextureHeight2}, nullptr, TextureConstants::BILINEAR_SAMPLINGMODE, _scene->getEngine(), false, textureType); _horizontalBlurPostprocess2->width = blurTextureWidth2; _horizontalBlurPostprocess2->height = blurTextureHeight2; _horizontalBlurPostprocess2->onApplyObservable.add([this](Effect* effect, EventState /*es*/) { effect->setTexture("textureSampler", _blurTexture1); }); _verticalBlurPostprocess2 = BlurPostProcess::New( "GlowLayerVBP2", Vector2(0.f, 1.f), _options.blurKernelSize / 2.f, PostProcessOptions{blurTextureWidth2, blurTextureHeight2}, nullptr, TextureConstants::BILINEAR_SAMPLINGMODE, _scene->getEngine(), false, textureType); _postProcesses = {_horizontalBlurPostprocess1, _verticalBlurPostprocess1, _horizontalBlurPostprocess2, _verticalBlurPostprocess2}; _postProcesses1 = {_horizontalBlurPostprocess1, _verticalBlurPostprocess1}; _postProcesses2 = {_horizontalBlurPostprocess2, _verticalBlurPostprocess2}; _mainTexture->samples = _options.mainTextureSamples.has_value() ? (*_options.mainTextureSamples) >= 0 ? static_cast<unsigned int>(*_options.mainTextureSamples) : 0 : 0; _mainTexture->onAfterUnbindObservable.add( [this](RenderTargetTexture* /*renderTargetTexture*/, EventState& /*es*/) { auto internalTexture = _blurTexture1->renderTarget(); if (internalTexture) { _scene->postProcessManager->directRender(_postProcesses1, internalTexture, true); auto internalTexture2 = _blurTexture2->renderTarget(); if (internalTexture2) { _scene->postProcessManager->directRender(_postProcesses2, internalTexture2, true); } _engine->unBindFramebuffer(internalTexture2 ? internalTexture2 : internalTexture, true); } }); // Prevent autoClear. for (auto& pp : _postProcesses) { pp->autoClear = false; } } bool GlowLayer::isReady(SubMesh* subMesh, bool useInstances) { auto material = subMesh->getMaterial(); auto mesh = subMesh->getRenderingMesh(); if (!material || !mesh) { return false; } BaseTexturePtr emissiveTexture = nullptr; if (material->type() == Type::STANDARDMATERIAL) { emissiveTexture = std::static_pointer_cast<StandardMaterial>(material)->emissiveTexture(); } return EffectLayer::_isReady(subMesh, useInstances, emissiveTexture); } bool GlowLayer::needStencil() const { return false; } bool GlowLayer::_canRenderMesh(const AbstractMeshPtr& /*mesh*/, const MaterialPtr& /*material*/) const { return true; } void GlowLayer::_internalRender(const EffectPtr& effect) { // Texture effect->setTexture("textureSampler", _blurTexture1); effect->setTexture("textureSampler2", _blurTexture2); effect->setFloat("offset", _intensity); // Cache auto engine = _engine; auto previousStencilBuffer = engine->getStencilBuffer(); // Draw order engine->setStencilBuffer(false); engine->drawElementsType(Material::TriangleFillMode, 0, 6); // Draw order engine->setStencilBuffer(previousStencilBuffer); } void GlowLayer::_setEmissiveTextureAndColor(const MeshPtr& mesh, SubMesh* subMesh, const MaterialPtr& iMaterial) { StandardMaterialPtr material = nullptr; if (iMaterial->type() == Type::STANDARDMATERIAL) { material = std::static_pointer_cast<StandardMaterial>(iMaterial); } auto textureLevel = 1.f; if (customEmissiveTextureSelector) { _emissiveTextureAndColor.texture = customEmissiveTextureSelector(mesh, subMesh, material); } else { if (material) { _emissiveTextureAndColor.texture = material->emissiveTexture(); if (_emissiveTextureAndColor.texture) { textureLevel = _emissiveTextureAndColor.texture->level; } } else { _emissiveTextureAndColor.texture = nullptr; } } if (customEmissiveColorSelector) { customEmissiveColorSelector(mesh, subMesh, material.get(), _emissiveTextureAndColor.color); } else { if (material) { const auto pbrMaterial = std::static_pointer_cast<PBRMaterial>(material); const auto emissiveIntensity = pbrMaterial ? pbrMaterial->emissiveIntensity() : 1.f; textureLevel *= emissiveIntensity; _emissiveTextureAndColor.color.set(material->emissiveColor.r * textureLevel, // material->emissiveColor.g * textureLevel, // material->emissiveColor.b * textureLevel, // material->alpha()); } else { _emissiveTextureAndColor.color.set(neutralColor.r, // neutralColor.g, // neutralColor.b, // neutralColor.a); } } } bool GlowLayer::_shouldRenderMesh(AbstractMesh* mesh) const { return hasMesh(mesh); } void GlowLayer::_addCustomEffectDefines(std::vector<std::string>& defines) { defines.emplace_back("#define GLOW"); } void GlowLayer::addExcludedMesh(Mesh* mesh) { if (!stl_util::contains(_excludedMeshes, mesh->uniqueId)) { _excludedMeshes.emplace_back(mesh->uniqueId); } } void GlowLayer::removeExcludedMesh(Mesh* mesh) { _excludedMeshes.erase(std::remove(_excludedMeshes.begin(), _excludedMeshes.end(), mesh->uniqueId), _excludedMeshes.end()); } void GlowLayer::addIncludedOnlyMesh(Mesh* mesh) { if (!stl_util::contains(_includedOnlyMeshes, mesh->uniqueId)) { _includedOnlyMeshes.emplace_back(mesh->uniqueId); } } void GlowLayer::removeIncludedOnlyMesh(Mesh* mesh) { _includedOnlyMeshes.erase( std::remove(_includedOnlyMeshes.begin(), _includedOnlyMeshes.end(), mesh->uniqueId), _includedOnlyMeshes.end()); } bool GlowLayer::hasMesh(AbstractMesh* mesh) const { if (!EffectLayer::hasMesh(mesh)) { return false; } // Included Mesh if (!_includedOnlyMeshes.empty()) { return stl_util::contains(_includedOnlyMeshes, mesh->uniqueId); } // Excluded Mesh if (!_excludedMeshes.empty()) { return stl_util::contains(_excludedMeshes, mesh->uniqueId); } return true; } bool GlowLayer::_useMeshMaterial(const AbstractMeshPtr& mesh) const { if (_meshesUsingTheirOwnMaterials.empty()) { return false; } return stl_util::contains(_meshesUsingTheirOwnMaterials, mesh->uniqueId); } void GlowLayer::referenceMeshToUseItsOwnMaterial(const AbstractMeshPtr& mesh) { _meshesUsingTheirOwnMaterials.emplace_back(mesh->uniqueId); mesh->onDisposeObservable.add([this, mesh](Node* /*node*/, EventState& /*es*/) -> void { _disposeMesh(static_cast<Mesh*>(mesh.get())); }); } void GlowLayer::unReferenceMeshFromUsingItsOwnMaterial(const AbstractMeshPtr& mesh) { auto index = stl_util::index_of(_meshesUsingTheirOwnMaterials, mesh->uniqueId); while (index >= 0) { stl_util::slice_in_place(_meshesUsingTheirOwnMaterials, index, index + 1); index = stl_util::index_of(_meshesUsingTheirOwnMaterials, mesh->uniqueId); } } void GlowLayer::_disposeMesh(Mesh* mesh) { removeIncludedOnlyMesh(mesh); removeExcludedMesh(mesh); } std::string GlowLayer::getClassName() const { return "GlowLayer"; } json GlowLayer::serialize() const { return nullptr; } GlowLayer* GlowLayer::Parse(const json& /*parsedGlowLayer*/, Scene* /*scene*/, const std::string& /*rootUrl*/) { return nullptr; } } // end of namespace BABYLON <commit_msg>Disabled temporary code and added type casting<commit_after>#include <babylon/layers/glow_layer.h> #include <nlohmann/json.hpp> #include <babylon/babylon_stl_util.h> #include <babylon/buffers/vertex_buffer.h> #include <babylon/engines/engine.h> #include <babylon/engines/scene.h> #include <babylon/materials/effect.h> #include <babylon/materials/ieffect_creation_options.h> #include <babylon/materials/material.h> #include <babylon/materials/pbr/pbr_material.h> #include <babylon/materials/standard_material.h> #include <babylon/materials/textures/base_texture.h> #include <babylon/materials/textures/render_target_texture.h> #include <babylon/meshes/abstract_mesh.h> #include <babylon/meshes/mesh.h> #include <babylon/meshes/sub_mesh.h> #include <babylon/postprocesses/blur_post_process.h> #include <babylon/postprocesses/post_process_manager.h> namespace BABYLON { GlowLayer::GlowLayer(const std::string& iName, Scene* scene) : GlowLayer(iName, scene, IGlowLayerOptions{ GlowLayer::DefaultTextureRatio, // mainTextureRatio; std::nullopt, // mainTextureFixedSize 32, // blurKernelSize nullptr, // camera 1, // mainTextureSamples -1 // renderingGroupId }) { } GlowLayer::GlowLayer(const std::string& iName, Scene* scene, const IGlowLayerOptions& options) : EffectLayer{iName, scene} , customEmissiveColorSelector{nullptr} , customEmissiveTextureSelector{nullptr} , blurKernelSize{this, &GlowLayer::get_blurKernelSize, &GlowLayer::set_blurKernelSize} , intensity{this, &GlowLayer::get_intensity, &GlowLayer::set_intensity} , _intensity{1.f} , _horizontalBlurPostprocess1{nullptr} , _verticalBlurPostprocess1{nullptr} , _horizontalBlurPostprocess2{nullptr} , _verticalBlurPostprocess2{nullptr} , _blurTexture1{nullptr} , _blurTexture2{nullptr} { neutralColor = Color4(0.f, 0.f, 0.f, 1.f); // Adapt options _options.mainTextureRatio = options.mainTextureRatio; _options.blurKernelSize = options.blurKernelSize; _options.mainTextureFixedSize = options.mainTextureFixedSize; _options.camera = options.camera; _options.mainTextureSamples = options.mainTextureSamples; // Initialize the layer IEffectLayerOptions effectLayerOptions; effectLayerOptions.alphaBlendingMode = Constants::ALPHA_ADD; effectLayerOptions.camera = _options.camera; effectLayerOptions.mainTextureFixedSize = _options.mainTextureFixedSize; effectLayerOptions.mainTextureRatio = _options.mainTextureRatio; effectLayerOptions.renderingGroupId = _options.renderingGroupId; _init(effectLayerOptions); } GlowLayer::~GlowLayer() = default; void GlowLayer::set_blurKernelSize(float value) { _horizontalBlurPostprocess1->kernel = value; _verticalBlurPostprocess1->kernel = value; _horizontalBlurPostprocess2->kernel = value; _verticalBlurPostprocess2->kernel = value; } float GlowLayer::get_blurKernelSize() const { return _horizontalBlurPostprocess1->kernel(); } void GlowLayer::set_intensity(float value) { _intensity = value; } float GlowLayer::get_intensity() const { return _intensity; } std::string GlowLayer::getEffectName() const { return GlowLayer::EffectName; } EffectPtr GlowLayer::_createMergeEffect() { // Effect IEffectCreationOptions effectCreationOptions; effectCreationOptions.attributes = {VertexBuffer::PositionKind}; effectCreationOptions.uniformBuffersNames = {"offset"}; effectCreationOptions.samplers = {"textureSampler", "textureSampler2"}; effectCreationOptions.defines = "#define EMISSIVE \n"; return _engine->createEffect("glowMapMerge", effectCreationOptions, _scene->getEngine()); } void GlowLayer::_createTextureAndPostProcesses() { auto blurTextureWidth = _mainTextureDesiredSize.width; auto blurTextureHeight = _mainTextureDesiredSize.height; blurTextureWidth = _engine->needPOTTextures() ? Engine::GetExponentOfTwo(blurTextureWidth, _maxSize) : blurTextureWidth; blurTextureHeight = _engine->needPOTTextures() ? Engine::GetExponentOfTwo(blurTextureHeight, _maxSize) : blurTextureHeight; auto textureType = 0u; if (_engine->getCaps().textureHalfFloatRender) { textureType = Constants::TEXTURETYPE_HALF_FLOAT; } else { textureType = Constants::TEXTURETYPE_UNSIGNED_INT; } _blurTexture1 = RenderTargetTexture::New("GlowLayerBlurRTT", RenderTargetSize{blurTextureWidth, blurTextureHeight}, _scene, false, true, textureType); _blurTexture1->wrapU = TextureConstants::CLAMP_ADDRESSMODE; _blurTexture1->wrapV = TextureConstants::CLAMP_ADDRESSMODE; _blurTexture1->updateSamplingMode(TextureConstants::BILINEAR_SAMPLINGMODE); _blurTexture1->renderParticles = false; _blurTexture1->ignoreCameraViewport = true; const auto blurTextureWidth2 = static_cast<int>(std::floor(blurTextureWidth / 2)); const auto blurTextureHeight2 = static_cast<int>(std::floor(blurTextureHeight / 2)); _blurTexture2 = RenderTargetTexture::New("GlowLayerBlurRTT2", RenderTargetSize{blurTextureWidth2, blurTextureHeight2}, _scene, false, true, textureType); _blurTexture2->wrapU = TextureConstants::CLAMP_ADDRESSMODE; _blurTexture2->wrapV = TextureConstants::CLAMP_ADDRESSMODE; _blurTexture2->updateSamplingMode(TextureConstants::BILINEAR_SAMPLINGMODE); _blurTexture2->renderParticles = false; _blurTexture2->ignoreCameraViewport = true; _textures = {_blurTexture1, _blurTexture2}; _horizontalBlurPostprocess1 = BlurPostProcess::New( "GlowLayerHBP1", Vector2(1.f, 0.f), _options.blurKernelSize / 2.f, PostProcessOptions{blurTextureWidth, blurTextureHeight}, nullptr, TextureConstants::BILINEAR_SAMPLINGMODE, _scene->getEngine(), false, textureType); _horizontalBlurPostprocess1->width = blurTextureWidth; _horizontalBlurPostprocess1->height = blurTextureHeight; _horizontalBlurPostprocess1->onApplyObservable.add([this](Effect* effect, EventState /*es*/) { effect->setTexture("textureSampler", _mainTexture); }); _verticalBlurPostprocess1 = BlurPostProcess::New( "GlowLayerVBP1", Vector2(0.f, 1.f), _options.blurKernelSize / 2.f, PostProcessOptions{blurTextureWidth, blurTextureHeight}, nullptr, TextureConstants::BILINEAR_SAMPLINGMODE, _scene->getEngine(), false, textureType); _horizontalBlurPostprocess2 = BlurPostProcess::New( "GlowLayerHBP2", Vector2(1.f, 0.f), _options.blurKernelSize / 2.f, PostProcessOptions{blurTextureWidth2, blurTextureHeight2}, nullptr, TextureConstants::BILINEAR_SAMPLINGMODE, _scene->getEngine(), false, textureType); _horizontalBlurPostprocess2->width = blurTextureWidth2; _horizontalBlurPostprocess2->height = blurTextureHeight2; _horizontalBlurPostprocess2->onApplyObservable.add([this](Effect* effect, EventState /*es*/) { effect->setTexture("textureSampler", _blurTexture1); }); _verticalBlurPostprocess2 = BlurPostProcess::New( "GlowLayerVBP2", Vector2(0.f, 1.f), _options.blurKernelSize / 2.f, PostProcessOptions{blurTextureWidth2, blurTextureHeight2}, nullptr, TextureConstants::BILINEAR_SAMPLINGMODE, _scene->getEngine(), false, textureType); _postProcesses = {_horizontalBlurPostprocess1, _verticalBlurPostprocess1, _horizontalBlurPostprocess2, _verticalBlurPostprocess2}; _postProcesses1 = {_horizontalBlurPostprocess1, _verticalBlurPostprocess1}; _postProcesses2 = {_horizontalBlurPostprocess2, _verticalBlurPostprocess2}; _mainTexture->samples = _options.mainTextureSamples.has_value() ? (*_options.mainTextureSamples) >= 0 ? static_cast<unsigned int>(*_options.mainTextureSamples) : 0 : 0; #if 0 _mainTexture->onAfterUnbindObservable.add( [this](RenderTargetTexture* /*renderTargetTexture*/, EventState& /*es*/) { auto internalTexture = _blurTexture1->renderTarget(); if (internalTexture) { _scene->postProcessManager->directRender(_postProcesses1, internalTexture, true); auto internalTexture2 = _blurTexture2->renderTarget(); if (internalTexture2) { _scene->postProcessManager->directRender(_postProcesses2, internalTexture2, true); } _engine->unBindFramebuffer(internalTexture2 ? internalTexture2 : internalTexture, true); } }); #endif // Prevent autoClear. for (auto& pp : _postProcesses) { pp->autoClear = false; } } bool GlowLayer::isReady(SubMesh* subMesh, bool useInstances) { auto material = subMesh->getMaterial(); auto mesh = subMesh->getRenderingMesh(); if (!material || !mesh) { return false; } BaseTexturePtr emissiveTexture = nullptr; if (material->type() == Type::STANDARDMATERIAL) { emissiveTexture = std::static_pointer_cast<StandardMaterial>(material)->emissiveTexture(); } return EffectLayer::_isReady(subMesh, useInstances, emissiveTexture); } bool GlowLayer::needStencil() const { return false; } bool GlowLayer::_canRenderMesh(const AbstractMeshPtr& /*mesh*/, const MaterialPtr& /*material*/) const { return true; } void GlowLayer::_internalRender(const EffectPtr& effect) { // Texture effect->setTexture("textureSampler", _blurTexture1); effect->setTexture("textureSampler2", _blurTexture2); effect->setFloat("offset", _intensity); // Cache auto engine = _engine; auto previousStencilBuffer = engine->getStencilBuffer(); // Draw order engine->setStencilBuffer(false); engine->drawElementsType(Material::TriangleFillMode, 0, 6); // Draw order engine->setStencilBuffer(previousStencilBuffer); } void GlowLayer::_setEmissiveTextureAndColor(const MeshPtr& mesh, SubMesh* subMesh, const MaterialPtr& iMaterial) { StandardMaterialPtr material = nullptr; if (iMaterial->type() == Type::STANDARDMATERIAL) { material = std::static_pointer_cast<StandardMaterial>(iMaterial); } auto textureLevel = 1.f; if (customEmissiveTextureSelector) { _emissiveTextureAndColor.texture = customEmissiveTextureSelector(mesh, subMesh, material); } else { if (material) { _emissiveTextureAndColor.texture = material->emissiveTexture(); if (_emissiveTextureAndColor.texture) { textureLevel = _emissiveTextureAndColor.texture->level; } } else { _emissiveTextureAndColor.texture = nullptr; } } if (customEmissiveColorSelector) { customEmissiveColorSelector(mesh, subMesh, material.get(), _emissiveTextureAndColor.color); } else { if (material) { const auto pbrMaterial = std::static_pointer_cast<PBRMaterial>(std::static_pointer_cast<Material>(material)); const auto emissiveIntensity = pbrMaterial ? pbrMaterial->emissiveIntensity() : 1.f; textureLevel *= emissiveIntensity; _emissiveTextureAndColor.color.set(material->emissiveColor.r * textureLevel, // material->emissiveColor.g * textureLevel, // material->emissiveColor.b * textureLevel, // material->alpha()); } else { _emissiveTextureAndColor.color.set(neutralColor.r, // neutralColor.g, // neutralColor.b, // neutralColor.a); } } } bool GlowLayer::_shouldRenderMesh(AbstractMesh* mesh) const { return hasMesh(mesh); } void GlowLayer::_addCustomEffectDefines(std::vector<std::string>& defines) { defines.emplace_back("#define GLOW"); } void GlowLayer::addExcludedMesh(Mesh* mesh) { if (!stl_util::contains(_excludedMeshes, mesh->uniqueId)) { _excludedMeshes.emplace_back(mesh->uniqueId); } } void GlowLayer::removeExcludedMesh(Mesh* mesh) { _excludedMeshes.erase(std::remove(_excludedMeshes.begin(), _excludedMeshes.end(), mesh->uniqueId), _excludedMeshes.end()); } void GlowLayer::addIncludedOnlyMesh(Mesh* mesh) { if (!stl_util::contains(_includedOnlyMeshes, mesh->uniqueId)) { _includedOnlyMeshes.emplace_back(mesh->uniqueId); } } void GlowLayer::removeIncludedOnlyMesh(Mesh* mesh) { _includedOnlyMeshes.erase( std::remove(_includedOnlyMeshes.begin(), _includedOnlyMeshes.end(), mesh->uniqueId), _includedOnlyMeshes.end()); } bool GlowLayer::hasMesh(AbstractMesh* mesh) const { if (!EffectLayer::hasMesh(mesh)) { return false; } // Included Mesh if (!_includedOnlyMeshes.empty()) { return stl_util::contains(_includedOnlyMeshes, mesh->uniqueId); } // Excluded Mesh if (!_excludedMeshes.empty()) { return stl_util::contains(_excludedMeshes, mesh->uniqueId); } return true; } bool GlowLayer::_useMeshMaterial(const AbstractMeshPtr& mesh) const { if (_meshesUsingTheirOwnMaterials.empty()) { return false; } return stl_util::contains(_meshesUsingTheirOwnMaterials, mesh->uniqueId); } void GlowLayer::referenceMeshToUseItsOwnMaterial(const AbstractMeshPtr& mesh) { _meshesUsingTheirOwnMaterials.emplace_back(mesh->uniqueId); mesh->onDisposeObservable.add([this, mesh](Node* /*node*/, EventState & /*es*/) -> void { _disposeMesh(static_cast<Mesh*>(mesh.get())); }); } void GlowLayer::unReferenceMeshFromUsingItsOwnMaterial(const AbstractMeshPtr& mesh) { auto index = stl_util::index_of(_meshesUsingTheirOwnMaterials, mesh->uniqueId); while (index >= 0) { stl_util::slice_in_place(_meshesUsingTheirOwnMaterials, index, index + 1); index = stl_util::index_of(_meshesUsingTheirOwnMaterials, mesh->uniqueId); } } void GlowLayer::_disposeMesh(Mesh* mesh) { removeIncludedOnlyMesh(mesh); removeExcludedMesh(mesh); } std::string GlowLayer::getClassName() const { return "GlowLayer"; } json GlowLayer::serialize() const { return nullptr; } GlowLayer* GlowLayer::Parse(const json& /*parsedGlowLayer*/, Scene* /*scene*/, const std::string& /*rootUrl*/) { return nullptr; } } // end of namespace BABYLON <|endoftext|>
<commit_before>// // CMatrix/instance_method_isApprox.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2014 Rick Yang (rick68 at gmail dot com) // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // #ifndef EIGENJS_CMATRIX_INSTANCE_METHOD_ISAPPROX_HPP #define EIGENJS_CMATRIX_INSTANCE_METHOD_ISAPPROX_HPP namespace EigenJS { EIGENJS_INSTANCE_METHOD(CMatrix, isApprox, { const int& args_length = args.Length(); NanScope(); if (args_length == 1 || args_length == 2) { const T* const& obj = node::ObjectWrap::Unwrap<T>(args.This()); const typename T::value_type& value = **obj; const typename T::value_type& v = value; if (CMatrix::is_cmatrix(args[0])) { const CMatrix* const& rhs_obj = node::ObjectWrap::Unwrap<CMatrix>(args[0]->ToObject()); const typename CMatrix::value_type& rhs_cmatrix = **rhs_obj; const typename CMatrix::value_type& w = rhs_cmatrix; if (T::is_nonconformate_arguments(obj, rhs_obj)) { NanReturnUndefined(); } typedef Eigen::NumTraits<typename T::value_type::Scalar> num_traits; const typename num_traits::Real& prec = args_length == 2 ? args[1]->NumberValue() : num_traits::dummy_precision(); NanReturnValue(NanNew(v.isApprox(w, prec))); } else if (CVector::is_cvector(args[0])) { const CVector* const& rhs_obj = node::ObjectWrap::Unwrap<CVector>(args[0]->ToObject()); const typename CVector::value_type& rhs_cvector = **rhs_obj; const typename CVector::value_type& w = rhs_cvector; if (T::is_nonconformate_arguments(obj, rhs_obj)) { NanReturnUndefined(); } typedef Eigen::NumTraits<typename T::value_type::Scalar> num_traits; const typename num_traits::Real& prec = args_length == 2 ? args[1]->NumberValue() : num_traits::dummy_precision(); NanReturnValue(NanNew(v.isApprox(w, prec))); } else if (CRowVector::is_crowvector(args[0])) { const CRowVector* const& rhs_obj = node::ObjectWrap::Unwrap<CRowVector>(args[0]->ToObject()); const typename CRowVector::value_type& rhs_crowvector = **rhs_obj; const typename CRowVector::value_type& w = rhs_crowvector; if (T::is_nonconformate_arguments(obj, rhs_obj)) { NanReturnUndefined(); } typedef Eigen::NumTraits<typename T::value_type::Scalar> num_traits; const typename num_traits::Real& prec = args_length == 2 ? args[1]->NumberValue() : num_traits::dummy_precision(); NanReturnValue(NanNew(v.isApprox(w, prec))); } } EIGENJS_THROW_ERROR_INVALID_ARGUMENT() NanReturnUndefined(); }) } // namespace EigenJS #endif // EIGENJS_CMATRIX_INSTANCE_METHOD_ISAPPROX_HPP <commit_msg>src: supported CMatrixBlock, CVectorBlock, and CRowVectorBlock<commit_after>// // CMatrix/instance_method_isApprox.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2014 Rick Yang (rick68 at gmail dot com) // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // #ifndef EIGENJS_CMATRIX_INSTANCE_METHOD_ISAPPROX_HPP #define EIGENJS_CMATRIX_INSTANCE_METHOD_ISAPPROX_HPP namespace EigenJS { EIGENJS_INSTANCE_METHOD(CMatrix, isApprox, { const int& args_length = args.Length(); NanScope(); if (args_length == 1 || args_length == 2) { const T* const& obj = node::ObjectWrap::Unwrap<T>(args.This()); const typename T::value_type& value = **obj; const typename T::value_type& v = value; if (CMatrix::is_cmatrix(args[0])) { const CMatrix* const& rhs_obj = node::ObjectWrap::Unwrap<CMatrix>(args[0]->ToObject()); const typename CMatrix::value_type& rhs_cmatrix = **rhs_obj; const typename CMatrix::value_type& w = rhs_cmatrix; if (T::is_nonconformate_arguments(obj, rhs_obj)) { NanReturnUndefined(); } typedef Eigen::NumTraits<typename T::value_type::Scalar> num_traits; const typename num_traits::Real& prec = args_length == 2 ? args[1]->NumberValue() : num_traits::dummy_precision(); NanReturnValue(NanNew(v.isApprox(w, prec))); } else if (CVector::is_cvector(args[0])) { const CVector* const& rhs_obj = node::ObjectWrap::Unwrap<CVector>(args[0]->ToObject()); const typename CVector::value_type& rhs_cvector = **rhs_obj; const typename CVector::value_type& w = rhs_cvector; if (T::is_nonconformate_arguments(obj, rhs_obj)) { NanReturnUndefined(); } typedef Eigen::NumTraits<typename T::value_type::Scalar> num_traits; const typename num_traits::Real& prec = args_length == 2 ? args[1]->NumberValue() : num_traits::dummy_precision(); NanReturnValue(NanNew(v.isApprox(w, prec))); } else if (CRowVector::is_crowvector(args[0])) { const CRowVector* const& rhs_obj = node::ObjectWrap::Unwrap<CRowVector>(args[0]->ToObject()); const typename CRowVector::value_type& rhs_crowvector = **rhs_obj; const typename CRowVector::value_type& w = rhs_crowvector; if (T::is_nonconformate_arguments(obj, rhs_obj)) { NanReturnUndefined(); } typedef Eigen::NumTraits<typename T::value_type::Scalar> num_traits; const typename num_traits::Real& prec = args_length == 2 ? args[1]->NumberValue() : num_traits::dummy_precision(); NanReturnValue(NanNew(v.isApprox(w, prec))); } else if (CMatrixBlock::is_cmatrixblock(args[0])) { const CMatrixBlock* const& rhs_obj = node::ObjectWrap::Unwrap<CMatrixBlock>(args[0]->ToObject()); const typename CMatrixBlock::value_type& rhs_cmatrixblock = **rhs_obj; const typename CMatrixBlock::value_type& w = rhs_cmatrixblock; if (T::is_nonconformate_arguments(obj, rhs_obj)) { NanReturnUndefined(); } typedef Eigen::NumTraits<typename T::value_type::Scalar> num_traits; const typename num_traits::Real& prec = args_length == 2 ? args[1]->NumberValue() : num_traits::dummy_precision(); NanReturnValue(NanNew(v.isApprox(w, prec))); } else if (CVectorBlock::is_cvectorblock(args[0])) { const CVectorBlock* const& rhs_obj = node::ObjectWrap::Unwrap<CVectorBlock>(args[0]->ToObject()); const typename CVectorBlock::value_type& rhs_cvectorblock = **rhs_obj; const typename CVectorBlock::value_type& w = rhs_cvectorblock; if (T::is_nonconformate_arguments(obj, rhs_obj)) { NanReturnUndefined(); } typedef Eigen::NumTraits<typename T::value_type::Scalar> num_traits; const typename num_traits::Real& prec = args_length == 2 ? args[1]->NumberValue() : num_traits::dummy_precision(); NanReturnValue(NanNew(v.isApprox(w, prec))); } else if (CRowVectorBlock::is_crowvectorblock(args[0])) { const CRowVectorBlock* const& rhs_obj = node::ObjectWrap::Unwrap<CRowVectorBlock>(args[0]->ToObject()); const typename CRowVectorBlock::value_type& rhs_crowvectorblock = **rhs_obj; const typename CRowVectorBlock::value_type& w = rhs_crowvectorblock; if (T::is_nonconformate_arguments(obj, rhs_obj)) { NanReturnUndefined(); } typedef Eigen::NumTraits<typename T::value_type::Scalar> num_traits; const typename num_traits::Real& prec = args_length == 2 ? args[1]->NumberValue() : num_traits::dummy_precision(); NanReturnValue(NanNew(v.isApprox(w, prec))); } } EIGENJS_THROW_ERROR_INVALID_ARGUMENT() NanReturnUndefined(); }) } // namespace EigenJS #endif // EIGENJS_CMATRIX_INSTANCE_METHOD_ISAPPROX_HPP <|endoftext|>
<commit_before>// Copyright 2015 Alessio Sclocco <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <ReadData.hpp> namespace AstroData { RingBufferError::RingBufferError(std::string message) : message(message) {} RingBufferError::~RingBufferError() throw () {} const char * RingBufferError::what() const throw() { return message.c_str(); } void readZappedChannels(Observation & observation, const std::string & inputFileName, std::vector< uint8_t > & zappedChannels) { unsigned int nrChannels = 0; std::ifstream input; input.open(inputFileName); while ( !input.eof() ) { unsigned int channel = observation.getNrChannels(); input >> channel; if ( channel < observation.getNrChannels() ) { zappedChannels[channel] = 1; nrChannels++; } } input.close(); observation.setNrZappedChannels(nrChannels); } void readIntegrationSteps(const Observation & observation, const std::string & inputFileName, std::set< unsigned int > & integrationSteps) { std::ifstream input; input.open(inputFileName); while ( !input.eof() ) { unsigned int step = observation.getNrSamplesPerBatch(); input >> step; if ( step < observation.getNrSamplesPerBatch() ) { integrationSteps.insert(step); } } input.close(); } void readPSRDADAHeader(Observation & observation, dada_hdu_t & ringBuffer) throw(RingBufferError) { // Staging variables for the header elements unsigned int uintValue = 0; float floatValue[2] = {0.0f, 0.0f}; // Header string uint64_t headerBytes = 0; char * header = 0; header = ipcbuf_get_next_read(ringBuffer.header_block, &headerBytes); if ( (header == 0) || (headerBytes == 0 ) ) { throw RingBufferError("Impossible to read the PSRDADA header."); } ascii_header_get(header, "SAMPLES_PER_BATCH", "%d", &uintValue); observation.setNrSamplesPerBatch(uintValue); ascii_header_get(header, "CHANNELS", "%d", &uintValue); ascii_header_get(header, "MIN_FREQUENCY", "%f", &floatValue[0]); ascii_header_get(header, "CHANNEL_BANDWIDTH", "%f", &floatValue[1]); observation.setFrequencyRange(1, uintValue, floatValue[0], floatValue[1]); if ( ipcbuf_mark_cleared(ringBuffer.header_block) < 0 ) { throw RingBufferError("Impossible to mark the PSRDADA header as cleared."); } delete header; } } // AstroData <commit_msg>No need to delete "buffer" because it is owned by PSRDADA.<commit_after>// Copyright 2015 Alessio Sclocco <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <ReadData.hpp> namespace AstroData { RingBufferError::RingBufferError(std::string message) : message(message) {} RingBufferError::~RingBufferError() throw () {} const char * RingBufferError::what() const throw() { return message.c_str(); } void readZappedChannels(Observation & observation, const std::string & inputFileName, std::vector< uint8_t > & zappedChannels) { unsigned int nrChannels = 0; std::ifstream input; input.open(inputFileName); while ( !input.eof() ) { unsigned int channel = observation.getNrChannels(); input >> channel; if ( channel < observation.getNrChannels() ) { zappedChannels[channel] = 1; nrChannels++; } } input.close(); observation.setNrZappedChannels(nrChannels); } void readIntegrationSteps(const Observation & observation, const std::string & inputFileName, std::set< unsigned int > & integrationSteps) { std::ifstream input; input.open(inputFileName); while ( !input.eof() ) { unsigned int step = observation.getNrSamplesPerBatch(); input >> step; if ( step < observation.getNrSamplesPerBatch() ) { integrationSteps.insert(step); } } input.close(); } void readPSRDADAHeader(Observation & observation, dada_hdu_t & ringBuffer) throw(RingBufferError) { // Staging variables for the header elements unsigned int uintValue = 0; float floatValue[2] = {0.0f, 0.0f}; // Header string uint64_t headerBytes = 0; char * header = 0; header = ipcbuf_get_next_read(ringBuffer.header_block, &headerBytes); if ( (header == 0) || (headerBytes == 0 ) ) { throw RingBufferError("Impossible to read the PSRDADA header."); } ascii_header_get(header, "SAMPLES_PER_BATCH", "%d", &uintValue); observation.setNrSamplesPerBatch(uintValue); ascii_header_get(header, "CHANNELS", "%d", &uintValue); ascii_header_get(header, "MIN_FREQUENCY", "%f", &floatValue[0]); ascii_header_get(header, "CHANNEL_BANDWIDTH", "%f", &floatValue[1]); observation.setFrequencyRange(1, uintValue, floatValue[0], floatValue[1]); if ( ipcbuf_mark_cleared(ringBuffer.header_block) < 0 ) { throw RingBufferError("Impossible to mark the PSRDADA header as cleared."); } } } // AstroData <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "ComposeDefaultKey.h" /* system headers */ #include <iostream> #include <vector> #include <string> /* common implementation headers */ #include "BzfEvent.h" #include "RemotePlayer.h" #include "KeyManager.h" #include "AutoCompleter.h" #include "BZDBCache.h" #include "AnsiCodes.h" #include "TextUtils.h" /* local implementation headers */ #include "LocalPlayer.h" #include "World.h" #include "HUDRenderer.h" #include "Roster.h" /* FIXME -- pulled from player.h */ void addMessage(const Player* player, const std::string& msg, int mode = 3, bool highlight=false, const char* oldColor=NULL); extern char messageMessage[PlayerIdPLen + MessageLen]; #define MAX_MESSAGE_HISTORY (20) extern HUDRenderer *hud; extern ServerLink* serverLink; extern DefaultCompleter completer; void selectNextRecipient (bool forward, bool robotIn); MessageQueue messageHistory; unsigned int messageHistoryIndex = 0; void printout(const std::string& name, void*) { std::cout << name << " = " << BZDB.get(name) << std::endl; } void listSetVars(const std::string& name, void*) { char message[MessageLen]; if (BZDB.getPermission(name) == StateDatabase::Locked) { if (BZDBCache::colorful) { sprintf(message, "/set %s%s %s%f %s%s", ColorStrings[RedColor].c_str(), name.c_str(), ColorStrings[GreenColor].c_str(), BZDB.eval(name), ColorStrings[BlueColor].c_str(), BZDB.get(name).c_str()); } else { sprintf(message, "/set %s <%f> %s", name.c_str(), BZDB.eval(name), BZDB.get(name).c_str()); } addMessage(LocalPlayer::getMyTank(), message, 2); } } bool ComposeDefaultKey::keyPress(const BzfKeyEvent& key) { bool sendIt; LocalPlayer *myTank = LocalPlayer::getMyTank(); if (KEYMGR.get(key, true) == "jump") { // jump while typing myTank->setJump(); } if (myTank->getInputMethod() != LocalPlayer::Keyboard) { if ((key.button == BzfKeyEvent::Up) || (key.button == BzfKeyEvent::Down)) return true; } switch (key.ascii) { case 3: // ^C case 27: // escape // case 127: // delete sendIt = false; // finished composing -- don't send break; case 4: // ^D case 13: // return sendIt = true; break; case 6: // ^F if (key.shift == BzfKeyEvent::ControlKey) { return true; } else { return false; } break; default: return false; } if (sendIt) { std::string message = hud->getComposeString(); if (message.length() > 0) { const char* silence = message.c_str(); if (strncmp(silence, "SILENCE", 7) == 0) { Player *loudmouth = getPlayerByName(silence + 8); if (loudmouth) { silencePlayers.push_back(silence + 8); std::string message = "Silenced "; message += (silence + 8); addMessage(NULL, message); } } else if (strncmp(silence, "DUMP", 4) == 0) { BZDB.iterate(printout, NULL); } else if (strncmp(silence, "UNSILENCE", 9) == 0) { Player *loudmouth = getPlayerByName(silence + 10); if (loudmouth) { std::vector<std::string>::iterator it = silencePlayers.begin(); for (; it != silencePlayers.end(); it++) { if (*it == silence + 10) { silencePlayers.erase(it); std::string message = "Unsilenced "; message += (silence + 10); addMessage(NULL, message); break; } } } } else if (strncmp(silence, "SAVEWORLD", 9) == 0) { std::string path = silence + 10; if (World::getWorld()->writeWorld(path)) { addMessage(NULL, "World Saved"); } else { addMessage(NULL, "Invalid file name specified"); } } else if (message == "/set") { BZDB.iterate(listSetVars, NULL); #ifdef DEBUG } else if (strncmp(silence, "/localset", 9) == 0) { std::string params = silence + 9; std::vector<std::string> tokens = TextUtils::tokenize(params, " ", 2); if (tokens.size() == 2) { if (!(BZDB.getPermission(tokens[0]) == StateDatabase::Server)) { BZDB.setPersistent(tokens[0], BZDB.isPersistent(tokens[0])); BZDB.set(tokens[0], tokens[1]); std::string msg = "/localset " + tokens[0] + " " + tokens[1]; addMessage(NULL, msg); } } #endif } else { int i, mhLen = messageHistory.size(); for (i = 0; i < mhLen; i++) { if (messageHistory[i] == message) { messageHistory.erase(messageHistory.begin() + i); messageHistory.push_front(message); break; } } if (i == mhLen) { if (mhLen >= MAX_MESSAGE_HISTORY) { messageHistory.pop_back(); } messageHistory.push_front(message); } char messageBuffer[MessageLen]; memset(messageBuffer, 0, MessageLen); strncpy(messageBuffer, message.c_str(), MessageLen); nboPackString(messageMessage + PlayerIdPLen, messageBuffer, MessageLen); serverLink->send(MsgMessage, sizeof(messageMessage), messageMessage); } } } messageHistoryIndex = 0; hud->setComposing(std::string()); HUDui::setDefaultKey(NULL); return true; } bool ComposeDefaultKey::keyRelease(const BzfKeyEvent& key) { LocalPlayer *myTank = LocalPlayer::getMyTank(); if (myTank->getInputMethod() != LocalPlayer::Keyboard) { if (key.button == BzfKeyEvent::Up) { if (messageHistoryIndex < messageHistory.size()) { hud->setComposeString(messageHistory[messageHistoryIndex]); messageHistoryIndex++; } else hud->setComposeString(std::string()); return true; } else if (key.button == BzfKeyEvent::Down) { if (messageHistoryIndex > 0){ messageHistoryIndex--; hud->setComposeString(messageHistory[messageHistoryIndex]); } else hud->setComposeString(std::string()); return true; } else if ((key.shift == BzfKeyEvent::ShiftKey || (hud->getComposeString().length() == 0)) && (key.button == BzfKeyEvent::Left || key.button == BzfKeyEvent::Right)) { // exclude robot from private message recipient. // No point sending messages to robot (now) selectNextRecipient(key.button != BzfKeyEvent::Left, false); const Player *recipient = myTank->getRecipient(); if (recipient) { void* buf = messageMessage; buf = nboPackUByte(buf, recipient->getId()); std::string composePrompt = "Send to "; composePrompt += recipient->getCallSign(); composePrompt += ": "; hud->setComposing(composePrompt); } return false; } else if (((key.shift == 0) && (key.button == BzfKeyEvent::F2)) || ((key.shift == BzfKeyEvent::ControlKey) && (key.ascii == 6))) { // auto completion (F2 or ^F) std::string line1 = hud->getComposeString(); int lastSpace = line1.find_last_of(" \t"); std::string line2 = line1.substr(0, lastSpace+1); line2 += completer.complete(line1.substr(lastSpace+1)); hud->setComposeString(line2); } } return keyPress(key); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>^F doesn't need a ControlKey check<commit_after>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "ComposeDefaultKey.h" /* system headers */ #include <iostream> #include <vector> #include <string> /* common implementation headers */ #include "BzfEvent.h" #include "RemotePlayer.h" #include "KeyManager.h" #include "AutoCompleter.h" #include "BZDBCache.h" #include "AnsiCodes.h" #include "TextUtils.h" /* local implementation headers */ #include "LocalPlayer.h" #include "World.h" #include "HUDRenderer.h" #include "Roster.h" /* FIXME -- pulled from player.h */ void addMessage(const Player* player, const std::string& msg, int mode = 3, bool highlight=false, const char* oldColor=NULL); extern char messageMessage[PlayerIdPLen + MessageLen]; #define MAX_MESSAGE_HISTORY (20) extern HUDRenderer *hud; extern ServerLink* serverLink; extern DefaultCompleter completer; void selectNextRecipient (bool forward, bool robotIn); MessageQueue messageHistory; unsigned int messageHistoryIndex = 0; void printout(const std::string& name, void*) { std::cout << name << " = " << BZDB.get(name) << std::endl; } void listSetVars(const std::string& name, void*) { char message[MessageLen]; if (BZDB.getPermission(name) == StateDatabase::Locked) { if (BZDBCache::colorful) { sprintf(message, "/set %s%s %s%f %s%s", ColorStrings[RedColor].c_str(), name.c_str(), ColorStrings[GreenColor].c_str(), BZDB.eval(name), ColorStrings[BlueColor].c_str(), BZDB.get(name).c_str()); } else { sprintf(message, "/set %s <%f> %s", name.c_str(), BZDB.eval(name), BZDB.get(name).c_str()); } addMessage(LocalPlayer::getMyTank(), message, 2); } } bool ComposeDefaultKey::keyPress(const BzfKeyEvent& key) { bool sendIt; LocalPlayer *myTank = LocalPlayer::getMyTank(); if (KEYMGR.get(key, true) == "jump") { // jump while typing myTank->setJump(); } if (myTank->getInputMethod() != LocalPlayer::Keyboard) { if ((key.button == BzfKeyEvent::Up) || (key.button == BzfKeyEvent::Down)) return true; } switch (key.ascii) { case 3: // ^C case 27: // escape // case 127: // delete sendIt = false; // finished composing -- don't send break; case 4: // ^D case 13: // return sendIt = true; break; case 6: // ^F return true; break; default: return false; } if (sendIt) { std::string message = hud->getComposeString(); if (message.length() > 0) { const char* silence = message.c_str(); if (strncmp(silence, "SILENCE", 7) == 0) { Player *loudmouth = getPlayerByName(silence + 8); if (loudmouth) { silencePlayers.push_back(silence + 8); std::string message = "Silenced "; message += (silence + 8); addMessage(NULL, message); } } else if (strncmp(silence, "DUMP", 4) == 0) { BZDB.iterate(printout, NULL); } else if (strncmp(silence, "UNSILENCE", 9) == 0) { Player *loudmouth = getPlayerByName(silence + 10); if (loudmouth) { std::vector<std::string>::iterator it = silencePlayers.begin(); for (; it != silencePlayers.end(); it++) { if (*it == silence + 10) { silencePlayers.erase(it); std::string message = "Unsilenced "; message += (silence + 10); addMessage(NULL, message); break; } } } } else if (strncmp(silence, "SAVEWORLD", 9) == 0) { std::string path = silence + 10; if (World::getWorld()->writeWorld(path)) { addMessage(NULL, "World Saved"); } else { addMessage(NULL, "Invalid file name specified"); } } else if (message == "/set") { BZDB.iterate(listSetVars, NULL); #ifdef DEBUG } else if (strncmp(silence, "/localset", 9) == 0) { std::string params = silence + 9; std::vector<std::string> tokens = TextUtils::tokenize(params, " ", 2); if (tokens.size() == 2) { if (!(BZDB.getPermission(tokens[0]) == StateDatabase::Server)) { BZDB.setPersistent(tokens[0], BZDB.isPersistent(tokens[0])); BZDB.set(tokens[0], tokens[1]); std::string msg = "/localset " + tokens[0] + " " + tokens[1]; addMessage(NULL, msg); } } #endif } else { int i, mhLen = messageHistory.size(); for (i = 0; i < mhLen; i++) { if (messageHistory[i] == message) { messageHistory.erase(messageHistory.begin() + i); messageHistory.push_front(message); break; } } if (i == mhLen) { if (mhLen >= MAX_MESSAGE_HISTORY) { messageHistory.pop_back(); } messageHistory.push_front(message); } char messageBuffer[MessageLen]; memset(messageBuffer, 0, MessageLen); strncpy(messageBuffer, message.c_str(), MessageLen); nboPackString(messageMessage + PlayerIdPLen, messageBuffer, MessageLen); serverLink->send(MsgMessage, sizeof(messageMessage), messageMessage); } } } messageHistoryIndex = 0; hud->setComposing(std::string()); HUDui::setDefaultKey(NULL); return true; } bool ComposeDefaultKey::keyRelease(const BzfKeyEvent& key) { LocalPlayer *myTank = LocalPlayer::getMyTank(); if (myTank->getInputMethod() != LocalPlayer::Keyboard) { if (key.button == BzfKeyEvent::Up) { if (messageHistoryIndex < messageHistory.size()) { hud->setComposeString(messageHistory[messageHistoryIndex]); messageHistoryIndex++; } else hud->setComposeString(std::string()); return true; } else if (key.button == BzfKeyEvent::Down) { if (messageHistoryIndex > 0){ messageHistoryIndex--; hud->setComposeString(messageHistory[messageHistoryIndex]); } else hud->setComposeString(std::string()); return true; } else if ((key.shift == BzfKeyEvent::ShiftKey || (hud->getComposeString().length() == 0)) && (key.button == BzfKeyEvent::Left || key.button == BzfKeyEvent::Right)) { // exclude robot from private message recipient. // No point sending messages to robot (now) selectNextRecipient(key.button != BzfKeyEvent::Left, false); const Player *recipient = myTank->getRecipient(); if (recipient) { void* buf = messageMessage; buf = nboPackUByte(buf, recipient->getId()); std::string composePrompt = "Send to "; composePrompt += recipient->getCallSign(); composePrompt += ": "; hud->setComposing(composePrompt); } return false; } else if (((key.shift == 0) && (key.button == BzfKeyEvent::F2)) || (key.ascii == 6)) { // auto completion (F2 or ^F) std::string line1 = hud->getComposeString(); int lastSpace = line1.find_last_of(" \t"); std::string line2 = line1.substr(0, lastSpace+1); line2 += completer.complete(line1.substr(lastSpace+1)); hud->setComposeString(line2); } } return keyPress(key); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include "testapp.hpp" #include "testwindow.hpp" #include <time.h> #include <iostream> #include <string> bool TestNookApp::run() { const struct timespec tenthsec = {0, 100000000} ; std::string strfilefb("/dev/graphics/fb0") ; std::string strRefresh("/sys/class/graphics/fb0/epd_refresh") ; if (!init_display(strfilefb,strRefresh)){ std::cerr << "Cannot open display " << strfilefb << std::endl; return false ; } TestNookWnd wnd ; std::cout << "Creating window, width: " << m_fbw << ", height: " << m_fbh << std::endl ; if (!wnd.create(0,0,m_fbw, m_fbh)){ std::cerr << "Cannot create window\n"; return false ; } register_window(wnd) ; while(1){ NookWindow::state s = get_active_window()->get_state() ; bool bFull = s == NookWindow::verydirty ; if (s != NookWindow::clean){ get_active_window()->redraw(); std::cout << "write_to_nook(get_active_window()->canvas)\n" ; write_to_nook(get_active_window()->canvas, bFull); } nanosleep(&tenthsec,NULL) ; get_active_window()->tick() ; } } int main() { TestNookApp app ; bool ret = app.run() ; std::cout << "Application exit: " << ret << std::endl ; return 0; } <commit_msg>Added test app<commit_after>#include "testapp.hpp" #include "testwindow.hpp" #include <time.h> #include <iostream> #include <string> bool TestNookApp::run() { const struct timespec tenthsec = {0, 100000000} ; std::string strfilefb("/dev/graphics/fb0") ; std::string strRefresh("/sys/class/graphics/fb0/epd_refresh") ; if (!init_display(strfilefb,strRefresh)){ std::cerr << "Cannot open display " << strfilefb << std::endl; return false ; } if (!init_inputs("/dev/input")){ std::cerr << "Failed to initialise the input events\n" ; return false ; } TestNookWnd wnd ; std::cout << "Creating window, width: " << m_fbw << ", height: " << m_fbh << std::endl ; if (!wnd.create(0,0,m_fbw, m_fbh)){ std::cerr << "Cannot create window\n"; return false ; } register_window(wnd) ; while(1){ dispatch_app_events() ; nanosleep(&tenthsec,NULL) ; } } int main() { TestNookApp app ; bool ret = app.run() ; std::cout << "Application exit: " << ret << std::endl ; return 0; } <|endoftext|>
<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2002 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <gadget/gadgetConfig.h> #include <vpr/Util/FileUtils.h> #include <jccl/Config/ConfigChunk.h> #include <gadget/Util/Debug.h> #include <gadget/Devices/Sim/SimGloveGesture.h> namespace gadget { /** * Constructs the SimGloveGesture. * Set the keyboard key pairs. * Load the sample file. * Trim the smallest so they are same length. * Find/Set pos proxy for glove. */ bool SimGloveGesture::config(jccl::ConfigChunkPtr chunk) { if((!GloveGesture::config(chunk)) || (!SimInput::config(chunk))) return false; mCurGesture = 0; // We are in no gesture yet std::vector<jccl::ConfigChunkPtr> key_list; int key_count = chunk->getNum("keyPairs"); for ( int i = 0; i < key_count; ++i ) { key_list.push_back(chunk->getProperty<jccl::ConfigChunkPtr>("keyPairs", i)); } mSimKeys = readKeyList(key_list); // Get sample filename std::string sample_file = chunk->getProperty<std::string>("trainedFilename"); loadTrainedFile(vpr::replaceEnvVars(sample_file)); // Trim the lengths unsigned int num_gestures = getNumGestures(); while(num_gestures < mSimKeys.size()) // If we have to many keys { mSimKeys.pop_back(); vprDEBUG(gadgetDBG_INPUT_MGR,1) << "vjSimGloveGesture: Not enough gestures. Trimming" << std::endl << vprDEBUG_FLUSH; } // Find pos proxy std::string glove_pos_proxy = chunk->getProperty<std::string>("glovePos"); // Get the name of the pos_proxy if(glove_pos_proxy == std::string("")) { vprDEBUG(gadgetDBG_INPUT_MGR,0) << clrOutNORM(clrRED, "ERROR:") << " SimGloveGesture has no posProxy." << std::endl << vprDEBUG_FLUSH; return false; } // init glove proxy interface /* int proxy_index = Kernel::instance()->getInputManager()->getProxyIndex(glove_pos_proxy); if(proxy_index != -1) mGlovePos[0] = Kernel::instance()->getInputManager()->getPosProxy(proxy_index); else vprDEBUG(gadgetDBG_INPUT_MGR,0) << clrOutNORM(clrRED, "ERROR:") << " SimGloveGesture::CyberGlove: Can't find posProxy." << std::endl << std::endl << vprDEBUG_FLUSH; */ // Set the indexes to defaults //resetIndexes(); return true; } /** * Gets the digital data for the given devNum. * Returns digital 0 or 1, if devNum makes sense. * Returns -1 if function fails or if devNum is out of range. * * @note If devNum is out of range, function will fail, possibly issueing * an error to a log or console - but will not ASSERT. */ const DigitalData SimGloveGesture::getDigitalData(int devNum) { int openLookupTable[] = { 0,0,0,0,0,-1,0,0,0,0,0 }; int closedLookupTable[] = { 1,1,1,1,1,-1,1,1,1,1,1 }; int pointingLookupTable[] = { 1,1,1,0,1,-1,1,1,1,0,1 }; switch (mCurGesture) { case 0: //open mDigitalData = openLookupTable[devNum]; break; case 1: //closed mDigitalData = closedLookupTable[devNum]; break; case 2: // pointing mDigitalData = pointingLookupTable[devNum]; break; default: mDigitalData = openLookupTable[devNum]; break; } return mDigitalData; } /** * Gets the current gesture. * @return id of current gesture */ int SimGloveGesture::getGesture() { return mCurGesture; } /** * Updates the device data. * Get the gesture id. * Set the glove params. */ void SimGloveGesture::updateData() { /* TEMPORARILY REMOVE // Get the current gesture for(unsigned int i=0;i<mSimKeys.size();i++) { if(checkKeyPair(mSimKeys[i]) > 0) { mCurGesture = i; vprDEBUG(gadgetDBG_INPUT_MGR,3) << "vjSimGloveGesture: Got gesture: " << getGestureString(mCurGesture).c_str() << std::endl << vprDEBUG_FLUSH; // Set the glove to the sample mTheData[0][current] = mGestureExamples[mCurGesture]; // Copy over the example mTheData[0][current].calcXforms(); // Update the xform data } } */ } /** * Loads trained data for the gesture object. * Loads the file for trained data. */ void SimGloveGesture::loadTrainedFile(std::string fileName) { std::ifstream inFile(fileName.c_str()); if(inFile) { this->loadFileHeader(inFile); inFile.close(); // Close the file } else { vprDEBUG(gadgetDBG_INPUT_MGR,0) << "gadget::SimGloveGesture:: Can't load trained file: " << fileName.c_str() << std::endl << vprDEBUG_FLUSH; } } } // End of gadget namespace <commit_msg>Added a missing #include. It had been coming in through an incredibly indirect path (via cppdom.h).<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2002 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <gadget/gadgetConfig.h> #include <fstream> #include <vpr/Util/FileUtils.h> #include <jccl/Config/ConfigChunk.h> #include <gadget/Util/Debug.h> #include <gadget/Devices/Sim/SimGloveGesture.h> namespace gadget { /** * Constructs the SimGloveGesture. * Set the keyboard key pairs. * Load the sample file. * Trim the smallest so they are same length. * Find/Set pos proxy for glove. */ bool SimGloveGesture::config(jccl::ConfigChunkPtr chunk) { if((!GloveGesture::config(chunk)) || (!SimInput::config(chunk))) return false; mCurGesture = 0; // We are in no gesture yet std::vector<jccl::ConfigChunkPtr> key_list; int key_count = chunk->getNum("keyPairs"); for ( int i = 0; i < key_count; ++i ) { key_list.push_back(chunk->getProperty<jccl::ConfigChunkPtr>("keyPairs", i)); } mSimKeys = readKeyList(key_list); // Get sample filename std::string sample_file = chunk->getProperty<std::string>("trainedFilename"); loadTrainedFile(vpr::replaceEnvVars(sample_file)); // Trim the lengths unsigned int num_gestures = getNumGestures(); while(num_gestures < mSimKeys.size()) // If we have to many keys { mSimKeys.pop_back(); vprDEBUG(gadgetDBG_INPUT_MGR,1) << "vjSimGloveGesture: Not enough gestures. Trimming" << std::endl << vprDEBUG_FLUSH; } // Find pos proxy std::string glove_pos_proxy = chunk->getProperty<std::string>("glovePos"); // Get the name of the pos_proxy if(glove_pos_proxy == std::string("")) { vprDEBUG(gadgetDBG_INPUT_MGR,0) << clrOutNORM(clrRED, "ERROR:") << " SimGloveGesture has no posProxy." << std::endl << vprDEBUG_FLUSH; return false; } // init glove proxy interface /* int proxy_index = Kernel::instance()->getInputManager()->getProxyIndex(glove_pos_proxy); if(proxy_index != -1) mGlovePos[0] = Kernel::instance()->getInputManager()->getPosProxy(proxy_index); else vprDEBUG(gadgetDBG_INPUT_MGR,0) << clrOutNORM(clrRED, "ERROR:") << " SimGloveGesture::CyberGlove: Can't find posProxy." << std::endl << std::endl << vprDEBUG_FLUSH; */ // Set the indexes to defaults //resetIndexes(); return true; } /** * Gets the digital data for the given devNum. * Returns digital 0 or 1, if devNum makes sense. * Returns -1 if function fails or if devNum is out of range. * * @note If devNum is out of range, function will fail, possibly issueing * an error to a log or console - but will not ASSERT. */ const DigitalData SimGloveGesture::getDigitalData(int devNum) { int openLookupTable[] = { 0,0,0,0,0,-1,0,0,0,0,0 }; int closedLookupTable[] = { 1,1,1,1,1,-1,1,1,1,1,1 }; int pointingLookupTable[] = { 1,1,1,0,1,-1,1,1,1,0,1 }; switch (mCurGesture) { case 0: //open mDigitalData = openLookupTable[devNum]; break; case 1: //closed mDigitalData = closedLookupTable[devNum]; break; case 2: // pointing mDigitalData = pointingLookupTable[devNum]; break; default: mDigitalData = openLookupTable[devNum]; break; } return mDigitalData; } /** * Gets the current gesture. * @return id of current gesture */ int SimGloveGesture::getGesture() { return mCurGesture; } /** * Updates the device data. * Get the gesture id. * Set the glove params. */ void SimGloveGesture::updateData() { /* TEMPORARILY REMOVE // Get the current gesture for(unsigned int i=0;i<mSimKeys.size();i++) { if(checkKeyPair(mSimKeys[i]) > 0) { mCurGesture = i; vprDEBUG(gadgetDBG_INPUT_MGR,3) << "vjSimGloveGesture: Got gesture: " << getGestureString(mCurGesture).c_str() << std::endl << vprDEBUG_FLUSH; // Set the glove to the sample mTheData[0][current] = mGestureExamples[mCurGesture]; // Copy over the example mTheData[0][current].calcXforms(); // Update the xform data } } */ } /** * Loads trained data for the gesture object. * Loads the file for trained data. */ void SimGloveGesture::loadTrainedFile(std::string fileName) { std::ifstream inFile(fileName.c_str()); if(inFile) { this->loadFileHeader(inFile); inFile.close(); // Close the file } else { vprDEBUG(gadgetDBG_INPUT_MGR,0) << "gadget::SimGloveGesture:: Can't load trained file: " << fileName.c_str() << std::endl << vprDEBUG_FLUSH; } } } // End of gadget namespace <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkPointSetToPointSetRegistrationTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifdef _WIN32 #pragma warning ( disable : 4786 ) #endif #include "itkTranslationTransform.h" #include "itkEuclideanDistancePointMetric.h" #include "itkLevenbergMarquardtOptimizer.h" #include "itkPointSet.h" #include "itkPointSetToPointSetRegistrationMethod.h" #include "itkDanielssonDistanceMapImageFilter.h" #include "itkPointSetToImageFilter.h" #include <iostream> /** * * This program tests the registration of a PointSet against an other PointSet. * */ int itkPointSetToPointSetRegistrationTest(int, char* [] ) { //------------------------------------------------------------ // Create two simple point sets //------------------------------------------------------------ typedef itk::PointSet< float, 2 > FixedPointSetType; FixedPointSetType::Pointer fixedPointSet = FixedPointSetType::New(); const unsigned int numberOfPoints = 500; fixedPointSet->SetPointData( FixedPointSetType::PointDataContainer::New() ); fixedPointSet->GetPoints()->Reserve( numberOfPoints ); fixedPointSet->GetPointData()->Reserve( numberOfPoints ); FixedPointSetType::PointType point; unsigned int id = 0; for(unsigned int i=0;i<numberOfPoints/2;i++) { point[0]=0; point[1]=i; fixedPointSet->SetPoint( id++, point ); } for(unsigned int i=0;i<numberOfPoints/2;i++) { point[0]=i; point[1]=0; fixedPointSet->SetPoint( id++, point ); } // Moving Point Set typedef itk::PointSet< float, 2 > MovingPointSetType; MovingPointSetType::Pointer movingPointSet = MovingPointSetType::New(); movingPointSet->SetPointData( MovingPointSetType::PointDataContainer::New() ); movingPointSet->GetPoints()->Reserve( numberOfPoints ); movingPointSet->GetPointData()->Reserve( numberOfPoints ); id = 0; for(unsigned int i=0;i<numberOfPoints/2;i++) { point[0]=0; point[1]=i; movingPointSet->SetPoint( id++, point ); } for(unsigned int i=0;i<numberOfPoints/2;i++) { point[0]=i; point[1]=0; movingPointSet->SetPoint( id++, point ); } //----------------------------------------------------------- // Set up the Metric //----------------------------------------------------------- typedef itk::EuclideanDistancePointMetric< FixedPointSetType, MovingPointSetType> MetricType; typedef MetricType::TransformType TransformBaseType; typedef TransformBaseType::ParametersType ParametersType; typedef TransformBaseType::JacobianType JacobianType; MetricType::Pointer metric = MetricType::New(); //----------------------------------------------------------- // Set up a Transform //----------------------------------------------------------- typedef itk::TranslationTransform< double, 2 > TransformType; TransformType::Pointer transform = TransformType::New(); // Optimizer Type typedef itk::LevenbergMarquardtOptimizer OptimizerType; OptimizerType::Pointer optimizer = OptimizerType::New(); optimizer->SetUseCostFunctionGradient(false); // Registration Method typedef itk::PointSetToPointSetRegistrationMethod< FixedPointSetType, MovingPointSetType > RegistrationType; RegistrationType::Pointer registration = RegistrationType::New(); // Scale the translation components of the Transform in the Optimizer OptimizerType::ScalesType scales( transform->GetNumberOfParameters() ); scales.Fill( 1.0 ); unsigned long numberOfIterations = 100; double gradientTolerance = 1e-1; // convergence criterion double valueTolerance = 1e-1; // convergence criterion double epsilonFunction = 1e-9; // convergence criterion optimizer->SetScales( scales ); optimizer->SetNumberOfIterations( numberOfIterations ); optimizer->SetValueTolerance(valueTolerance); optimizer->SetGradientTolerance(gradientTolerance); optimizer->SetEpsilonFunction(epsilonFunction); // Start from an Identity transform (in a normal case, the user // can probably provide a better guess than the identity... transform->SetIdentity(); registration->SetInitialTransformParameters( transform->GetParameters() ); //------------------------------------------------------ // Connect all the components required for Registration //------------------------------------------------------ registration->SetMetric( metric ); registration->SetOptimizer( optimizer ); registration->SetTransform( transform ); registration->SetFixedPointSet( fixedPointSet ); registration->SetMovingPointSet( movingPointSet ); //------------------------------------------------------------ // Set up transform parameters //------------------------------------------------------------ ParametersType parameters( transform->GetNumberOfParameters() ); // initialize the offset/vector part for( unsigned int k = 0; k < 2; k++ ) { parameters[k]= 10.0; } transform->SetParameters(parameters); registration->SetInitialTransformParameters( transform->GetParameters() ); try { registration->StartRegistration(); } catch( itk::ExceptionObject & e ) { std::cout << e << std::endl; return EXIT_FAILURE; } std::cout << "Solution = " << transform->GetParameters() << std::endl; if((fabs(transform->GetParameters()[0])>1.0) || (fabs(transform->GetParameters()[1])>1.0) ) { return EXIT_FAILURE; } /** Test with the danielsson distance map */ typedef itk::Image<unsigned char,2> BinaryImageType; typedef itk::Image<unsigned short,2> ImageType; typedef itk::PointSetToImageFilter<FixedPointSetType,BinaryImageType> PSToImageFilterType; PSToImageFilterType::Pointer psToImageFilter = PSToImageFilterType::New(); psToImageFilter->SetInput(fixedPointSet); double origin[2] = {0.0, 0.0}, spacing[2] = {1.0, 1.0}; psToImageFilter->SetSpacing(spacing); psToImageFilter->SetOrigin(origin); std::cout << "Spacing and origin set: [" << psToImageFilter->GetSpacing() << "], ,[" << psToImageFilter->GetOrigin() << "]" << std::endl; psToImageFilter->Update(); std::cout << "psToImageFilter: " << psToImageFilter << std::endl; BinaryImageType::Pointer binaryImage = psToImageFilter->GetOutput(); typedef itk::DanielssonDistanceMapImageFilter<BinaryImageType,ImageType> DDFilterType; DDFilterType::Pointer ddFilter = DDFilterType::New(); ddFilter->SetInput(binaryImage); ddFilter->Update(); metric->SetDistanceMap(ddFilter->GetOutput()); // initialize the offset/vector part for( unsigned int k = 0; k < 2; k++ ) { parameters[k]= 10.0; } transform->SetParameters(parameters); registration->SetInitialTransformParameters( transform->GetParameters() ); try { registration->StartRegistration(); } catch( itk::ExceptionObject & e ) { std::cout << e << std::endl; return EXIT_FAILURE; } std::cout << "Solution = " << transform->GetParameters() << std::endl; if((fabs(transform->GetParameters()[0])>1.0) || (fabs(transform->GetParameters()[1])>1.0) ) { return EXIT_FAILURE; } std::cout << "TEST DONE" << std::endl; return EXIT_SUCCESS; } <commit_msg>BUG: ComputeSquaredDistaneOn() for metric.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkPointSetToPointSetRegistrationTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifdef _WIN32 #pragma warning ( disable : 4786 ) #endif #include "itkTranslationTransform.h" #include "itkEuclideanDistancePointMetric.h" #include "itkLevenbergMarquardtOptimizer.h" #include "itkPointSet.h" #include "itkPointSetToPointSetRegistrationMethod.h" #include "itkDanielssonDistanceMapImageFilter.h" #include "itkPointSetToImageFilter.h" #include <iostream> /** * * This program tests the registration of a PointSet against an other PointSet. * */ int itkPointSetToPointSetRegistrationTest(int, char* [] ) { //------------------------------------------------------------ // Create two simple point sets //------------------------------------------------------------ typedef itk::PointSet< float, 2 > FixedPointSetType; FixedPointSetType::Pointer fixedPointSet = FixedPointSetType::New(); const unsigned int numberOfPoints = 500; fixedPointSet->SetPointData( FixedPointSetType::PointDataContainer::New() ); fixedPointSet->GetPoints()->Reserve( numberOfPoints ); fixedPointSet->GetPointData()->Reserve( numberOfPoints ); FixedPointSetType::PointType point; unsigned int id = 0; for(unsigned int i=0;i<numberOfPoints/2;i++) { point[0]=0; point[1]=i; fixedPointSet->SetPoint( id++, point ); } for(unsigned int i=0;i<numberOfPoints/2;i++) { point[0]=i; point[1]=0; fixedPointSet->SetPoint( id++, point ); } // Moving Point Set typedef itk::PointSet< float, 2 > MovingPointSetType; MovingPointSetType::Pointer movingPointSet = MovingPointSetType::New(); movingPointSet->SetPointData( MovingPointSetType::PointDataContainer::New() ); movingPointSet->GetPoints()->Reserve( numberOfPoints ); movingPointSet->GetPointData()->Reserve( numberOfPoints ); id = 0; for(unsigned int i=0;i<numberOfPoints/2;i++) { point[0]=0; point[1]=i; movingPointSet->SetPoint( id++, point ); } for(unsigned int i=0;i<numberOfPoints/2;i++) { point[0]=i; point[1]=0; movingPointSet->SetPoint( id++, point ); } //----------------------------------------------------------- // Set up the Metric //----------------------------------------------------------- typedef itk::EuclideanDistancePointMetric< FixedPointSetType, MovingPointSetType> MetricType; typedef MetricType::TransformType TransformBaseType; typedef TransformBaseType::ParametersType ParametersType; typedef TransformBaseType::JacobianType JacobianType; MetricType::Pointer metric = MetricType::New(); //----------------------------------------------------------- // Set up a Transform //----------------------------------------------------------- typedef itk::TranslationTransform< double, 2 > TransformType; TransformType::Pointer transform = TransformType::New(); // Optimizer Type typedef itk::LevenbergMarquardtOptimizer OptimizerType; OptimizerType::Pointer optimizer = OptimizerType::New(); optimizer->SetUseCostFunctionGradient(false); // Registration Method typedef itk::PointSetToPointSetRegistrationMethod< FixedPointSetType, MovingPointSetType > RegistrationType; RegistrationType::Pointer registration = RegistrationType::New(); // Scale the translation components of the Transform in the Optimizer OptimizerType::ScalesType scales( transform->GetNumberOfParameters() ); scales.Fill( 1.0 ); unsigned long numberOfIterations = 100; double gradientTolerance = 1e-1; // convergence criterion double valueTolerance = 1e-1; // convergence criterion double epsilonFunction = 1e-9; // convergence criterion optimizer->SetScales( scales ); optimizer->SetNumberOfIterations( numberOfIterations ); optimizer->SetValueTolerance(valueTolerance); optimizer->SetGradientTolerance(gradientTolerance); optimizer->SetEpsilonFunction(epsilonFunction); // Start from an Identity transform (in a normal case, the user // can probably provide a better guess than the identity... transform->SetIdentity(); registration->SetInitialTransformParameters( transform->GetParameters() ); //------------------------------------------------------ // Connect all the components required for Registration //------------------------------------------------------ registration->SetMetric( metric ); registration->SetOptimizer( optimizer ); registration->SetTransform( transform ); registration->SetFixedPointSet( fixedPointSet ); registration->SetMovingPointSet( movingPointSet ); //------------------------------------------------------------ // Set up transform parameters //------------------------------------------------------------ ParametersType parameters( transform->GetNumberOfParameters() ); // initialize the offset/vector part for( unsigned int k = 0; k < 2; k++ ) { parameters[k]= 10.0; } transform->SetParameters(parameters); registration->SetInitialTransformParameters( transform->GetParameters() ); try { registration->StartRegistration(); } catch( itk::ExceptionObject & e ) { std::cout << e << std::endl; return EXIT_FAILURE; } std::cout << "Solution = " << transform->GetParameters() << std::endl; if((fabs(transform->GetParameters()[0])>1.0) || (fabs(transform->GetParameters()[1])>1.0) ) { return EXIT_FAILURE; } /** Test with the danielsson distance map */ typedef itk::Image<unsigned char,2> BinaryImageType; typedef itk::Image<unsigned short,2> ImageType; typedef itk::PointSetToImageFilter<FixedPointSetType,BinaryImageType> PSToImageFilterType; PSToImageFilterType::Pointer psToImageFilter = PSToImageFilterType::New(); psToImageFilter->SetInput(fixedPointSet); double origin[2] = {0.0, 0.0}, spacing[2] = {1.0, 1.0}; psToImageFilter->SetSpacing(spacing); psToImageFilter->SetOrigin(origin); std::cout << "Spacing and origin set: [" << psToImageFilter->GetSpacing() << "], ,[" << psToImageFilter->GetOrigin() << "]" << std::endl; psToImageFilter->Update(); std::cout << "psToImageFilter: " << psToImageFilter << std::endl; BinaryImageType::Pointer binaryImage = psToImageFilter->GetOutput(); typedef itk::DanielssonDistanceMapImageFilter<BinaryImageType,ImageType> DDFilterType; DDFilterType::Pointer ddFilter = DDFilterType::New(); ddFilter->SetInput(binaryImage); ddFilter->Update(); metric->SetDistanceMap(ddFilter->GetOutput()); metric->ComputeSquaredDistanceOn(); // initialize the offset/vector part for( unsigned int k = 0; k < 2; k++ ) { parameters[k]= 10.0; } transform->SetParameters(parameters); registration->SetInitialTransformParameters( transform->GetParameters() ); try { registration->StartRegistration(); } catch( itk::ExceptionObject & e ) { std::cout << e << std::endl; return EXIT_FAILURE; } std::cout << "Solution = " << transform->GetParameters() << std::endl; if((fabs(transform->GetParameters()[0])>1.0) || (fabs(transform->GetParameters()[1])>1.0) ) { return EXIT_FAILURE; } std::cout << "TEST DONE" << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// BSD 2-Clause License, see github.com/ma16/rpio #include "Error.h" using namespace Protocol::OneWire::Bang ; static std::string toStr(Error::Type type,int line) { static char const *v[] = { "NotPresent","Retry","Reset","Timing","Vanished" } ; auto s = v[Error::TypeN(type).n()] ; std::ostringstream os ; os << "Device:Ds18x20:Bang: " << s << " #" << line ; return os.str() ; } Error::Error(Type type,int line) : Neat::Error(toStr(type,line)),type_(type) { // void } <commit_msg>fix message<commit_after>// BSD 2-Clause License, see github.com/ma16/rpio #include "Error.h" using namespace Protocol::OneWire::Bang ; static std::string toStr(Error::Type type,int line) { static char const *v[] = { "NotPresent","Retry","Reset","Timing","Vanished" } ; auto s = v[Error::TypeN(type).n()] ; std::ostringstream os ; os << "Protocol::OneWire::Bang: " << s << " #" << line ; return os.str() ; } Error::Error(Type type,int line) : Neat::Error(toStr(type,line)),type_(type) { // void } <|endoftext|>
<commit_before>#include <vpr/vpr.h> #include <vpr/Util/GUID.h> //#include <vpr/Util/GUIDFactory.h> #include <vpr/Util/Interval.h> #include <vpr/Util/Debug.h> #include <TestCases/Perf/PerfTest.h> #include <vpr/Perf/ProfileManager.h> // Get all the profile stuff namespace vprTest { CPPUNIT_TEST_SUITE_REGISTRATION( PerfTest ); CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( PerfMetricTest, MySuites::metric() ); void PerfTest::testConstructTree () { vpr::ProfileManager::startProfile("First"); vpr::ProfileManager::startProfile("First-one"); vpr::ProfileManager::stopProfile(); vpr::ProfileManager::stopProfile(); vpr::ProfileNode* root_node = vpr::ProfileManager::getRootNode(); vpr::ProfileNode* first_node = root_node->getChild(); vpr::ProfileNode* first_one_node = first_node->getChild(); CPPUNIT_ASSERT(first_node->getParent() == root_node); CPPUNIT_ASSERT(first_one_node->getParent() == first_node); } void PerfTest::testNamedLookupSample () { vpr::ProfileManager::startProfile("myNamedProfile"); //do something so there is a little time in the profile int i=0; int j=1; for(; i++; i<10000) { j=j+1; } for(; j--; j>0) { i = i-1; } vpr::ProfileManager::stopProfile(); float f = vpr::ProfileManager::getNamedNodeSample("myNamedProfile"); CPPUNIT_ASSERT(f != 0.0f); } void PerfTest::testReset () { //CPPUNIT_ASSERT(false); } // ------------------ Perf Metric --------------------- // void PerfMetricTest::testTreeOverhead() { const vpr::Uint32 iters(1000); vpr::Uint32 loops = iters; vpr::GUID guid1; CPPUNIT_METRIC_START_TIMING(); while(loops--) { vpr::ProfileManager::startProfile("MyFirst"); vpr::ProfileManager::startProfile("MySecond"); vpr::ProfileManager::stopProfile(); vpr::ProfileManager::startProfile("MySecondAgain"); vpr::ProfileManager::stopProfile(); vpr::ProfileManager::stopProfile(); } CPPUNIT_METRIC_STOP_TIMING(); CPPUNIT_ASSERT_METRIC_TIMING_LE("PerfTest/TreeOverhead", iters, 0.05f, 0.1f); } } // End of vprTest namespace <commit_msg>Silenced MIPSpro compiler warnings, and in so doing fixed the loops in testNamedLookupSample() so that they now iterate more than once. I also shuffled the code around a bit but did not change the intended functionality at all.<commit_after>#include <vpr/vpr.h> #include <vpr/Util/GUID.h> //#include <vpr/Util/GUIDFactory.h> #include <vpr/Util/Interval.h> #include <vpr/Util/Debug.h> #include <TestCases/Perf/PerfTest.h> #include <vpr/Perf/ProfileManager.h> // Get all the profile stuff namespace vprTest { CPPUNIT_TEST_SUITE_REGISTRATION( PerfTest ); CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( PerfMetricTest, MySuites::metric() ); void PerfTest::testConstructTree () { vpr::ProfileManager::startProfile("First"); vpr::ProfileManager::startProfile("First-one"); vpr::ProfileManager::stopProfile(); vpr::ProfileManager::stopProfile(); vpr::ProfileNode* root_node = vpr::ProfileManager::getRootNode(); vpr::ProfileNode* first_node = root_node->getChild(); vpr::ProfileNode* first_one_node = first_node->getChild(); CPPUNIT_ASSERT(first_node->getParent() == root_node); CPPUNIT_ASSERT(first_one_node->getParent() == first_node); } void PerfTest::testNamedLookupSample () { vpr::ProfileManager::startProfile("myNamedProfile"); //do something so there is a little time in the profile int i(0), j(1); for ( ; i < 10000; ++i, ++j ) { ; } for ( ; j > 0; --j, --i ) { ; } vpr::ProfileManager::stopProfile(); float f = vpr::ProfileManager::getNamedNodeSample("myNamedProfile"); CPPUNIT_ASSERT(f != 0.0f); } void PerfTest::testReset () { //CPPUNIT_ASSERT(false); } // ------------------ Perf Metric --------------------- // void PerfMetricTest::testTreeOverhead() { const vpr::Uint32 iters(1000); vpr::Uint32 loops = iters; vpr::GUID guid1; CPPUNIT_METRIC_START_TIMING(); while(loops--) { vpr::ProfileManager::startProfile("MyFirst"); vpr::ProfileManager::startProfile("MySecond"); vpr::ProfileManager::stopProfile(); vpr::ProfileManager::startProfile("MySecondAgain"); vpr::ProfileManager::stopProfile(); vpr::ProfileManager::stopProfile(); } CPPUNIT_METRIC_STOP_TIMING(); CPPUNIT_ASSERT_METRIC_TIMING_LE("PerfTest/TreeOverhead", iters, 0.05f, 0.1f); } } // End of vprTest namespace <|endoftext|>
<commit_before>// // XMLInterpreter.cpp // TimGameLib // // Created by Tim Brier on 11/10/2014. // Copyright (c) 2014 tbrier. All rights reserved. // // ============================================================================= // Include Files // ----------------------------------------------------------------------------- #include "CXMLInterpreter.hpp" #include "SystemUtilities.hpp" // ============================================================================= // CXMLInterpreter constructor/destructor // ----------------------------------------------------------------------------- CXMLInterpreter::CXMLInterpreter(std::string filename) { mFilename = SystemUtilities::GetResourcePath() + filename; } CXMLInterpreter::~CXMLInterpreter() { } // ============================================================================= // CXMLInterpreter::LoadFile // ----------------------------------------------------------------------------- bool CXMLInterpreter::LoadFile() { pugi::xml_parse_result theResult = mDocument.load_file(mFilename.c_str()); if (theResult.status != pugi::status_ok) { DEBUG_LOG("Error parsisng config xml file: %s", mFilename.c_str()); DEBUG_LOG("Status code: %d", theResult.status); return false; } return true; } // ============================================================================= // CXMLInterpreter::GetInt // ----------------------------------------------------------------------------- int CXMLInterpreter::GetInt(pugi::xml_node theRoot) { int theResult = 0; theResult = theRoot.text().as_int(); return theResult; } // ============================================================================= // CXMLInterpreter::GetFloat // ----------------------------------------------------------------------------- float CXMLInterpreter::GetFloat(pugi::xml_node theRoot) { float theResult = 0.0f; theResult = theRoot.text().as_float(); return theResult; } // ============================================================================= // CXMLInterpreter::GetBool // ----------------------------------------------------------------------------- bool CXMLInterpreter::GetBool(pugi::xml_node theRoot) { int theResult = 0; theResult = theRoot.text().as_bool(); return theResult; } // ============================================================================= // CXMLInterpreter::GetVector2f // ----------------------------------------------------------------------------- CVector2f CXMLInterpreter::GetVector2f(pugi::xml_node theRoot) { CHECK_CHILD(theRoot, "x"); CHECK_CHILD(theRoot, "y"); CVector2f theResult; theResult.x = theRoot.child("x").text().as_float(); theResult.y = theRoot.child("y").text().as_float(); return theResult; } // ============================================================================= // CXMLInterpreter::GetTime // ----------------------------------------------------------------------------- CTime CXMLInterpreter::GetTime(pugi::xml_node theRoot) { float seconds = theRoot.text().as_float(); CTime theResult = CTime::Seconds(seconds); return theResult; }<commit_msg>Not all xml files are config files<commit_after>// // XMLInterpreter.cpp // TimGameLib // // Created by Tim Brier on 11/10/2014. // Copyright (c) 2014 tbrier. All rights reserved. // // ============================================================================= // Include Files // ----------------------------------------------------------------------------- #include "CXMLInterpreter.hpp" #include "SystemUtilities.hpp" // ============================================================================= // CXMLInterpreter constructor/destructor // ----------------------------------------------------------------------------- CXMLInterpreter::CXMLInterpreter(std::string filename) { mFilename = SystemUtilities::GetResourcePath() + filename; } CXMLInterpreter::~CXMLInterpreter() { } // ============================================================================= // CXMLInterpreter::LoadFile // ----------------------------------------------------------------------------- bool CXMLInterpreter::LoadFile() { pugi::xml_parse_result theResult = mDocument.load_file(mFilename.c_str()); if (theResult.status != pugi::status_ok) { DEBUG_LOG("Error parsisng xml file: %s", mFilename.c_str()); DEBUG_LOG("Status code: %d", theResult.status); return false; } return true; } // ============================================================================= // CXMLInterpreter::GetInt // ----------------------------------------------------------------------------- int CXMLInterpreter::GetInt(pugi::xml_node theRoot) { int theResult = 0; theResult = theRoot.text().as_int(); return theResult; } // ============================================================================= // CXMLInterpreter::GetFloat // ----------------------------------------------------------------------------- float CXMLInterpreter::GetFloat(pugi::xml_node theRoot) { float theResult = 0.0f; theResult = theRoot.text().as_float(); return theResult; } // ============================================================================= // CXMLInterpreter::GetBool // ----------------------------------------------------------------------------- bool CXMLInterpreter::GetBool(pugi::xml_node theRoot) { int theResult = 0; theResult = theRoot.text().as_bool(); return theResult; } // ============================================================================= // CXMLInterpreter::GetVector2f // ----------------------------------------------------------------------------- CVector2f CXMLInterpreter::GetVector2f(pugi::xml_node theRoot) { CHECK_CHILD(theRoot, "x"); CHECK_CHILD(theRoot, "y"); CVector2f theResult; theResult.x = theRoot.child("x").text().as_float(); theResult.y = theRoot.child("y").text().as_float(); return theResult; } // ============================================================================= // CXMLInterpreter::GetTime // ----------------------------------------------------------------------------- CTime CXMLInterpreter::GetTime(pugi::xml_node theRoot) { float seconds = theRoot.text().as_float(); CTime theResult = CTime::Seconds(seconds); return theResult; }<|endoftext|>
<commit_before>// // CRTOpenGL.hpp // Clock Signal // // Created by Thomas Harte on 13/02/2016. // Copyright © 2016 Thomas Harte. All rights reserved. // #ifndef CRTOpenGL_h #define CRTOpenGL_h #include "../CRTTypes.hpp" #include "CRTConstants.hpp" #include "OpenGL.hpp" #include "TextureTarget.hpp" #include "Shader.hpp" #include "InputTextureBuilder.hpp" #include "Shaders/OutputShader.hpp" #include "Shaders/IntermediateShader.hpp" #include <mutex> #include <vector> namespace Outputs { namespace CRT { class OpenGLOutputBuilder { private: // colour information ColourSpace _colour_space; unsigned int _colour_cycle_numerator; unsigned int _colour_cycle_denominator; OutputDevice _output_device; // timing information to allow reasoning about input information unsigned int _input_frequency; unsigned int _cycles_per_line; unsigned int _height_of_display; unsigned int _horizontal_scan_period; unsigned int _vertical_scan_period; unsigned int _vertical_period_divider; // The user-supplied visible area Rect _visible_area; // Other things the caller may have provided. char *_composite_shader; char *_rgb_shader; // Methods used by the OpenGL code void prepare_output_shader(); void prepare_rgb_input_shaders(); void prepare_composite_input_shaders(); void prepare_output_vertex_array(); void prepare_source_vertex_array(); // the run and input data buffers std::unique_ptr<InputTextureBuilder> _texture_builder; std::unique_ptr<std::mutex> _output_mutex; std::unique_ptr<std::mutex> _draw_mutex; // transient buffers indicating composite data not yet decoded GLsizei _composite_src_output_y; std::unique_ptr<OpenGL::OutputShader> output_shader_program; std::unique_ptr<OpenGL::IntermediateShader> composite_input_shader_program, composite_separation_filter_program, composite_y_filter_shader_program, composite_chrominance_filter_shader_program; std::unique_ptr<OpenGL::IntermediateShader> rgb_input_shader_program, rgb_filter_shader_program; std::unique_ptr<OpenGL::TextureTarget> compositeTexture; // receives raw composite levels std::unique_ptr<OpenGL::TextureTarget> separatedTexture; // receives unfiltered Y in the R channel plus unfiltered but demodulated chrominance in G and B std::unique_ptr<OpenGL::TextureTarget> filteredYTexture; // receives filtered Y in the R channel plus unfiltered chrominance in G and B std::unique_ptr<OpenGL::TextureTarget> filteredTexture; // receives filtered YIQ or YUV std::unique_ptr<OpenGL::TextureTarget> framebuffer; // the current pixel output GLuint output_array_buffer, output_vertex_array; GLuint source_array_buffer, source_vertex_array; unsigned int _last_output_width, _last_output_height; GLuint textureName, shadowMaskTextureName; GLuint defaultFramebuffer; void set_timing_uniforms(); void set_colour_space_uniforms(); void establish_OpenGL_state(); void reset_all_OpenGL_state(); public: OpenGLOutputBuilder(unsigned int buffer_depth); ~OpenGLOutputBuilder(); inline uint8_t *get_next_source_run() { _line_buffer.data.resize(_line_buffer.pointer + SourceVertexSize); return &_line_buffer.data[_line_buffer.pointer]; } inline void complete_source_run() { _line_buffer.pointer += SourceVertexSize; } inline uint8_t *get_buffered_source_runs(size_t &size) { size = _line_buffer.pointer; return _line_buffer.data.data(); } inline uint8_t *get_next_output_run() { if(_output_buffer.pointer == OutputVertexBufferDataSize) return nullptr; return &_output_buffer.data[_output_buffer.pointer]; } inline void complete_output_run() { size_t line_buffer_size = _line_buffer.data.size(); if(_source_buffer.pointer + line_buffer_size < SourceVertexBufferDataSize) { _output_buffer.pointer += OutputVertexSize; memcpy(&_source_buffer.data[_source_buffer.pointer], _line_buffer.data.data(), _line_buffer.data.size()); _source_buffer.pointer += _line_buffer.data.size(); _line_buffer.data.resize(0); _line_buffer.pointer = 0; } } inline void set_colour_format(ColourSpace colour_space, unsigned int colour_cycle_numerator, unsigned int colour_cycle_denominator) { _output_mutex->lock(); _colour_space = colour_space; _colour_cycle_numerator = colour_cycle_numerator; _colour_cycle_denominator = colour_cycle_denominator; set_colour_space_uniforms(); _output_mutex->unlock(); } inline void set_visible_area(Rect visible_area) { _visible_area = visible_area; } inline bool composite_output_run_has_room_for_vertex() { return _output_buffer.pointer < OutputVertexBufferDataSize; } inline void lock_output() { _output_mutex->lock(); } inline void unlock_output() { _output_mutex->unlock(); } inline OutputDevice get_output_device() { return _output_device; } inline uint16_t get_composite_output_y() { return (uint16_t)_composite_src_output_y; } inline bool composite_output_buffer_is_full() { return _composite_src_output_y == IntermediateBufferHeight; } inline void increment_composite_output_y() { if(!composite_output_buffer_is_full()) _composite_src_output_y++; } inline uint8_t *allocate_write_area(size_t required_length) { return _texture_builder->allocate_write_area(required_length); } inline void reduce_previous_allocation_to(size_t actual_length) { _texture_builder->reduce_previous_allocation_to(actual_length); } inline bool input_buffer_is_full() { return _texture_builder->is_full(); } inline uint16_t get_last_write_x_posititon() { return _texture_builder->get_last_write_x_position(); } inline uint16_t get_last_write_y_posititon() { return _texture_builder->get_last_write_y_position(); } void draw_frame(unsigned int output_width, unsigned int output_height, bool only_if_dirty); void set_openGL_context_will_change(bool should_delete_resources); void set_composite_sampling_function(const char *shader); void set_rgb_sampling_function(const char *shader); void set_output_device(OutputDevice output_device); void set_timing(unsigned int input_frequency, unsigned int cycles_per_line, unsigned int height_of_display, unsigned int horizontal_scan_period, unsigned int vertical_scan_period, unsigned int vertical_period_divider); struct Buffer { std::vector<uint8_t> data; size_t pointer; Buffer() : pointer(0) {} } _line_buffer, _source_buffer, _output_buffer; GLsync _fence; }; } } #endif /* CRTOpenGL_h */ <commit_msg>Attempted to reduce allocations.<commit_after>// // CRTOpenGL.hpp // Clock Signal // // Created by Thomas Harte on 13/02/2016. // Copyright © 2016 Thomas Harte. All rights reserved. // #ifndef CRTOpenGL_h #define CRTOpenGL_h #include "../CRTTypes.hpp" #include "CRTConstants.hpp" #include "OpenGL.hpp" #include "TextureTarget.hpp" #include "Shader.hpp" #include "InputTextureBuilder.hpp" #include "Shaders/OutputShader.hpp" #include "Shaders/IntermediateShader.hpp" #include <mutex> #include <vector> namespace Outputs { namespace CRT { class OpenGLOutputBuilder { private: // colour information ColourSpace _colour_space; unsigned int _colour_cycle_numerator; unsigned int _colour_cycle_denominator; OutputDevice _output_device; // timing information to allow reasoning about input information unsigned int _input_frequency; unsigned int _cycles_per_line; unsigned int _height_of_display; unsigned int _horizontal_scan_period; unsigned int _vertical_scan_period; unsigned int _vertical_period_divider; // The user-supplied visible area Rect _visible_area; // Other things the caller may have provided. char *_composite_shader; char *_rgb_shader; // Methods used by the OpenGL code void prepare_output_shader(); void prepare_rgb_input_shaders(); void prepare_composite_input_shaders(); void prepare_output_vertex_array(); void prepare_source_vertex_array(); // the run and input data buffers std::unique_ptr<InputTextureBuilder> _texture_builder; std::unique_ptr<std::mutex> _output_mutex; std::unique_ptr<std::mutex> _draw_mutex; // transient buffers indicating composite data not yet decoded GLsizei _composite_src_output_y; std::unique_ptr<OpenGL::OutputShader> output_shader_program; std::unique_ptr<OpenGL::IntermediateShader> composite_input_shader_program, composite_separation_filter_program, composite_y_filter_shader_program, composite_chrominance_filter_shader_program; std::unique_ptr<OpenGL::IntermediateShader> rgb_input_shader_program, rgb_filter_shader_program; std::unique_ptr<OpenGL::TextureTarget> compositeTexture; // receives raw composite levels std::unique_ptr<OpenGL::TextureTarget> separatedTexture; // receives unfiltered Y in the R channel plus unfiltered but demodulated chrominance in G and B std::unique_ptr<OpenGL::TextureTarget> filteredYTexture; // receives filtered Y in the R channel plus unfiltered chrominance in G and B std::unique_ptr<OpenGL::TextureTarget> filteredTexture; // receives filtered YIQ or YUV std::unique_ptr<OpenGL::TextureTarget> framebuffer; // the current pixel output GLuint output_array_buffer, output_vertex_array; GLuint source_array_buffer, source_vertex_array; unsigned int _last_output_width, _last_output_height; GLuint textureName, shadowMaskTextureName; GLuint defaultFramebuffer; void set_timing_uniforms(); void set_colour_space_uniforms(); void establish_OpenGL_state(); void reset_all_OpenGL_state(); public: OpenGLOutputBuilder(unsigned int buffer_depth); ~OpenGLOutputBuilder(); inline uint8_t *get_next_source_run() { if(_line_buffer.data.size() < _line_buffer.pointer + SourceVertexSize) _line_buffer.data.resize(_line_buffer.pointer + SourceVertexSize); return &_line_buffer.data[_line_buffer.pointer]; } inline void complete_source_run() { _line_buffer.pointer += SourceVertexSize; } inline uint8_t *get_buffered_source_runs(size_t &size) { size = _line_buffer.pointer; return _line_buffer.data.data(); } inline uint8_t *get_next_output_run() { if(_output_buffer.pointer == OutputVertexBufferDataSize) return nullptr; return &_output_buffer.data[_output_buffer.pointer]; } inline void complete_output_run() { size_t line_buffer_size = _line_buffer.data.size(); if(_source_buffer.pointer + line_buffer_size < SourceVertexBufferDataSize) { _output_buffer.pointer += OutputVertexSize; memcpy(&_source_buffer.data[_source_buffer.pointer], _line_buffer.data.data(), _line_buffer.data.size()); _source_buffer.pointer += _line_buffer.data.size(); _line_buffer.pointer = 0; } } inline void set_colour_format(ColourSpace colour_space, unsigned int colour_cycle_numerator, unsigned int colour_cycle_denominator) { _output_mutex->lock(); _colour_space = colour_space; _colour_cycle_numerator = colour_cycle_numerator; _colour_cycle_denominator = colour_cycle_denominator; set_colour_space_uniforms(); _output_mutex->unlock(); } inline void set_visible_area(Rect visible_area) { _visible_area = visible_area; } inline bool composite_output_run_has_room_for_vertex() { return _output_buffer.pointer < OutputVertexBufferDataSize; } inline void lock_output() { _output_mutex->lock(); } inline void unlock_output() { _output_mutex->unlock(); } inline OutputDevice get_output_device() { return _output_device; } inline uint16_t get_composite_output_y() { return (uint16_t)_composite_src_output_y; } inline bool composite_output_buffer_is_full() { return _composite_src_output_y == IntermediateBufferHeight; } inline void increment_composite_output_y() { if(!composite_output_buffer_is_full()) _composite_src_output_y++; } inline uint8_t *allocate_write_area(size_t required_length) { return _texture_builder->allocate_write_area(required_length); } inline void reduce_previous_allocation_to(size_t actual_length) { _texture_builder->reduce_previous_allocation_to(actual_length); } inline bool input_buffer_is_full() { return _texture_builder->is_full(); } inline uint16_t get_last_write_x_posititon() { return _texture_builder->get_last_write_x_position(); } inline uint16_t get_last_write_y_posititon() { return _texture_builder->get_last_write_y_position(); } void draw_frame(unsigned int output_width, unsigned int output_height, bool only_if_dirty); void set_openGL_context_will_change(bool should_delete_resources); void set_composite_sampling_function(const char *shader); void set_rgb_sampling_function(const char *shader); void set_output_device(OutputDevice output_device); void set_timing(unsigned int input_frequency, unsigned int cycles_per_line, unsigned int height_of_display, unsigned int horizontal_scan_period, unsigned int vertical_scan_period, unsigned int vertical_period_divider); struct Buffer { std::vector<uint8_t> data; size_t pointer; Buffer() : pointer(0) {} } _line_buffer, _source_buffer, _output_buffer; GLsync _fence; }; } } #endif /* CRTOpenGL_h */ <|endoftext|>
<commit_before>// MIT License // // Copyright (c) 2017 Artur Wyszyński, aljen at hitomi dot pl // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <boost/dll.hpp> #include <boost/filesystem.hpp> #include "core/logger.h" #include "core/registry.h" #include "core/version.h" #include "elements/element.h" #include "elements/logic/all.h" #include "elements/ui/all.h" #include "elements/package.h" #include "nodes/ui/float_info.h" #include "nodes/ui/push_button.h" #include "nodes/ui/toggle_button.h" #include "nodes/blinker.h" #include "nodes/clock.h" #include "nodes/const_value.h" #include "nodes/node.h" namespace fs = boost::filesystem; namespace dll = boost::dll; inline void init_resources() { Q_INIT_RESOURCE(icons); } namespace core { Registry &Registry::get() { static Registry s_registry{}; return s_registry; } Registry::Registry() { log::init(); log::info("Spaghetti version: {}, git: {}@{}, build date: {}, {}", version::STRING, version::BRANCH, version::COMMIT_SHORT_HASH, __DATE__, __TIME__); } void Registry::registerInternalElements() { init_resources(); using namespace elements; registerElement<Package>("Package", ":/elements/logic/package.png"); registerElement<ui::FloatInfo, nodes::ui::FloatInfo>("Float Info", ":/unknown.png"); registerElement<ui::PushButton, nodes::ui::PushButton>("Push Button", ":/elements/ui/push_button.png"); registerElement<ui::ToggleButton, nodes::ui::ToggleButton>("Toggle Button", ":/elements/ui/toggle_button.png"); registerElement<logic::Blinker, nodes::Blinker>("Blinker (bool)", ":/unknown.png"); registerElement<logic::Clock, nodes::Clock>("Clock (ms)", ":/elements/logic/clock.png"); registerElement<logic::Multiply>("Multiply (Float)", ":/unknown.png"); registerElement<logic::MultiplyIf>("Multiply If (Float)", ":/unknown.png"); registerElement<logic::Nand>("NAND (Bool)", ":/elements/logic/nand.png"); registerElement<logic::And>("AND (Bool)", ":/elements/logic/and.png"); registerElement<logic::Nor>("NOR (Bool)", ":/elements/logic/nor.png"); registerElement<logic::Or>("OR (Bool)", ":/elements/logic/or.png"); registerElement<logic::Not>("NOT (Bool)", ":/elements/logic/not.png"); registerElement<logic::ConstBool, nodes::ConstBool>("Const value (Bool)", ":/elements/logic/const_bool.png"); registerElement<logic::ConstFloat, nodes::ConstFloat>("Const value (Float)", ":/elements/logic/const_float.png"); registerElement<logic::ConstInt, nodes::ConstInt>("Const value (Int)", ":/elements/logic/const_int.png"); registerElement<logic::RandomBool>("Random (Bool)", ":/elements/logic/random_value.png"); registerElement<logic::Switch>("Switch (Int)", ":/elements/logic/switch.png"); } void Registry::loadPlugins() { fs::path const pluginsDir{ "../plugins" }; if (!fs::is_directory(pluginsDir)) return; for (auto const &entry : fs::directory_iterator(pluginsDir)) { if (!fs::is_regular_file(entry)) continue; boost::system::error_code error{}; auto plugin = std::make_shared<dll::shared_library>(entry, error, dll::load_mode::append_decorations); if (error.value() != 0 || !plugin->has("register_plugin")) continue; auto registerPlugin = plugin->get<void(core::Registry &)>("register_plugin"); registerPlugin(*this); m_plugins.emplace_back(std::move(plugin)); } } } // namespace core <commit_msg>Sort includes in registry.cc<commit_after>// MIT License // // Copyright (c) 2017 Artur Wyszyński, aljen at hitomi dot pl // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <boost/dll.hpp> #include <boost/filesystem.hpp> #include "core/logger.h" #include "core/registry.h" #include "core/version.h" #include "elements/element.h" #include "elements/logic/all.h" #include "elements/package.h" #include "elements/ui/all.h" #include "nodes/blinker.h" #include "nodes/clock.h" #include "nodes/const_value.h" #include "nodes/node.h" #include "nodes/ui/float_info.h" #include "nodes/ui/push_button.h" #include "nodes/ui/toggle_button.h" namespace fs = boost::filesystem; namespace dll = boost::dll; inline void init_resources() { Q_INIT_RESOURCE(icons); } namespace core { Registry &Registry::get() { static Registry s_registry{}; return s_registry; } Registry::Registry() { log::init(); log::info("Spaghetti version: {}, git: {}@{}, build date: {}, {}", version::STRING, version::BRANCH, version::COMMIT_SHORT_HASH, __DATE__, __TIME__); } void Registry::registerInternalElements() { init_resources(); using namespace elements; registerElement<Package>("Package", ":/elements/logic/package.png"); registerElement<ui::FloatInfo, nodes::ui::FloatInfo>("Float Info", ":/unknown.png"); registerElement<ui::PushButton, nodes::ui::PushButton>("Push Button", ":/elements/ui/push_button.png"); registerElement<ui::ToggleButton, nodes::ui::ToggleButton>("Toggle Button", ":/elements/ui/toggle_button.png"); registerElement<logic::Blinker, nodes::Blinker>("Blinker (bool)", ":/unknown.png"); registerElement<logic::Clock, nodes::Clock>("Clock (ms)", ":/elements/logic/clock.png"); registerElement<logic::Multiply>("Multiply (Float)", ":/unknown.png"); registerElement<logic::MultiplyIf>("Multiply If (Float)", ":/unknown.png"); registerElement<logic::Nand>("NAND (Bool)", ":/elements/logic/nand.png"); registerElement<logic::And>("AND (Bool)", ":/elements/logic/and.png"); registerElement<logic::Nor>("NOR (Bool)", ":/elements/logic/nor.png"); registerElement<logic::Or>("OR (Bool)", ":/elements/logic/or.png"); registerElement<logic::Not>("NOT (Bool)", ":/elements/logic/not.png"); registerElement<logic::ConstBool, nodes::ConstBool>("Const value (Bool)", ":/elements/logic/const_bool.png"); registerElement<logic::ConstFloat, nodes::ConstFloat>("Const value (Float)", ":/elements/logic/const_float.png"); registerElement<logic::ConstInt, nodes::ConstInt>("Const value (Int)", ":/elements/logic/const_int.png"); registerElement<logic::RandomBool>("Random (Bool)", ":/elements/logic/random_value.png"); registerElement<logic::Switch>("Switch (Int)", ":/elements/logic/switch.png"); } void Registry::loadPlugins() { fs::path const pluginsDir{ "../plugins" }; if (!fs::is_directory(pluginsDir)) return; for (auto const &entry : fs::directory_iterator(pluginsDir)) { if (!fs::is_regular_file(entry)) continue; boost::system::error_code error{}; auto plugin = std::make_shared<dll::shared_library>(entry, error, dll::load_mode::append_decorations); if (error.value() != 0 || !plugin->has("register_plugin")) continue; auto registerPlugin = plugin->get<void(core::Registry &)>("register_plugin"); registerPlugin(*this); m_plugins.emplace_back(std::move(plugin)); } } } // namespace core <|endoftext|>
<commit_before>void runLocal() { // header location gInterpreter->ProcessLine(".include $ROOTSYS/include"); gInterpreter->ProcessLine(".include $ALICE_ROOT/include"); // create the analysis manager AliAnalysisManager *mgr = new AliAnalysisManager("AnalysisBG"); AliAODInputHandler *aodH = new AliAODInputHandler(); mgr->SetInputEventHandler(aodH); // compile the class (locally) with debug symbols gInterpreter->LoadMacro("AliAnalysisTaskLegendreCoef.cxx++g"); // load the addtask macro and create the task AliAnalysisTaskLegendreCoef *task = reinterpret_cast<AliAnalysisTaskLegendreCoef*>(gInterpreter->ExecuteMacro("macros/AddTaskLegendreCoef.C")); task->SetPileUpRead(kTRUE); // task->SetBuildBackground(kTRUE); TFile *f1 = new TFile("/home/alidock/localtest/AnalysisResults9599.root"); TList* histlist = (TList*)f1->Get("LongFluctuations/EtaBG"); if(!histlist) printf("error!!!!!!!! no list\n"); if(!(TH2D*)histlist->FindObject("PosBGHistOut")) printf("error!!!!!!!! no hist\n"); task->GetPosBackground((TH2D*)histlist->FindObject("PosBGHistOut")); task->GetNegBackground((TH2D*)histlist->FindObject("NegBGHistOut")); task->GetChargedBackground((TH2D*)histlist->FindObject("ChargedBGHistOut")); task->SetBuildLegendre(kTRUE); if(!mgr->InitAnalysis()) return; mgr->SetDebugLevel(2); mgr->PrintStatus(); mgr->SetUseProgressBar(1, 25); // if you want to run locally, we need to define some input TChain* chain = new TChain("aodTree"); chain->Add("/home/alidock/longfluc/AliAOD.root"); mgr->StartAnalysis("local", chain); } <commit_msg>Update runLocal.C<commit_after>void runLocal() { // header location gInterpreter->ProcessLine(".include $ROOTSYS/include"); gInterpreter->ProcessLine(".include $ALICE_ROOT/include"); // create the analysis manager AliAnalysisManager *mgr = new AliAnalysisManager("AnalysisBG"); AliAODInputHandler *aodH = new AliAODInputHandler(); mgr->SetInputEventHandler(aodH); // compile the class (locally) with debug symbols gInterpreter->LoadMacro("AliAnalysisTaskLegendreCoef.cxx++g"); // load the addtask macro and create the task AliAnalysisTaskLegendreCoef *task = reinterpret_cast<AliAnalysisTaskLegendreCoef*>(gInterpreter->ExecuteMacro("macros/AddTaskLegendreCoef.C")); task->SetPileUpRead(kTRUE); // task->SetBuildBackground(kTRUE); TFile *f1 = new TFile("/home/alidock/localtest/AnalysisResults9775.root"); TList* histlist = (TList*)f1->Get("LongFluctuations/EtaBG"); if(!histlist) printf("error!!!!!!!! no list\n"); if(!(TH2D*)histlist->FindObject("PosBGHistOut")) printf("error!!!!!!!! no hist\n"); task->GetPosBackground((TH2D*)histlist->FindObject("PosBGHistOut")); task->GetNegBackground((TH2D*)histlist->FindObject("NegBGHistOut")); task->GetChargedBackground((TH2D*)histlist->FindObject("ChargedBGHistOut")); task->GetNeventsCentHist((TH1D*)histlist->FindObject("NeventsCentHist")); task->SetBuildLegendre(kTRUE); if(!mgr->InitAnalysis()) return; mgr->SetDebugLevel(2); mgr->PrintStatus(); mgr->SetUseProgressBar(1, 25); // if you want to run locally, we need to define some input TChain* chain = new TChain("aodTree"); chain->Add("/home/alidock/longfluc/AliAOD.root"); mgr->StartAnalysis("local", chain); } <|endoftext|>
<commit_before>// Sh: A GPU metaprogramming language. // // Copyright 2003-2005 Serious Hack Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, // MA 02110-1301, USA ////////////////////////////////////////////////////////////////////////////// #include "ShMemory.hpp" #include "ShDebug.hpp" #include "ShVariant.hpp" #include <cstring> #include <algorithm> namespace SH { ////////////////////// // --- ShMemory --- // ////////////////////// ShMemory::~ShMemory() { for (StorageList::iterator I = m_storages.begin(); I != m_storages.end(); ++I) { (*I)->orphan(); // We don't need these storages to tell us that they are // going away, since we're going away ourselves. } } int ShMemory::timestamp() const { return m_timestamp; } ShPointer<ShStorage> ShMemory::findStorage(const std::string& id) { for (StorageList::iterator I = m_storages.begin(); I != m_storages.end(); ++I) { if ((*I)->id() == id) return *I; } return 0; } ShMemory::ShMemory() : m_timestamp(0) { } int ShMemory::increment_timestamp() { return ++m_timestamp; } void ShMemory::addStorage(const ShPointer<ShStorage>& storage) { m_storages.push_back(storage); } void ShMemory::removeStorage(const ShPointer<ShStorage>& storage) { StorageList::iterator I = std::find(m_storages.begin(), m_storages.end(), storage); if (I == m_storages.end()) return; (*I)->orphan(); m_storages.erase(I); // TODO: fix this, refcount lossage. } void ShMemory::add_dep(ShMemoryDep* dep) { dependencies.push_back(dep); } void ShMemory::flush() { ShHostStoragePtr storage = shref_dynamic_cast<ShHostStorage>(findStorage("host")); storage->dirtyall(); for(std::list<ShMemoryDep*>::iterator i = dependencies.begin(); i != dependencies.end(); i++) (*i)->memory_update(); } //////////////////////// // --- ShTransfer --- // //////////////////////// ShTransfer::ShTransfer(const std::string& from, const std::string& to) { ShStorage::addTransfer(from, to, this); } /////////////////////// // --- ShStorage --- // /////////////////////// ShStorage::ShStorage() : m_timestamp(-1) { } ShStorage::~ShStorage() { if (m_memory) { m_memory->removeStorage(this); } } int ShStorage::timestamp() const { return m_timestamp; } void ShStorage::setTimestamp(int timestamp) { SH_DEBUG_ASSERT(timestamp >= m_timestamp); // TODO: Assert this assertion :) m_timestamp = timestamp; } const ShMemory* ShStorage::memory() const { return m_memory; } ShMemory* ShStorage::memory() { return m_memory; } void ShStorage::orphan() { m_memory = 0; } void ShStorage::sync() const { SH_DEBUG_ASSERT(m_memory); if (m_memory->timestamp() == timestamp()) return; // We are already in sync // Out of sync. Find the cheapest other storage to sync from const ShStorage* source = 0; int transfer_cost = -1; ShMemory::StorageList::const_iterator I; for (I = m_memory->m_storages.begin(); I != m_memory->m_storages.end(); ++I) { const ShStorage* other = I->object(); if (other == this) continue; if (other->timestamp() < m_memory->timestamp()) continue; int local_cost = cost(other, this); if (local_cost < 0) continue; // Can't transfer from that storage. if (!source || local_cost < transfer_cost) { source = other; transfer_cost = local_cost; } } // For now: SH_DEBUG_ASSERT(source); // TODO: In the future, traverse the graph of transfers to find a // cheap, working one. // Do the actual transfer // Need to cast away the constness since we actually want to write TO this, // although all we're doing is "updating" it to the latest version. if (!transfer(source, const_cast<ShStorage*>(this))) { SH_DEBUG_WARN("Transfer from " << source << " to " << this << " failed!"); } } void ShStorage::dirty() { // TODO: Maybe in the future check that the sync worked sync(); dirtyall(); } void ShStorage::dirtyall() { m_timestamp = m_memory->increment_timestamp(); } int ShStorage::cost(const ShStorage* from, const ShStorage* to) { if (!from) return -1; if (!to) return -1; if (!m_transfers) return false; TransferMap::const_iterator I = m_transfers->find(std::make_pair(from->id(), to->id())); if (I == m_transfers->end()) return -1; return I->second->cost(from, to); } bool ShStorage::transfer(const ShStorage* from, ShStorage* to) { if (!from) return false; if (!to) return false; if (!m_transfers) return false; TransferMap::const_iterator I = m_transfers->find(std::make_pair(from->id(), to->id())); if (I == m_transfers->end()) return false; // No transfer function? // TODO: Should we only allow transfers between storages // corresponding to the same memory? // Probably. if (I->second->transfer(from, to)) { to->setTimestamp(from->timestamp()); return true; } else { return false; } } void ShStorage::addTransfer(const std::string& from, const std::string& to, ShTransfer* transfer) { if (!m_transfers) m_transfers = new TransferMap(); (*m_transfers)[std::make_pair(from, to)] = transfer; } ShStorage::ShStorage(ShMemory* memory, ShValueType value_type) : m_value_type(value_type), m_value_size(shTypeInfo(value_type)->datasize()), m_memory(memory), m_timestamp(-1) { m_memory->addStorage(this); } void ShStorage::value_type(ShValueType value_type) { m_value_type = value_type; m_value_size = shTypeInfo(value_type)->datasize(); } ShStorage::TransferMap* ShStorage::m_transfers = 0; /////////////////////////// // --- ShHostStorage --- // /////////////////////////// ShHostStorage::ShHostStorage(ShMemory* memory, std::size_t length, ShValueType value_type) : ShStorage(memory, value_type), m_length(length), m_data(new char[length]), m_managed(true) { } ShHostStorage::ShHostStorage(ShMemory* memory, std::size_t length, void* data, ShValueType value_type) : ShStorage(memory, value_type), m_length(length), m_data(data), m_managed(false) { } ShHostStorage::~ShHostStorage() { if (m_managed) { delete [] reinterpret_cast<char*>(m_data); } } std::string ShHostStorage::id() const { return "host"; } std::size_t ShHostStorage::length() const { return m_length; } const void* ShHostStorage::data() const { return m_data; } void* ShHostStorage::data() { return m_data; } ////////////////////////// // --- ShHostMemory --- // ////////////////////////// #pragma warning(disable:4355) // Disable useless VC warning ShHostMemory::ShHostMemory(std::size_t length, ShValueType value_type) : m_hostStorage(new ShHostStorage(this, length, value_type)) { // Make the host storage represent the newest version of the memory m_hostStorage->dirtyall(); } ShHostMemory::ShHostMemory(std::size_t length, void* data, ShValueType value_type) : m_hostStorage(new ShHostStorage(this, length, data, value_type)) { // Make the host storage represent the newest version of the memory m_hostStorage->dirtyall(); } ShHostMemory::~ShHostMemory() { } ShHostStoragePtr ShHostMemory::hostStorage() { return m_hostStorage; } ShPointer<const ShHostStorage> ShHostMemory::hostStorage() const { return m_hostStorage; } class ShHostHostTransfer : public ShTransfer { public: bool transfer(const ShStorage* from, ShStorage* to) { const ShHostStorage* host_from = dynamic_cast<const ShHostStorage*>(from); ShHostStorage* host_to = dynamic_cast<ShHostStorage*>(to); // Check that casts succeeded if (!host_from) return false; if (!host_to) return false; if (host_from->value_type() == host_to->value_type()) { // Check that sizes match if (host_from->length() != host_to->length()) { std::cerr << "From length = " << host_from->length() << ", To length = " << host_to->length() << std::endl; return false; } std::memcpy(host_to->data(), host_from->data(), host_to->length()); } else { // Do the type conversion const std::size_t nb_values = host_from->length() / host_from->value_size(); ShVariantPtr from_variant = shVariantFactory(host_from->value_type(), SH_MEM)-> generate(nb_values, const_cast<void*>(host_from->data()), false); ShVariantPtr to_variant = shVariantFactory(host_to->value_type(), SH_MEM)-> generate(nb_values, host_to->data(), false); to_variant->set(from_variant); } return true; } int cost(const ShStorage* from, const ShStorage* to) { return 10; // Maybe this should be 0, but you never know... } private: ShHostHostTransfer() : ShTransfer("host", "host") { } static ShHostHostTransfer* instance; }; ShHostHostTransfer* ShHostHostTransfer::instance = new ShHostHostTransfer(); } <commit_msg>Only enable the pragma on Windows<commit_after>// Sh: A GPU metaprogramming language. // // Copyright 2003-2005 Serious Hack Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, // MA 02110-1301, USA ////////////////////////////////////////////////////////////////////////////// #include "ShMemory.hpp" #include "ShDebug.hpp" #include "ShVariant.hpp" #include <cstring> #include <algorithm> namespace SH { ////////////////////// // --- ShMemory --- // ////////////////////// ShMemory::~ShMemory() { for (StorageList::iterator I = m_storages.begin(); I != m_storages.end(); ++I) { (*I)->orphan(); // We don't need these storages to tell us that they are // going away, since we're going away ourselves. } } int ShMemory::timestamp() const { return m_timestamp; } ShPointer<ShStorage> ShMemory::findStorage(const std::string& id) { for (StorageList::iterator I = m_storages.begin(); I != m_storages.end(); ++I) { if ((*I)->id() == id) return *I; } return 0; } ShMemory::ShMemory() : m_timestamp(0) { } int ShMemory::increment_timestamp() { return ++m_timestamp; } void ShMemory::addStorage(const ShPointer<ShStorage>& storage) { m_storages.push_back(storage); } void ShMemory::removeStorage(const ShPointer<ShStorage>& storage) { StorageList::iterator I = std::find(m_storages.begin(), m_storages.end(), storage); if (I == m_storages.end()) return; (*I)->orphan(); m_storages.erase(I); // TODO: fix this, refcount lossage. } void ShMemory::add_dep(ShMemoryDep* dep) { dependencies.push_back(dep); } void ShMemory::flush() { ShHostStoragePtr storage = shref_dynamic_cast<ShHostStorage>(findStorage("host")); storage->dirtyall(); for(std::list<ShMemoryDep*>::iterator i = dependencies.begin(); i != dependencies.end(); i++) (*i)->memory_update(); } //////////////////////// // --- ShTransfer --- // //////////////////////// ShTransfer::ShTransfer(const std::string& from, const std::string& to) { ShStorage::addTransfer(from, to, this); } /////////////////////// // --- ShStorage --- // /////////////////////// ShStorage::ShStorage() : m_timestamp(-1) { } ShStorage::~ShStorage() { if (m_memory) { m_memory->removeStorage(this); } } int ShStorage::timestamp() const { return m_timestamp; } void ShStorage::setTimestamp(int timestamp) { SH_DEBUG_ASSERT(timestamp >= m_timestamp); // TODO: Assert this assertion :) m_timestamp = timestamp; } const ShMemory* ShStorage::memory() const { return m_memory; } ShMemory* ShStorage::memory() { return m_memory; } void ShStorage::orphan() { m_memory = 0; } void ShStorage::sync() const { SH_DEBUG_ASSERT(m_memory); if (m_memory->timestamp() == timestamp()) return; // We are already in sync // Out of sync. Find the cheapest other storage to sync from const ShStorage* source = 0; int transfer_cost = -1; ShMemory::StorageList::const_iterator I; for (I = m_memory->m_storages.begin(); I != m_memory->m_storages.end(); ++I) { const ShStorage* other = I->object(); if (other == this) continue; if (other->timestamp() < m_memory->timestamp()) continue; int local_cost = cost(other, this); if (local_cost < 0) continue; // Can't transfer from that storage. if (!source || local_cost < transfer_cost) { source = other; transfer_cost = local_cost; } } // For now: SH_DEBUG_ASSERT(source); // TODO: In the future, traverse the graph of transfers to find a // cheap, working one. // Do the actual transfer // Need to cast away the constness since we actually want to write TO this, // although all we're doing is "updating" it to the latest version. if (!transfer(source, const_cast<ShStorage*>(this))) { SH_DEBUG_WARN("Transfer from " << source << " to " << this << " failed!"); } } void ShStorage::dirty() { // TODO: Maybe in the future check that the sync worked sync(); dirtyall(); } void ShStorage::dirtyall() { m_timestamp = m_memory->increment_timestamp(); } int ShStorage::cost(const ShStorage* from, const ShStorage* to) { if (!from) return -1; if (!to) return -1; if (!m_transfers) return false; TransferMap::const_iterator I = m_transfers->find(std::make_pair(from->id(), to->id())); if (I == m_transfers->end()) return -1; return I->second->cost(from, to); } bool ShStorage::transfer(const ShStorage* from, ShStorage* to) { if (!from) return false; if (!to) return false; if (!m_transfers) return false; TransferMap::const_iterator I = m_transfers->find(std::make_pair(from->id(), to->id())); if (I == m_transfers->end()) return false; // No transfer function? // TODO: Should we only allow transfers between storages // corresponding to the same memory? // Probably. if (I->second->transfer(from, to)) { to->setTimestamp(from->timestamp()); return true; } else { return false; } } void ShStorage::addTransfer(const std::string& from, const std::string& to, ShTransfer* transfer) { if (!m_transfers) m_transfers = new TransferMap(); (*m_transfers)[std::make_pair(from, to)] = transfer; } ShStorage::ShStorage(ShMemory* memory, ShValueType value_type) : m_value_type(value_type), m_value_size(shTypeInfo(value_type)->datasize()), m_memory(memory), m_timestamp(-1) { m_memory->addStorage(this); } void ShStorage::value_type(ShValueType value_type) { m_value_type = value_type; m_value_size = shTypeInfo(value_type)->datasize(); } ShStorage::TransferMap* ShStorage::m_transfers = 0; /////////////////////////// // --- ShHostStorage --- // /////////////////////////// ShHostStorage::ShHostStorage(ShMemory* memory, std::size_t length, ShValueType value_type) : ShStorage(memory, value_type), m_length(length), m_data(new char[length]), m_managed(true) { } ShHostStorage::ShHostStorage(ShMemory* memory, std::size_t length, void* data, ShValueType value_type) : ShStorage(memory, value_type), m_length(length), m_data(data), m_managed(false) { } ShHostStorage::~ShHostStorage() { if (m_managed) { delete [] reinterpret_cast<char*>(m_data); } } std::string ShHostStorage::id() const { return "host"; } std::size_t ShHostStorage::length() const { return m_length; } const void* ShHostStorage::data() const { return m_data; } void* ShHostStorage::data() { return m_data; } ////////////////////////// // --- ShHostMemory --- // ////////////////////////// #ifdef WIN32 # pragma warning(disable:4355) #endif ShHostMemory::ShHostMemory(std::size_t length, ShValueType value_type) : m_hostStorage(new ShHostStorage(this, length, value_type)) { // Make the host storage represent the newest version of the memory m_hostStorage->dirtyall(); } ShHostMemory::ShHostMemory(std::size_t length, void* data, ShValueType value_type) : m_hostStorage(new ShHostStorage(this, length, data, value_type)) { // Make the host storage represent the newest version of the memory m_hostStorage->dirtyall(); } ShHostMemory::~ShHostMemory() { } ShHostStoragePtr ShHostMemory::hostStorage() { return m_hostStorage; } ShPointer<const ShHostStorage> ShHostMemory::hostStorage() const { return m_hostStorage; } class ShHostHostTransfer : public ShTransfer { public: bool transfer(const ShStorage* from, ShStorage* to) { const ShHostStorage* host_from = dynamic_cast<const ShHostStorage*>(from); ShHostStorage* host_to = dynamic_cast<ShHostStorage*>(to); // Check that casts succeeded if (!host_from) return false; if (!host_to) return false; if (host_from->value_type() == host_to->value_type()) { // Check that sizes match if (host_from->length() != host_to->length()) { std::cerr << "From length = " << host_from->length() << ", To length = " << host_to->length() << std::endl; return false; } std::memcpy(host_to->data(), host_from->data(), host_to->length()); } else { // Do the type conversion const std::size_t nb_values = host_from->length() / host_from->value_size(); ShVariantPtr from_variant = shVariantFactory(host_from->value_type(), SH_MEM)-> generate(nb_values, const_cast<void*>(host_from->data()), false); ShVariantPtr to_variant = shVariantFactory(host_to->value_type(), SH_MEM)-> generate(nb_values, host_to->data(), false); to_variant->set(from_variant); } return true; } int cost(const ShStorage* from, const ShStorage* to) { return 10; // Maybe this should be 0, but you never know... } private: ShHostHostTransfer() : ShTransfer("host", "host") { } static ShHostHostTransfer* instance; }; ShHostHostTransfer* ShHostHostTransfer::instance = new ShHostHostTransfer(); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "load.h" #include <cstdio> #include <cstring> #include <ctime> #include <iostream> #include <memory> #include <string> #include <vector> #include "cas/dimension.h" #include "cellml.h" #include "compiler.h" #include "database.h" #include "db/driver.h" #include "db/statement-driver.h" #include "file.h" #include "layout.h" #include "load/param.h" #include "load/var.h" #include "phml.h" #include "phz.h" #include "runtime.h" #include "sbml.h" using std::cerr; using std::endl; using std::fclose; using std::fopen; using std::fprintf; using std::perror; using std::sprintf; namespace flint { namespace load { namespace { class ConfigWriter : db::StatementDriver { public: explicit ConfigWriter(sqlite3 *db) : db::StatementDriver(db, "UPDATE config SET method = ?, length = ?, step = ?") {} bool Write(const char *method, const char *length, const char *step) { int e; e = sqlite3_bind_text(stmt(), 1, method, -1, SQLITE_STATIC); if (e != SQLITE_OK) { cerr << "failed to bind method: " << e << endl; return false; } e = sqlite3_bind_text(stmt(), 2, length, -1, SQLITE_STATIC); if (e != SQLITE_OK) { cerr << "failed to bind length: " << e << endl; return false; } e = sqlite3_bind_text(stmt(), 3, step, -1, SQLITE_STATIC); if (e != SQLITE_OK) { cerr << "failed to bind step: " << e << endl; return false; } e = sqlite3_step(stmt()); if (e != SQLITE_DONE) { cerr << "failed to step statement: " << e << endl; return false; } sqlite3_reset(stmt()); return true; } }; class Loader { public: static const int kFilenameLength = 64; explicit Loader(int dir) : dir_(new char[kFilenameLength]) , after_bc_(new char[kFilenameLength]) , before_bc_(new char[kFilenameLength]) , const_bc_(new char[kFilenameLength]) , init_(new char[kFilenameLength]) , layout_(new char[kFilenameLength]) , model_(new char[kFilenameLength]) , modeldb_(new char[kFilenameLength]) , nc_(new char[kFilenameLength]) , param_(new char[kFilenameLength]) , phz_(new char[kFilenameLength]) , unitoftime_(new char[kFilenameLength]) , var_(new char[kFilenameLength]) { if (dir) { sprintf(dir_.get(), "%d", dir); } else { sprintf(dir_.get(), "."); } sprintf(after_bc_.get(), "%s/after-bc", dir_.get()); sprintf(before_bc_.get(), "%s/before-bc", dir_.get()); sprintf(const_bc_.get(), "%s/const-bc", dir_.get()); sprintf(init_.get(), "%s/init", dir_.get()); sprintf(layout_.get(), "%s/layout", dir_.get()); sprintf(model_.get(), "%s/model", dir_.get()); sprintf(modeldb_.get(), "%s/model.db", dir_.get()); sprintf(nc_.get(), "%s/nc", dir_.get()); sprintf(param_.get(), "%s/param", dir_.get()); sprintf(phz_.get(), "%s/phz", dir_.get()); sprintf(unitoftime_.get(), "%s/unitoftime", dir_.get()); sprintf(var_.get(), "%s/var", dir_.get()); } const char *model() const {return model_.get();} const char *modeldb() const {return modeldb_.get();} const char *param() const {return param_.get();} const char *phz() const {return phz_.get();} const char *var() const {return var_.get();} bool LoadCellml(sqlite3 *db) { if (!cellml::Read(db)) return false; if (!layout::Generate(db, layout_.get())) return false; { cas::DimensionAnalyzer da; if (!da.Load(db)) return false; compiler::Compiler c(&da); if (!c.Compile(db, "input_ivs", compiler::Method::kAssign, const_bc_.get())) return false; } return runtime::Init(db, 0, layout_.get(), const_bc_.get(), init_.get()); } bool LoadPhml(sqlite3 *db) { if (!phml::Read(db)) return false; int seed = static_cast<int>(std::clock()); if (!phml::Nc(db, nc_.get(), &seed)) return false; if (!phml::UnitOfTime(db, unitoftime_.get())) return false; if (!phml::LengthAndStep(db, nc_.get(), unitoftime_.get())) return false; if (!layout::Generate(db, layout_.get())) return false; { cas::DimensionAnalyzer da; if (!da.Load(db)) return false; compiler::Compiler c(&da); if (!c.Compile(db, "input_ivs", compiler::Method::kAssign, const_bc_.get())) return false; if (!c.Compile(db, "after_eqs", compiler::Method::kEvent, after_bc_.get())) return false; if (!c.Compile(db, "before_eqs", compiler::Method::kEvent, before_bc_.get())) return false; } return runtime::Init(db, seed, layout_.get(), const_bc_.get(), init_.get()); } bool LoadSbml(sqlite3 *db) { if (!flint::sbml::Read(db)) return false; if (!layout::Generate(db, layout_.get())) return false; { cas::DimensionAnalyzer da; if (!da.Load(db)) return false; compiler::Compiler c(&da); if (!c.Compile(db, "input_ivs", compiler::Method::kAssign, const_bc_.get())) return false; } return runtime::Init(db, 0, layout_.get(), const_bc_.get(), init_.get()); } private: std::unique_ptr<char[]> dir_; std::unique_ptr<char[]> after_bc_; std::unique_ptr<char[]> before_bc_; std::unique_ptr<char[]> const_bc_; std::unique_ptr<char[]> init_; std::unique_ptr<char[]> layout_; std::unique_ptr<char[]> model_; std::unique_ptr<char[]> modeldb_; std::unique_ptr<char[]> nc_; std::unique_ptr<char[]> param_; std::unique_ptr<char[]> phz_; std::unique_ptr<char[]> unitoftime_; std::unique_ptr<char[]> var_; }; } bool Load(const char *given_file, ConfigMode mode, int dir) { Loader loader(dir); db::Driver driver(loader.modeldb()); sqlite3 *db = driver.db(); if (!SaveGivenFile(db, given_file)) return false; file::Format format; if (!file::Txt(given_file, &format, dir)) return false; switch (format) { case file::kIsml: case file::kPhml: if (!loader.LoadPhml(db)) return false; break; case file::kPhz: if (!phz::Read(db, loader.phz())) return false; if (!loader.LoadPhml(db)) return false; break; case file::kCellml: if (!loader.LoadCellml(db)) return false; if (mode == kRun) { ConfigWriter writer(db); if (!writer.Write("rk4", "2000", "0.01")) return false; } break; case file::kSbml: if (!loader.LoadSbml(db)) return false; if (mode == kRun) { ConfigWriter writer(db); if (!writer.Write("rk4", "100", "0.01")) return false; } break; default: cerr << "unexpected file format: " << format << endl; return false; } if (mode == kOpen) { if (!Param(db, loader.param())) return false; if (!Var(db, loader.var())) return false; } return true; } } } <commit_msg>Drop unused lines<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "load.h" #include <cstdio> #include <cstring> #include <ctime> #include <iostream> #include <memory> #include <string> #include <vector> #include "cas/dimension.h" #include "cellml.h" #include "compiler.h" #include "database.h" #include "db/driver.h" #include "db/statement-driver.h" #include "file.h" #include "layout.h" #include "load/param.h" #include "load/var.h" #include "phml.h" #include "phz.h" #include "runtime.h" #include "sbml.h" using std::cerr; using std::endl; using std::sprintf; namespace flint { namespace load { namespace { class ConfigWriter : db::StatementDriver { public: explicit ConfigWriter(sqlite3 *db) : db::StatementDriver(db, "UPDATE config SET method = ?, length = ?, step = ?") {} bool Write(const char *method, const char *length, const char *step) { int e; e = sqlite3_bind_text(stmt(), 1, method, -1, SQLITE_STATIC); if (e != SQLITE_OK) { cerr << "failed to bind method: " << e << endl; return false; } e = sqlite3_bind_text(stmt(), 2, length, -1, SQLITE_STATIC); if (e != SQLITE_OK) { cerr << "failed to bind length: " << e << endl; return false; } e = sqlite3_bind_text(stmt(), 3, step, -1, SQLITE_STATIC); if (e != SQLITE_OK) { cerr << "failed to bind step: " << e << endl; return false; } e = sqlite3_step(stmt()); if (e != SQLITE_DONE) { cerr << "failed to step statement: " << e << endl; return false; } sqlite3_reset(stmt()); return true; } }; class Loader { public: static const int kFilenameLength = 64; explicit Loader(int dir) : dir_(new char[kFilenameLength]) , after_bc_(new char[kFilenameLength]) , before_bc_(new char[kFilenameLength]) , const_bc_(new char[kFilenameLength]) , init_(new char[kFilenameLength]) , layout_(new char[kFilenameLength]) , model_(new char[kFilenameLength]) , modeldb_(new char[kFilenameLength]) , nc_(new char[kFilenameLength]) , param_(new char[kFilenameLength]) , phz_(new char[kFilenameLength]) , unitoftime_(new char[kFilenameLength]) , var_(new char[kFilenameLength]) { if (dir) { sprintf(dir_.get(), "%d", dir); } else { sprintf(dir_.get(), "."); } sprintf(after_bc_.get(), "%s/after-bc", dir_.get()); sprintf(before_bc_.get(), "%s/before-bc", dir_.get()); sprintf(const_bc_.get(), "%s/const-bc", dir_.get()); sprintf(init_.get(), "%s/init", dir_.get()); sprintf(layout_.get(), "%s/layout", dir_.get()); sprintf(model_.get(), "%s/model", dir_.get()); sprintf(modeldb_.get(), "%s/model.db", dir_.get()); sprintf(nc_.get(), "%s/nc", dir_.get()); sprintf(param_.get(), "%s/param", dir_.get()); sprintf(phz_.get(), "%s/phz", dir_.get()); sprintf(unitoftime_.get(), "%s/unitoftime", dir_.get()); sprintf(var_.get(), "%s/var", dir_.get()); } const char *model() const {return model_.get();} const char *modeldb() const {return modeldb_.get();} const char *param() const {return param_.get();} const char *phz() const {return phz_.get();} const char *var() const {return var_.get();} bool LoadCellml(sqlite3 *db) { if (!cellml::Read(db)) return false; if (!layout::Generate(db, layout_.get())) return false; { cas::DimensionAnalyzer da; if (!da.Load(db)) return false; compiler::Compiler c(&da); if (!c.Compile(db, "input_ivs", compiler::Method::kAssign, const_bc_.get())) return false; } return runtime::Init(db, 0, layout_.get(), const_bc_.get(), init_.get()); } bool LoadPhml(sqlite3 *db) { if (!phml::Read(db)) return false; int seed = static_cast<int>(std::clock()); if (!phml::Nc(db, nc_.get(), &seed)) return false; if (!phml::UnitOfTime(db, unitoftime_.get())) return false; if (!phml::LengthAndStep(db, nc_.get(), unitoftime_.get())) return false; if (!layout::Generate(db, layout_.get())) return false; { cas::DimensionAnalyzer da; if (!da.Load(db)) return false; compiler::Compiler c(&da); if (!c.Compile(db, "input_ivs", compiler::Method::kAssign, const_bc_.get())) return false; if (!c.Compile(db, "after_eqs", compiler::Method::kEvent, after_bc_.get())) return false; if (!c.Compile(db, "before_eqs", compiler::Method::kEvent, before_bc_.get())) return false; } return runtime::Init(db, seed, layout_.get(), const_bc_.get(), init_.get()); } bool LoadSbml(sqlite3 *db) { if (!flint::sbml::Read(db)) return false; if (!layout::Generate(db, layout_.get())) return false; { cas::DimensionAnalyzer da; if (!da.Load(db)) return false; compiler::Compiler c(&da); if (!c.Compile(db, "input_ivs", compiler::Method::kAssign, const_bc_.get())) return false; } return runtime::Init(db, 0, layout_.get(), const_bc_.get(), init_.get()); } private: std::unique_ptr<char[]> dir_; std::unique_ptr<char[]> after_bc_; std::unique_ptr<char[]> before_bc_; std::unique_ptr<char[]> const_bc_; std::unique_ptr<char[]> init_; std::unique_ptr<char[]> layout_; std::unique_ptr<char[]> model_; std::unique_ptr<char[]> modeldb_; std::unique_ptr<char[]> nc_; std::unique_ptr<char[]> param_; std::unique_ptr<char[]> phz_; std::unique_ptr<char[]> unitoftime_; std::unique_ptr<char[]> var_; }; } bool Load(const char *given_file, ConfigMode mode, int dir) { Loader loader(dir); db::Driver driver(loader.modeldb()); sqlite3 *db = driver.db(); if (!SaveGivenFile(db, given_file)) return false; file::Format format; if (!file::Txt(given_file, &format, dir)) return false; switch (format) { case file::kIsml: case file::kPhml: if (!loader.LoadPhml(db)) return false; break; case file::kPhz: if (!phz::Read(db, loader.phz())) return false; if (!loader.LoadPhml(db)) return false; break; case file::kCellml: if (!loader.LoadCellml(db)) return false; if (mode == kRun) { ConfigWriter writer(db); if (!writer.Write("rk4", "2000", "0.01")) return false; } break; case file::kSbml: if (!loader.LoadSbml(db)) return false; if (mode == kRun) { ConfigWriter writer(db); if (!writer.Write("rk4", "100", "0.01")) return false; } break; default: cerr << "unexpected file format: " << format << endl; return false; } if (mode == kOpen) { if (!Param(db, loader.param())) return false; if (!Var(db, loader.var())) return false; } return true; } } } <|endoftext|>
<commit_before>/** ========================================================================== * 2015 by KjellKod.cc * * This code is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * ============================================================================* * PUBLIC DOMAIN and Not copywrited. First published at KjellKod.cc * ********************************************* */ #include "FilterTest.h" #include "g3sinks/LogRotateWithFilter.h" #include <iostream> #include <cerrno> #include <g3log/std2_make_unique.hpp> #include "RotateTestHelper.h" #if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) && !defined(__MINGW32__) #define F_OK 0 #else #include <unistd.h> #endif #if (defined(CHANGE_G3LOG_DEBUG_TO_DBUG)) #define DEBUG DBUG #endif using namespace RotateTestHelper; namespace { // anonymous g3::LogMessageMover CreateLogEntry(const LEVELS level, std::string content, std::string file, int line, std::string function) { auto message = g3::LogMessage(file, line, function, level); message.write().append(content); return g3::MoveOnCopy<g3::LogMessage>(std::move(message)); } #define CREATE_LOG_ENTRY(level, content) CreateLogEntry(level, content, __FILE__, __LINE__, __FUNCTION__) } // anonymous TEST_F(FilterTest, CreateObject) { std::string logfilename; { auto logRotatePtr = std2::make_unique<LogRotate>(_filename, _directory); LogRotateWithFilter logWithFilter(std::move(logRotatePtr), {}); } // RAII flush of log auto name = std::string{_directory + _filename + ".log"}; int check = access(name.c_str(), F_OK); // check that the file exists EXPECT_EQ(check, 0) << std::strerror(errno) << " : " << name; } TEST_F(FilterTest, CreateObjectUsingHelper) { auto name = std::string{_directory +"/" + _filename + ".log"}; int check = access(name.c_str(), F_OK); // check that the file exists EXPECT_NE(check, 0) << std::strerror(errno) << " : " << name; { auto filterSinkPtr = LogRotateWithFilter::CreateLogRotateWithFilter(_filename, _directory, {}); } // raii check = access(name.c_str(), F_OK); // check that the file exists EXPECT_EQ(check, 0) << std::strerror(errno) << " : " << name; auto content = ReadContent(name); EXPECT_TRUE(Exists(content, "g3log: created log file at:")) << ", content: [" << "]" << ", name: " << name; EXPECT_TRUE(Exists(content, "file shutdown at:")) << ", ontent: [" << "]"<< ", name: " << name; } TEST_F(FilterTest, NothingFiltered) { { auto filterSinkPtr = LogRotateWithFilter::CreateLogRotateWithFilter(_filename, _directory, {}); auto message0 = CREATE_LOG_ENTRY(INFO, "Hello World"); filterSinkPtr->save(message0); auto message1 = std::move(CREATE_LOG_ENTRY(DEBUG, "Hello D World")); filterSinkPtr->save(message1); auto message2 = std::move(CREATE_LOG_ENTRY(WARNING, "Hello W World")); filterSinkPtr->save(message2); auto message3 = std::move(CREATE_LOG_ENTRY(FATAL, "Hello F World")); filterSinkPtr->save(message3); } // raii auto name = std::string{_directory + _filename + ".log"}; auto content = ReadContent(name); EXPECT_TRUE(Exists(content, "Hello World")) << content; EXPECT_TRUE(Exists(content, "Hello D World")) << content; EXPECT_TRUE(Exists(content, "Hello W World")) << content; EXPECT_TRUE(Exists(content, "Hello F World")) << content; } TEST_F(FilterTest, FilteredAndNotFiltered) { { auto filterSinkPtr = LogRotateWithFilter::CreateLogRotateWithFilter(_filename, _directory, {DEBUG, INFO, WARNING, FATAL}); auto message0 = CREATE_LOG_ENTRY(INFO, "Hello World"); filterSinkPtr->save(message0); auto message1 = std::move(CREATE_LOG_ENTRY(DEBUG, "Hello D World")); filterSinkPtr->save(message1); auto message2 = std::move(CREATE_LOG_ENTRY(WARNING, "Hello W World")); filterSinkPtr->save(message2); auto message3 = std::move(CREATE_LOG_ENTRY(FATAL, "Hello F World")); filterSinkPtr->save(message3); auto newLevel = LEVELS{123, "MadeUpLevel"}; auto message4 = std::move(CREATE_LOG_ENTRY(newLevel, "Hello New World")); filterSinkPtr->save(message4); } // raii auto name = std::string{_directory + _filename + ".log"}; auto content = ReadContent(name); EXPECT_FALSE(Exists(content, "Hello World")) << content; EXPECT_FALSE(Exists(content, "Hello D World")) << content; EXPECT_FALSE(Exists(content, "Hello W World")) << content; EXPECT_FALSE(Exists(content, "Hello F World")) << content; // Not filtered will exist EXPECT_TRUE(Exists(content, "Hello New World")) << content; const auto level1 = INFO; const auto level2 = INFO; EXPECT_TRUE(level1 == level2); } TEST_F(FilterTest, setFlushPolicy__default__every_time) { auto filterSinkPtr = LogRotateWithFilter::CreateLogRotateWithFilter(_filename, _directory, {}); auto logfilename = filterSinkPtr->logFileName(); for (size_t i = 0; i < 10; ++i) { std::string msg{"message: "}; msg += std::to_string(i) + "\n"; filterSinkPtr->save(CREATE_LOG_ENTRY(INFO, msg)); auto content = ReadContent(logfilename); #if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) && !defined(__MINGW32__) msg.replace(msg.find("\n") , 2, "\r\n"); auto exists = Exists(content, msg); #else auto exists = Exists(content, msg); #endif ASSERT_TRUE(exists) << "\n\tcontent:" << content << "-\n\tentry: " << msg; } } TEST_F(FilterTest, setFlushPolicy__only_when_buffer_is_full) { auto filterSinkPtr = LogRotateWithFilter::CreateLogRotateWithFilter(_filename, _directory, {}); auto logfilename = filterSinkPtr->logFileName(); filterSinkPtr->setFlushPolicy(0); // auto buffer size if by default 1024 for(int i = 0; i < 10; ++i) { filterSinkPtr->save(CREATE_LOG_ENTRY(INFO, "this is a messagen\n")); } auto content = ReadContent(logfilename); auto exists = Exists(content, "this is a message"); ASSERT_FALSE(exists) << "\n\tcontent:" << content << "-\n\tentry: " << "Y" << ", content.size(): " << content.size(); } TEST_F(FilterTest, setFlushPolicy__every_third_write) { auto filterSinkPtr = LogRotateWithFilter::CreateLogRotateWithFilter(_filename, _directory, {}); auto logfilename = filterSinkPtr->logFileName(); filterSinkPtr->setFlushPolicy(3); std::string content; auto checkIfExist = [&](std::string expected) -> bool { content = ReadContent(logfilename); bool exists = Exists(content, expected); return exists; }; // auto buffer size if by default 1024 filterSinkPtr->save(CREATE_LOG_ENTRY(INFO, "msg1\n")); ASSERT_FALSE(checkIfExist("msg1")) << "\n\tcontent:" << content; filterSinkPtr->save(CREATE_LOG_ENTRY(INFO,"msg2\n")); ASSERT_FALSE(checkIfExist("msg2")) << "\n\tcontent:" << content; filterSinkPtr->save(CREATE_LOG_ENTRY(INFO,"msg3\n")); ASSERT_TRUE(checkIfExist("msg3")) << "\n\tcontent:" << content; // 3rd write flushes it + previous filterSinkPtr->save(CREATE_LOG_ENTRY(INFO, "msg4\n")); ASSERT_FALSE(checkIfExist("msg4")) << "\n\tcontent:" << content; } TEST_F(FilterTest, setFlushPolicy__force_flush) { auto filterSinkPtr = LogRotateWithFilter::CreateLogRotateWithFilter(_filename, _directory, {}); auto logfilename = filterSinkPtr->logFileName(); filterSinkPtr->setFlushPolicy(100); std::string content; auto checkIfExist = [&](std::string expected) -> bool { content = ReadContent(logfilename); bool exists = Exists(content, expected); return exists; }; // auto buffer size if by default 1024 filterSinkPtr->save(CREATE_LOG_ENTRY(INFO,"msg1\n")); ASSERT_FALSE(checkIfExist("msg1")) << "\n\tcontent:" << content; filterSinkPtr->save(CREATE_LOG_ENTRY(INFO, "msg2\n")); ASSERT_FALSE(checkIfExist("msg2")) << "\n\tcontent:" << content; filterSinkPtr->save(CREATE_LOG_ENTRY(INFO, "msg3\n")); filterSinkPtr->flush(); ASSERT_TRUE(checkIfExist("msg3")) << "\n\tcontent:" << content; // 3rd write flushes it + previous filterSinkPtr->save(CREATE_LOG_ENTRY(INFO, "msg4\n")); filterSinkPtr->flush(); ASSERT_TRUE(checkIfExist("msg4")) << "\n\tcontent:" << content; // 3rd write flushes it + previous } <commit_msg>fixed 'ontent'<commit_after>/** ========================================================================== * 2015 by KjellKod.cc * * This code is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * ============================================================================* * PUBLIC DOMAIN and Not copywrited. First published at KjellKod.cc * ********************************************* */ #include "FilterTest.h" #include "g3sinks/LogRotateWithFilter.h" #include <iostream> #include <cerrno> #include <g3log/std2_make_unique.hpp> #include "RotateTestHelper.h" #if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) && !defined(__MINGW32__) #define F_OK 0 #else #include <unistd.h> #endif #if (defined(CHANGE_G3LOG_DEBUG_TO_DBUG)) #define DEBUG DBUG #endif using namespace RotateTestHelper; namespace { // anonymous g3::LogMessageMover CreateLogEntry(const LEVELS level, std::string content, std::string file, int line, std::string function) { auto message = g3::LogMessage(file, line, function, level); message.write().append(content); return g3::MoveOnCopy<g3::LogMessage>(std::move(message)); } #define CREATE_LOG_ENTRY(level, content) CreateLogEntry(level, content, __FILE__, __LINE__, __FUNCTION__) } // anonymous TEST_F(FilterTest, CreateObject) { std::string logfilename; { auto logRotatePtr = std2::make_unique<LogRotate>(_filename, _directory); LogRotateWithFilter logWithFilter(std::move(logRotatePtr), {}); } // RAII flush of log auto name = std::string{_directory + _filename + ".log"}; int check = access(name.c_str(), F_OK); // check that the file exists EXPECT_EQ(check, 0) << std::strerror(errno) << " : " << name; } TEST_F(FilterTest, CreateObjectUsingHelper) { auto name = std::string{_directory +"/" + _filename + ".log"}; int check = access(name.c_str(), F_OK); // check that the file exists EXPECT_NE(check, 0) << std::strerror(errno) << " : " << name; { auto filterSinkPtr = LogRotateWithFilter::CreateLogRotateWithFilter(_filename, _directory, {}); } // raii check = access(name.c_str(), F_OK); // check that the file exists EXPECT_EQ(check, 0) << std::strerror(errno) << " : " << name; auto content = ReadContent(name); EXPECT_TRUE(Exists(content, "g3log: created log file at:")) << ", content: [" << "]" << ", name: " << name; EXPECT_TRUE(Exists(content, "file shutdown at:")) << ", content: [" << "]"<< ", name: " << name; } TEST_F(FilterTest, NothingFiltered) { { auto filterSinkPtr = LogRotateWithFilter::CreateLogRotateWithFilter(_filename, _directory, {}); auto message0 = CREATE_LOG_ENTRY(INFO, "Hello World"); filterSinkPtr->save(message0); auto message1 = std::move(CREATE_LOG_ENTRY(DEBUG, "Hello D World")); filterSinkPtr->save(message1); auto message2 = std::move(CREATE_LOG_ENTRY(WARNING, "Hello W World")); filterSinkPtr->save(message2); auto message3 = std::move(CREATE_LOG_ENTRY(FATAL, "Hello F World")); filterSinkPtr->save(message3); } // raii auto name = std::string{_directory + _filename + ".log"}; auto content = ReadContent(name); EXPECT_TRUE(Exists(content, "Hello World")) << content; EXPECT_TRUE(Exists(content, "Hello D World")) << content; EXPECT_TRUE(Exists(content, "Hello W World")) << content; EXPECT_TRUE(Exists(content, "Hello F World")) << content; } TEST_F(FilterTest, FilteredAndNotFiltered) { { auto filterSinkPtr = LogRotateWithFilter::CreateLogRotateWithFilter(_filename, _directory, {DEBUG, INFO, WARNING, FATAL}); auto message0 = CREATE_LOG_ENTRY(INFO, "Hello World"); filterSinkPtr->save(message0); auto message1 = std::move(CREATE_LOG_ENTRY(DEBUG, "Hello D World")); filterSinkPtr->save(message1); auto message2 = std::move(CREATE_LOG_ENTRY(WARNING, "Hello W World")); filterSinkPtr->save(message2); auto message3 = std::move(CREATE_LOG_ENTRY(FATAL, "Hello F World")); filterSinkPtr->save(message3); auto newLevel = LEVELS{123, "MadeUpLevel"}; auto message4 = std::move(CREATE_LOG_ENTRY(newLevel, "Hello New World")); filterSinkPtr->save(message4); } // raii auto name = std::string{_directory + _filename + ".log"}; auto content = ReadContent(name); EXPECT_FALSE(Exists(content, "Hello World")) << content; EXPECT_FALSE(Exists(content, "Hello D World")) << content; EXPECT_FALSE(Exists(content, "Hello W World")) << content; EXPECT_FALSE(Exists(content, "Hello F World")) << content; // Not filtered will exist EXPECT_TRUE(Exists(content, "Hello New World")) << content; const auto level1 = INFO; const auto level2 = INFO; EXPECT_TRUE(level1 == level2); } TEST_F(FilterTest, setFlushPolicy__default__every_time) { auto filterSinkPtr = LogRotateWithFilter::CreateLogRotateWithFilter(_filename, _directory, {}); auto logfilename = filterSinkPtr->logFileName(); for (size_t i = 0; i < 10; ++i) { std::string msg{"message: "}; msg += std::to_string(i) + "\n"; filterSinkPtr->save(CREATE_LOG_ENTRY(INFO, msg)); auto content = ReadContent(logfilename); #if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) && !defined(__MINGW32__) msg.replace(msg.find("\n") , 2, "\r\n"); auto exists = Exists(content, msg); #else auto exists = Exists(content, msg); #endif ASSERT_TRUE(exists) << "\n\tcontent:" << content << "-\n\tentry: " << msg; } } TEST_F(FilterTest, setFlushPolicy__only_when_buffer_is_full) { auto filterSinkPtr = LogRotateWithFilter::CreateLogRotateWithFilter(_filename, _directory, {}); auto logfilename = filterSinkPtr->logFileName(); filterSinkPtr->setFlushPolicy(0); // auto buffer size if by default 1024 for(int i = 0; i < 10; ++i) { filterSinkPtr->save(CREATE_LOG_ENTRY(INFO, "this is a messagen\n")); } auto content = ReadContent(logfilename); auto exists = Exists(content, "this is a message"); ASSERT_FALSE(exists) << "\n\tcontent:" << content << "-\n\tentry: " << "Y" << ", content.size(): " << content.size(); } TEST_F(FilterTest, setFlushPolicy__every_third_write) { auto filterSinkPtr = LogRotateWithFilter::CreateLogRotateWithFilter(_filename, _directory, {}); auto logfilename = filterSinkPtr->logFileName(); filterSinkPtr->setFlushPolicy(3); std::string content; auto checkIfExist = [&](std::string expected) -> bool { content = ReadContent(logfilename); bool exists = Exists(content, expected); return exists; }; // auto buffer size if by default 1024 filterSinkPtr->save(CREATE_LOG_ENTRY(INFO, "msg1\n")); ASSERT_FALSE(checkIfExist("msg1")) << "\n\tcontent:" << content; filterSinkPtr->save(CREATE_LOG_ENTRY(INFO,"msg2\n")); ASSERT_FALSE(checkIfExist("msg2")) << "\n\tcontent:" << content; filterSinkPtr->save(CREATE_LOG_ENTRY(INFO,"msg3\n")); ASSERT_TRUE(checkIfExist("msg3")) << "\n\tcontent:" << content; // 3rd write flushes it + previous filterSinkPtr->save(CREATE_LOG_ENTRY(INFO, "msg4\n")); ASSERT_FALSE(checkIfExist("msg4")) << "\n\tcontent:" << content; } TEST_F(FilterTest, setFlushPolicy__force_flush) { auto filterSinkPtr = LogRotateWithFilter::CreateLogRotateWithFilter(_filename, _directory, {}); auto logfilename = filterSinkPtr->logFileName(); filterSinkPtr->setFlushPolicy(100); std::string content; auto checkIfExist = [&](std::string expected) -> bool { content = ReadContent(logfilename); bool exists = Exists(content, expected); return exists; }; // auto buffer size if by default 1024 filterSinkPtr->save(CREATE_LOG_ENTRY(INFO,"msg1\n")); ASSERT_FALSE(checkIfExist("msg1")) << "\n\tcontent:" << content; filterSinkPtr->save(CREATE_LOG_ENTRY(INFO, "msg2\n")); ASSERT_FALSE(checkIfExist("msg2")) << "\n\tcontent:" << content; filterSinkPtr->save(CREATE_LOG_ENTRY(INFO, "msg3\n")); filterSinkPtr->flush(); ASSERT_TRUE(checkIfExist("msg3")) << "\n\tcontent:" << content; // 3rd write flushes it + previous filterSinkPtr->save(CREATE_LOG_ENTRY(INFO, "msg4\n")); filterSinkPtr->flush(); ASSERT_TRUE(checkIfExist("msg4")) << "\n\tcontent:" << content; // 3rd write flushes it + previous } <|endoftext|>
<commit_before><commit_msg>Added bci_test_runner.cc - required for having multiple test files using Boost.Test<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tk_punct.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-07 18:52:27 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <precomp.h> #include <s2_luidl/tk_punct.hxx> // NOT FULLY DECLARED SERVICES #include <parser/parserinfo.hxx> #include <s2_luidl/tokintpr.hxx> using csi::uidl::TokPunctuation; lux::EnumValueMap G_aTokPunctuation_EV_TokenId_Values; TokPunctuation::EV_TokenId ev_none(TokPunctuation::e_none,""); TokPunctuation::EV_TokenId BracketOpen(TokPunctuation::BracketOpen,"("); TokPunctuation::EV_TokenId BracketClose(TokPunctuation::BracketClose,")"); TokPunctuation::EV_TokenId ArrayBracketOpen(TokPunctuation::ArrayBracketOpen,"["); TokPunctuation::EV_TokenId ArrayBracketClose(TokPunctuation::ArrayBracketClose,"]"); TokPunctuation::EV_TokenId CurledBracketOpen(TokPunctuation::CurledBracketOpen,"{"); TokPunctuation::EV_TokenId CurledBracketClose(TokPunctuation::CurledBracketClose,"}"); TokPunctuation::EV_TokenId Semicolon(TokPunctuation::Semicolon,";"); TokPunctuation::EV_TokenId Colon(TokPunctuation::Colon,":"); TokPunctuation::EV_TokenId DoubleColon(TokPunctuation::DoubleColon,"::"); TokPunctuation::EV_TokenId Comma(TokPunctuation::Comma,","); TokPunctuation::EV_TokenId Minus(TokPunctuation::Minus,"-"); TokPunctuation::EV_TokenId Fullstop(TokPunctuation::Fullstop,"."); TokPunctuation::EV_TokenId Lesser(TokPunctuation::Lesser,"<"); TokPunctuation::EV_TokenId Greater(TokPunctuation::Greater,">"); namespace lux { template<> EnumValueMap & TokPunctuation::EV_TokenId::Values_() { return G_aTokPunctuation_EV_TokenId_Values; } } namespace csi { namespace uidl { void TokPunctuation::Trigger( TokenInterpreter & io_rInterpreter ) const { io_rInterpreter.Process_Punctuation(*this); } const char * TokPunctuation::Text() const { return eTag.Text(); } void Tok_EOL::Trigger( TokenInterpreter & io_rInterpreter ) const { io_rInterpreter.Process_EOL(); } const char * Tok_EOL::Text() const { return "\r\n"; } void Tok_EOF::Trigger( TokenInterpreter & io_rInterpreter ) const { csv_assert(false); // io_rInterpreter.Process_EOF(); } const char * Tok_EOF::Text() const { return ""; } } // namespace uidl } // namespace csi <commit_msg>INTEGRATION: CWS warnings01 (1.6.4); FILE MERGED 2005/10/18 08:36:22 np 1.6.4.1: #i53898#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tk_punct.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2006-06-19 12:08:53 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <precomp.h> #include <s2_luidl/tk_punct.hxx> // NOT FULLY DECLARED SERVICES #include <parser/parserinfo.hxx> #include <s2_luidl/tokintpr.hxx> using csi::uidl::TokPunctuation; lux::EnumValueMap G_aTokPunctuation_EV_TokenId_Values; TokPunctuation::EV_TokenId ev_none(TokPunctuation::e_none,""); TokPunctuation::EV_TokenId BracketOpen(TokPunctuation::BracketOpen,"("); TokPunctuation::EV_TokenId BracketClose(TokPunctuation::BracketClose,")"); TokPunctuation::EV_TokenId ArrayBracketOpen(TokPunctuation::ArrayBracketOpen,"["); TokPunctuation::EV_TokenId ArrayBracketClose(TokPunctuation::ArrayBracketClose,"]"); TokPunctuation::EV_TokenId CurledBracketOpen(TokPunctuation::CurledBracketOpen,"{"); TokPunctuation::EV_TokenId CurledBracketClose(TokPunctuation::CurledBracketClose,"}"); TokPunctuation::EV_TokenId Semicolon(TokPunctuation::Semicolon,";"); TokPunctuation::EV_TokenId Colon(TokPunctuation::Colon,":"); TokPunctuation::EV_TokenId DoubleColon(TokPunctuation::DoubleColon,"::"); TokPunctuation::EV_TokenId Comma(TokPunctuation::Comma,","); TokPunctuation::EV_TokenId Minus(TokPunctuation::Minus,"-"); TokPunctuation::EV_TokenId Fullstop(TokPunctuation::Fullstop,"."); TokPunctuation::EV_TokenId Lesser(TokPunctuation::Lesser,"<"); TokPunctuation::EV_TokenId Greater(TokPunctuation::Greater,">"); namespace lux { template<> EnumValueMap & TokPunctuation::EV_TokenId::Values_() { return G_aTokPunctuation_EV_TokenId_Values; } } namespace csi { namespace uidl { void TokPunctuation::Trigger( TokenInterpreter & io_rInterpreter ) const { io_rInterpreter.Process_Punctuation(*this); } const char * TokPunctuation::Text() const { return eTag.Text(); } void Tok_EOL::Trigger( TokenInterpreter & io_rInterpreter ) const { io_rInterpreter.Process_EOL(); } const char * Tok_EOL::Text() const { return "\r\n"; } void Tok_EOF::Trigger( TokenInterpreter & ) const { csv_assert(false); // io_rInterpreter.Process_EOF(); } const char * Tok_EOF::Text() const { return ""; } } // namespace uidl } // namespace csi <|endoftext|>
<commit_before>#include "stdafx.h" #include "CompressedCube.h" #include <ConvectionKernels/ConvectionKernels.h> namespace et { namespace pl { //----------------------- // CompressedCube::c-tor // CompressedCube::CompressedCube(render::TextureData const& cubeMap, TextureCompression::E_Quality const quality) { CompressedCube* mip = this; ivec2 const res = cubeMap.GetResolution(); ET_ASSERT(res.x == res.y, "cubemaps must be square"); ET_ASSERT(RasterImage::GetClosestPowerOf2(res.x) == static_cast<uint32>(res.x), "cubemap size must be a power of 2"); uint32 size = static_cast<uint32>(res.x); for (int32 mipLevel = 0; mipLevel < cubeMap.GetNumMipLevels() + 1; ++mipLevel) { mip->CompressFromTexture(cubeMap, quality, static_cast<uint8>(mipLevel), size); size /= 2u; if (size < 4u) { return; } if (mipLevel < cubeMap.GetNumMipLevels() - 1) { mip->CreateMip(); mip = mip->GetChildMip(); } } } //----------------------- // CompressedCube::d-tor // CompressedCube::~CompressedCube() { delete m_ChildMip; } //------------------------------------- // CompressedCube::CompressFromTexture // void CompressedCube::CompressFromTexture(render::TextureData const& cubeMap, TextureCompression::E_Quality const quality, uint8 const mipLevel, uint32 const size) { static size_t const s_BlockDim = 4u; static size_t const s_ChannelCount = 4u; static size_t const s_UncompressedPixelSize = s_ChannelCount * 2u; static size_t const s_UncompressedBlockRow = s_UncompressedPixelSize * s_BlockDim; static size_t const s_UncompressedBlockSize = s_UncompressedBlockRow * s_BlockDim; static render::E_ColorFormat const compressedFormat = render::E_ColorFormat::BC6H_RGB; size_t const faceSize = s_UncompressedPixelSize * static_cast<size_t>(size) * static_cast<size_t>(size); // count of int16, not bytes size_t const rowLength = static_cast<size_t>(size) * s_UncompressedPixelSize; uint32 const blocksX = size / s_BlockDim; uint32 const blocksY = size / s_BlockDim; size_t const blockCount = faceSize / s_UncompressedBlockSize; // per face, 4x4 = 16 pixels size_t const compressedFaceSize = blockCount * 16u; // BC6H block size is 16 bytes m_CompressedData.resize(compressedFaceSize * render::TextureData::s_NumCubeFaces); // BC6H texture compression with Convection kernels requires to process this amount of pixels at a time, so we need to provide it size_t padding = 0; { size_t const excess = blockCount % cvtt::NumParallelBlocks; if (excess != 0u) { padding = cvtt::NumParallelBlocks - excess; } } size_t const paddedBlockCount = blockCount + padding; // read pixels from GPU uint8* const cubePixels = new uint8[faceSize * render::TextureData::s_NumCubeFaces]; render::I_GraphicsContextApi* const api = render::ContextHolder::GetRenderContext(); api->GetTextureData(cubeMap, mipLevel, render::E_ColorFormat::RGBA, render::E_DataType::Half, reinterpret_cast<void*>(cubePixels)); for (uint8 faceIdx = 0u; faceIdx < render::TextureData::s_NumCubeFaces; ++faceIdx) { uint8 const* const facePixels = cubePixels + (faceSize * static_cast<size_t>(faceIdx)); uint8* const faceBlockPixels = new uint8[faceSize]; // swizzle into blocks { uint32 writeAddress = 0u; for (uint32 blockY = 0u; blockY < blocksY; ++blockY) { uint32 const yOffset = blockY * s_BlockDim; for (uint32 blockX = 0u; blockX < blocksX; ++blockX) { uint32 const x = blockX * s_UncompressedBlockRow; for (uint32 blockRow = 0u; blockRow < s_BlockDim; blockRow++) { uint32 const readAddress = x + (rowLength * (yOffset + blockRow)); memcpy(reinterpret_cast<void*>(faceBlockPixels + writeAddress), reinterpret_cast<void const*>(facePixels + readAddress), s_UncompressedBlockRow); writeAddress += s_UncompressedBlockRow; } //for (uint32 blockRow = s_BlockDim - 1u; blockRow < s_BlockDim; blockRow--) //{ // uint32 const readAddress = x + (rowLength * (yOffset + blockRow)); // for (uint32 blockColumn = 0u; blockColumn < s_BlockDim; blockColumn++) // { // memcpy(reinterpret_cast<void*>(faceBlockPixels + writeAddress + (s_UncompressedPixelSize * blockColumn)), // reinterpret_cast<void const*>(facePixels + readAddress + (s_UncompressedPixelSize * ((s_BlockDim - 1u) - blockColumn))), // s_UncompressedPixelSize); // } // writeAddress += s_UncompressedBlockRow; //} } } } std::vector<uint8> faceData; TextureCompression::CompressImage(faceBlockPixels, static_cast<uint32>(paddedBlockCount), compressedFormat, quality, faceData); delete[] faceBlockPixels; // we can now remove the padding again if (padding != 0) { size_t const toRemove = padding * static_cast<size_t>(render::TextureFormat::GetBlockByteCount(compressedFormat)); faceData.resize(faceData.size() - toRemove); } ET_ASSERT(faceData.size() == compressedFaceSize); memcpy(m_CompressedData.data() + (static_cast<size_t>(faceIdx) * compressedFaceSize), faceData.data(), compressedFaceSize); } delete[] cubePixels; } //-------------------------- // CompressedCube::GetFace // void CompressedCube::CreateMip() { m_ChildMip = new CompressedCube(); } } // namespace pl } // namespace et <commit_msg>removed leftover test code from previous commit<commit_after>#include "stdafx.h" #include "CompressedCube.h" #include <ConvectionKernels/ConvectionKernels.h> namespace et { namespace pl { //----------------------- // CompressedCube::c-tor // CompressedCube::CompressedCube(render::TextureData const& cubeMap, TextureCompression::E_Quality const quality) { CompressedCube* mip = this; ivec2 const res = cubeMap.GetResolution(); ET_ASSERT(res.x == res.y, "cubemaps must be square"); ET_ASSERT(RasterImage::GetClosestPowerOf2(res.x) == static_cast<uint32>(res.x), "cubemap size must be a power of 2"); uint32 size = static_cast<uint32>(res.x); for (int32 mipLevel = 0; mipLevel < cubeMap.GetNumMipLevels() + 1; ++mipLevel) { mip->CompressFromTexture(cubeMap, quality, static_cast<uint8>(mipLevel), size); size /= 2u; if (size < 4u) { return; } if (mipLevel < cubeMap.GetNumMipLevels() - 1) { mip->CreateMip(); mip = mip->GetChildMip(); } } } //----------------------- // CompressedCube::d-tor // CompressedCube::~CompressedCube() { delete m_ChildMip; } //------------------------------------- // CompressedCube::CompressFromTexture // void CompressedCube::CompressFromTexture(render::TextureData const& cubeMap, TextureCompression::E_Quality const quality, uint8 const mipLevel, uint32 const size) { static size_t const s_BlockDim = 4u; static size_t const s_ChannelCount = 4u; static size_t const s_UncompressedPixelSize = s_ChannelCount * 2u; static size_t const s_UncompressedBlockRow = s_UncompressedPixelSize * s_BlockDim; static size_t const s_UncompressedBlockSize = s_UncompressedBlockRow * s_BlockDim; static render::E_ColorFormat const compressedFormat = render::E_ColorFormat::BC6H_RGB; size_t const faceSize = s_UncompressedPixelSize * static_cast<size_t>(size) * static_cast<size_t>(size); // count of int16, not bytes size_t const rowLength = static_cast<size_t>(size) * s_UncompressedPixelSize; uint32 const blocksX = size / s_BlockDim; uint32 const blocksY = size / s_BlockDim; size_t const blockCount = faceSize / s_UncompressedBlockSize; // per face, 4x4 = 16 pixels size_t const compressedFaceSize = blockCount * 16u; // BC6H block size is 16 bytes m_CompressedData.resize(compressedFaceSize * render::TextureData::s_NumCubeFaces); // BC6H texture compression with Convection kernels requires to process this amount of pixels at a time, so we need to provide it size_t padding = 0; { size_t const excess = blockCount % cvtt::NumParallelBlocks; if (excess != 0u) { padding = cvtt::NumParallelBlocks - excess; } } size_t const paddedBlockCount = blockCount + padding; // read pixels from GPU uint8* const cubePixels = new uint8[faceSize * render::TextureData::s_NumCubeFaces]; render::I_GraphicsContextApi* const api = render::ContextHolder::GetRenderContext(); api->GetTextureData(cubeMap, mipLevel, render::E_ColorFormat::RGBA, render::E_DataType::Half, reinterpret_cast<void*>(cubePixels)); for (uint8 faceIdx = 0u; faceIdx < render::TextureData::s_NumCubeFaces; ++faceIdx) { uint8 const* const facePixels = cubePixels + (faceSize * static_cast<size_t>(faceIdx)); uint8* const faceBlockPixels = new uint8[faceSize]; // swizzle into blocks { uint32 writeAddress = 0u; for (uint32 blockY = 0u; blockY < blocksY; ++blockY) { uint32 const yOffset = blockY * s_BlockDim; for (uint32 blockX = 0u; blockX < blocksX; ++blockX) { uint32 const x = blockX * s_UncompressedBlockRow; for (uint32 blockRow = 0u; blockRow < s_BlockDim; blockRow++) { uint32 const readAddress = x + (rowLength * (yOffset + blockRow)); memcpy(reinterpret_cast<void*>(faceBlockPixels + writeAddress), reinterpret_cast<void const*>(facePixels + readAddress), s_UncompressedBlockRow); writeAddress += s_UncompressedBlockRow; } } } } std::vector<uint8> faceData; TextureCompression::CompressImage(faceBlockPixels, static_cast<uint32>(paddedBlockCount), compressedFormat, quality, faceData); delete[] faceBlockPixels; // we can now remove the padding again if (padding != 0) { size_t const toRemove = padding * static_cast<size_t>(render::TextureFormat::GetBlockByteCount(compressedFormat)); faceData.resize(faceData.size() - toRemove); } ET_ASSERT(faceData.size() == compressedFaceSize); memcpy(m_CompressedData.data() + (static_cast<size_t>(faceIdx) * compressedFaceSize), faceData.data(), compressedFaceSize); } delete[] cubePixels; } //-------------------------- // CompressedCube::GetFace // void CompressedCube::CreateMip() { m_ChildMip = new CompressedCube(); } } // namespace pl } // namespace et <|endoftext|>
<commit_before>/** * For conditions of distribution and use, see copyright notice in license.txt * * @file InputMapper.h * @brief Registers an InputContext from the Naali Input subsystem and uses it to translate * given set of keys to Entity Actions on the entity the component is part of. */ #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "MemoryLeakCheck.h" #include "EC_InputMapper.h" #include "IAttribute.h" #include "InputAPI.h" #include "Entity.h" #include "LoggingFunctions.h" EC_InputMapper::~EC_InputMapper() { input_.reset(); } void EC_InputMapper::RegisterMapping(const QKeySequence &keySeq, const QString &action, int eventType, int executionType) { ActionInvocation invocation; invocation.name = action; invocation.executionType = executionType; mappings_[qMakePair(keySeq, (KeyEvent::EventType)eventType)] = invocation; } void EC_InputMapper::RegisterMapping(const QString &keySeq, const QString &action, int eventType, int executionType) { ActionInvocation invocation; invocation.name = action; invocation.executionType = executionType; QKeySequence key(keySeq); if(!key.isEmpty()) { mappings_[qMakePair(key, (KeyEvent::EventType)eventType)] = invocation; } } void EC_InputMapper::RemoveMapping(const QKeySequence &keySeq, int eventType) { Mappings_t::iterator it = mappings_.find(qMakePair(keySeq, (KeyEvent::EventType)eventType)); if (it != mappings_.end()) mappings_.erase(it); } void EC_InputMapper::RemoveMapping(const QString &keySeq, int eventType) { Mappings_t::iterator it = mappings_.find(qMakePair(QKeySequence(keySeq), (KeyEvent::EventType)eventType)); if (it != mappings_.end()) mappings_.erase(it); } EC_InputMapper::EC_InputMapper(IModule *module): IComponent(module->GetFramework()), contextName(this, "Input context name", "EC_InputMapper"), contextPriority(this, "Input context priority", 90), takeKeyboardEventsOverQt(this, "Take keyboard events over Qt", false), takeMouseEventsOverQt(this, "Take mouse events over Qt", false), mappings(this, "Mappings"), executionType(this, "Action execution type", 1), modifiersEnabled(this, "Key modifiers enable", true), enabled(this, "Enable actions", true), keyrepeatTrigger(this, "Trigger on keyrepeats", true) { static AttributeMetadata executionAttrData; static bool metadataInitialized = false; if(!metadataInitialized) { executionAttrData.enums[EntityAction::Local] = "Local"; executionAttrData.enums[EntityAction::Server] = "Server"; executionAttrData.enums[EntityAction::Server | EntityAction::Local] = "Local+Server"; executionAttrData.enums[EntityAction::Peers] = "Peers"; executionAttrData.enums[EntityAction::Peers | EntityAction::Local] = "Local+Peers"; executionAttrData.enums[EntityAction::Peers | EntityAction::Server] = "Local+Server"; executionAttrData.enums[EntityAction::Peers | EntityAction::Server | EntityAction::Local] = "Local+Server+Peers"; metadataInitialized = true; } executionType.SetMetadata(&executionAttrData); connect(this, SIGNAL(AttributeChanged(IAttribute *, AttributeChange::Type)), SLOT(HandleAttributeUpdated(IAttribute *, AttributeChange::Type))); input_ = GetFramework()->Input()->RegisterInputContext(contextName.Get().toStdString().c_str(), contextPriority.Get()); input_->SetTakeKeyboardEventsOverQt(takeKeyboardEventsOverQt.Get()); input_->SetTakeMouseEventsOverQt(takeMouseEventsOverQt.Get()); connect(input_.get(), SIGNAL(OnKeyEvent(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *))); connect(input_.get(), SIGNAL(OnMouseEvent(MouseEvent *)), SLOT(HandleMouseEvent(MouseEvent *))); } void EC_InputMapper::HandleAttributeUpdated(IAttribute *attribute, AttributeChange::Type change) { if(attribute == &contextName || attribute == &contextPriority) { input_.reset(); input_ = GetFramework()->Input()->RegisterInputContext(contextName.Get().toStdString().c_str(), contextPriority.Get()); connect(input_.get(), SIGNAL(OnKeyEvent(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *))); connect(input_.get(), SIGNAL(OnMouseEvent(MouseEvent *)), SLOT(HandleMouseEvent(MouseEvent *))); } else if(attribute == &takeKeyboardEventsOverQt) { input_->SetTakeKeyboardEventsOverQt(takeKeyboardEventsOverQt.Get()); } else if(attribute == &takeMouseEventsOverQt) { input_->SetTakeMouseEventsOverQt(takeMouseEventsOverQt.Get()); } else if(attribute == &mappings) { } } void EC_InputMapper::HandleKeyEvent(KeyEvent *e) { if (!enabled.Get()) return; // Do not act on already handled key events. if (!e || e->handled) return; if (!keyrepeatTrigger.Get()) { // Now we do not repeat key pressed events. if (e != 0 && e->eventType == KeyEvent::KeyPressed && e->keyPressCount > 1) return; } Mappings_t::iterator it; if (modifiersEnabled.Get()) it = mappings_.find(qMakePair(QKeySequence(e->keyCode | e->modifiers), e->eventType)); else it = mappings_.find(qMakePair(QKeySequence(e->keyCode), e->eventType)); if (it == mappings_.end()) return; Scene::Entity *entity = GetParentEntity(); if (!entity) { LogWarning("Parent entity not set. Cannot execute action."); return; } ActionInvocation& invocation = it.value(); QString &action = invocation.name; int execType = invocation.executionType; // If zero execution type, use default if (!execType) execType = executionType.Get(); // If the action has parameters, parse them from the action string. int idx = action.indexOf('('); if (idx != -1) { QString act = action.left(idx); QString parsedAction = action.mid(idx + 1); parsedAction.remove('('); parsedAction.remove(')'); QStringList parameters = parsedAction.split(','); entity->Exec((EntityAction::ExecutionType)execType, act, parameters); } else entity->Exec((EntityAction::ExecutionType)execType, action); } void EC_InputMapper::HandleMouseEvent(MouseEvent *e) { if (!enabled.Get()) return; if (!GetParentEntity()) return; /// \todo this hard coding of look button logic is not nice! if ((e->IsButtonDown(MouseEvent::RightButton)) && (!GetFramework()->Input()->IsMouseCursorVisible())) { if (e->relativeX != 0) GetParentEntity()->Exec((EntityAction::ExecutionType)executionType.Get(), "MouseLookX" , QString::number(e->relativeX)); if (e->relativeY != 0) GetParentEntity()->Exec((EntityAction::ExecutionType)executionType.Get(), "MouseLookY" , QString::number(e->relativeY)); } if (e->relativeZ != 0 && e->relativeZ != -1) // For some reason this is -1 without scroll GetParentEntity()->Exec((EntityAction::ExecutionType)executionType.Get(), "MouseScroll" , QString::number(e->relativeZ)); } <commit_msg>EC_InputMapper: Fix camera mouse look x/y. Apparently was checking if mouse cursor is visible and this branch does not hide it on right click drag events in the input api.<commit_after>/** * For conditions of distribution and use, see copyright notice in license.txt * * @file InputMapper.h * @brief Registers an InputContext from the Naali Input subsystem and uses it to translate * given set of keys to Entity Actions on the entity the component is part of. */ #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "MemoryLeakCheck.h" #include "EC_InputMapper.h" #include "IAttribute.h" #include "InputAPI.h" #include "Entity.h" #include "LoggingFunctions.h" EC_InputMapper::~EC_InputMapper() { input_.reset(); } void EC_InputMapper::RegisterMapping(const QKeySequence &keySeq, const QString &action, int eventType, int executionType) { ActionInvocation invocation; invocation.name = action; invocation.executionType = executionType; mappings_[qMakePair(keySeq, (KeyEvent::EventType)eventType)] = invocation; } void EC_InputMapper::RegisterMapping(const QString &keySeq, const QString &action, int eventType, int executionType) { ActionInvocation invocation; invocation.name = action; invocation.executionType = executionType; QKeySequence key(keySeq); if(!key.isEmpty()) { mappings_[qMakePair(key, (KeyEvent::EventType)eventType)] = invocation; } } void EC_InputMapper::RemoveMapping(const QKeySequence &keySeq, int eventType) { Mappings_t::iterator it = mappings_.find(qMakePair(keySeq, (KeyEvent::EventType)eventType)); if (it != mappings_.end()) mappings_.erase(it); } void EC_InputMapper::RemoveMapping(const QString &keySeq, int eventType) { Mappings_t::iterator it = mappings_.find(qMakePair(QKeySequence(keySeq), (KeyEvent::EventType)eventType)); if (it != mappings_.end()) mappings_.erase(it); } EC_InputMapper::EC_InputMapper(IModule *module): IComponent(module->GetFramework()), contextName(this, "Input context name", "EC_InputMapper"), contextPriority(this, "Input context priority", 90), takeKeyboardEventsOverQt(this, "Take keyboard events over Qt", false), takeMouseEventsOverQt(this, "Take mouse events over Qt", false), mappings(this, "Mappings"), executionType(this, "Action execution type", 1), modifiersEnabled(this, "Key modifiers enable", true), enabled(this, "Enable actions", true), keyrepeatTrigger(this, "Trigger on keyrepeats", true) { static AttributeMetadata executionAttrData; static bool metadataInitialized = false; if(!metadataInitialized) { executionAttrData.enums[EntityAction::Local] = "Local"; executionAttrData.enums[EntityAction::Server] = "Server"; executionAttrData.enums[EntityAction::Server | EntityAction::Local] = "Local+Server"; executionAttrData.enums[EntityAction::Peers] = "Peers"; executionAttrData.enums[EntityAction::Peers | EntityAction::Local] = "Local+Peers"; executionAttrData.enums[EntityAction::Peers | EntityAction::Server] = "Local+Server"; executionAttrData.enums[EntityAction::Peers | EntityAction::Server | EntityAction::Local] = "Local+Server+Peers"; metadataInitialized = true; } executionType.SetMetadata(&executionAttrData); connect(this, SIGNAL(AttributeChanged(IAttribute *, AttributeChange::Type)), SLOT(HandleAttributeUpdated(IAttribute *, AttributeChange::Type))); input_ = GetFramework()->Input()->RegisterInputContext(contextName.Get().toStdString().c_str(), contextPriority.Get()); input_->SetTakeKeyboardEventsOverQt(takeKeyboardEventsOverQt.Get()); input_->SetTakeMouseEventsOverQt(takeMouseEventsOverQt.Get()); connect(input_.get(), SIGNAL(OnKeyEvent(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *))); connect(input_.get(), SIGNAL(OnMouseEvent(MouseEvent *)), SLOT(HandleMouseEvent(MouseEvent *))); } void EC_InputMapper::HandleAttributeUpdated(IAttribute *attribute, AttributeChange::Type change) { if(attribute == &contextName || attribute == &contextPriority) { input_.reset(); input_ = GetFramework()->Input()->RegisterInputContext(contextName.Get().toStdString().c_str(), contextPriority.Get()); connect(input_.get(), SIGNAL(OnKeyEvent(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *))); connect(input_.get(), SIGNAL(OnMouseEvent(MouseEvent *)), SLOT(HandleMouseEvent(MouseEvent *))); } else if(attribute == &takeKeyboardEventsOverQt) { input_->SetTakeKeyboardEventsOverQt(takeKeyboardEventsOverQt.Get()); } else if(attribute == &takeMouseEventsOverQt) { input_->SetTakeMouseEventsOverQt(takeMouseEventsOverQt.Get()); } else if(attribute == &mappings) { } } void EC_InputMapper::HandleKeyEvent(KeyEvent *e) { if (!enabled.Get()) return; // Do not act on already handled key events. if (!e || e->handled) return; if (!keyrepeatTrigger.Get()) { // Now we do not repeat key pressed events. if (e != 0 && e->eventType == KeyEvent::KeyPressed && e->keyPressCount > 1) return; } Mappings_t::iterator it; if (modifiersEnabled.Get()) it = mappings_.find(qMakePair(QKeySequence(e->keyCode | e->modifiers), e->eventType)); else it = mappings_.find(qMakePair(QKeySequence(e->keyCode), e->eventType)); if (it == mappings_.end()) return; Scene::Entity *entity = GetParentEntity(); if (!entity) { LogWarning("Parent entity not set. Cannot execute action."); return; } ActionInvocation& invocation = it.value(); QString &action = invocation.name; int execType = invocation.executionType; // If zero execution type, use default if (!execType) execType = executionType.Get(); // If the action has parameters, parse them from the action string. int idx = action.indexOf('('); if (idx != -1) { QString act = action.left(idx); QString parsedAction = action.mid(idx + 1); parsedAction.remove('('); parsedAction.remove(')'); QStringList parameters = parsedAction.split(','); entity->Exec((EntityAction::ExecutionType)execType, act, parameters); } else entity->Exec((EntityAction::ExecutionType)execType, action); } void EC_InputMapper::HandleMouseEvent(MouseEvent *e) { if (!enabled.Get()) return; if (!GetParentEntity()) return; /// \todo this hard coding of look button logic is not nice! if (e->IsButtonDown(MouseEvent::RightButton)) { if (e->relativeX != 0) GetParentEntity()->Exec((EntityAction::ExecutionType)executionType.Get(), "MouseLookX" , QString::number(e->relativeX)); if (e->relativeY != 0) GetParentEntity()->Exec((EntityAction::ExecutionType)executionType.Get(), "MouseLookY" , QString::number(e->relativeY)); } if (e->relativeZ != 0 && e->relativeZ != -1) // For some reason this is -1 without scroll GetParentEntity()->Exec((EntityAction::ExecutionType)executionType.Get(), "MouseScroll" , QString::number(e->relativeZ)); } <|endoftext|>
<commit_before>#include <Arduino.h> #include <ArduinoOTA.h> #include <ESP8266WiFi.h> #include <ESP8266mDNS.h> #include <NeoPixelBus.h> #include <WiFiUdp.h> #define WIFI_SSID "****" #define WIFI_PASS "****" #define HORIZONTAL_LEDS 60 #define VERTICAL_LEDS 34 static WiFiUDP *udp_socket; static int missed_ticks = 0; static NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod> *strip; void ICACHE_FLASH_ATTR setup() { Serial.begin(115200); strip = new NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod>(2 * (HORIZONTAL_LEDS + VERTICAL_LEDS), 0); strip->Begin(); WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASS); while (WiFi.status() != WL_CONNECTED) { delay(50); Serial.print("."); } udp_socket = new WiFiUDP(); udp_socket->begin(65000); ArduinoOTA.setPort(8266); ArduinoOTA.begin(); delay(100); } void loop() { if (udp_socket->parsePacket()) { if (missed_ticks != 0) missed_ticks = 0; uint8_t buffer[6 * (HORIZONTAL_LEDS + VERTICAL_LEDS)]; udp_socket->readBytes(buffer, 6 * (HORIZONTAL_LEDS + VERTICAL_LEDS)); for (uint16_t p = 0; p < 2 * (HORIZONTAL_LEDS + VERTICAL_LEDS); p++) { strip->SetPixelColor(p, RgbColor(buffer[0 + 3 * p], buffer[1 + 3 * p], buffer[2 + 3 * p])); } strip->Show(); } else if (missed_ticks >= 500000) { for (uint16_t p = 0; p < 2 * (HORIZONTAL_LEDS + VERTICAL_LEDS); p++) { strip->SetPixelColor(p, RgbColor(0, 0, 0)); } strip->Show(); missed_ticks = -1; } else if (missed_ticks >= 0) { missed_ticks++; } else { ArduinoOTA.handle(); delay(500); } yield(); // WATCHDOG/WIFI feed } <commit_msg>Add COMPILE option to select smooth/dynamic fading<commit_after>#include <Arduino.h> #include <ArduinoOTA.h> #include <ESP8266WiFi.h> #include <ESP8266mDNS.h> #include <NeoPixelBus.h> #include <WiFiUdp.h> // TODO: remove, these needs to be changeable during runtime/reboot per user #define WIFI_SSID "****" #define WIFI_PASS "****" #define HORIZONTAL_LEDS 60 #define VERTICAL_LEDS 34 // TODO: this may be shifted to LE46B650 logic if possible #define SMOOTH_FADING static WiFiUDP *udp_socket; static int missed_ticks = 0; static NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod> *strip; void ICACHE_FLASH_ATTR setup() { Serial.begin(115200); strip = new NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod>(2 * (HORIZONTAL_LEDS + VERTICAL_LEDS), 0); strip->Begin(); WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASS); // TODO: if not connected in few second go to AP mode, to be able to reflash or update settings of module. while (WiFi.status() != WL_CONNECTED) { delay(50); Serial.print("."); } udp_socket = new WiFiUDP(); udp_socket->begin(65000); ArduinoOTA.setPort(8266); ArduinoOTA.begin(); delay(100); } void loop() { if (udp_socket->parsePacket()) { if (missed_ticks != 0) missed_ticks = 0; uint8_t buffer[6 * (HORIZONTAL_LEDS + VERTICAL_LEDS)]; udp_socket->readBytes(buffer, 6 * (HORIZONTAL_LEDS + VERTICAL_LEDS)); for (uint16_t p = 0; p < 2 * (HORIZONTAL_LEDS + VERTICAL_LEDS); p++) { #ifndef SMOOTH_FADING strip->SetPixelColor(p, RgbColor(buffer[0 + 3 * p], buffer[1 + 3 * p], buffer[2 + 3 * p])); #else RgbColor current_color = strip->GetPixelColor(p); strip->SetPixelColor(p, RgbColor((uint8_t) (0.5 * (buffer[0 + 3 * p] + current_color.R)), (uint8_t) (0.5 * (buffer[1 + 3 * p] + current_color.G)), (uint8_t) (0.5 * (buffer[2 + 3 * p] + current_color.B)))); #endif } strip->Show(); } else if (missed_ticks >= 500000) { for (uint16_t p = 0; p < 2 * (HORIZONTAL_LEDS + VERTICAL_LEDS); p++) { strip->SetPixelColor(p, RgbColor(0, 0, 0)); } strip->Show(); missed_ticks = -1; } else if (missed_ticks >= 0) { missed_ticks++; } else { ArduinoOTA.handle(); delay(500); } yield(); // WATCHDOG/WIFI feed } <|endoftext|>
<commit_before>#include <Arduino.h> #include <ArduinoOTA.h> #include <ESP8266mDNS.h> #include <NeoPixelBus.h> // TODO: remove, these needs to be changeable during runtime/reboot per user #define WIFI_SSID "****" #define WIFI_PASS "****" #define HORIZONTAL_LEDS 60 #define VERTICAL_LEDS 34 // TODO: this may be shifted to LE46B650 logic if possible #define SMOOTH_FADING static WiFiUDP *udp_socket; static int missed_ticks = 0; static NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod> *strip; void ICACHE_FLASH_ATTR setup() { Serial.begin(115200); strip = new NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod>(2 * (HORIZONTAL_LEDS + VERTICAL_LEDS), 0); strip->Begin(); WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASS); // TODO: if not connected in few second go to AP mode, to be able to reflash or update settings of module. while (WiFi.status() != WL_CONNECTED) { delay(50); Serial.print("."); } udp_socket = new WiFiUDP(); udp_socket->begin(65000); ArduinoOTA.setPort(8266); ArduinoOTA.begin(); delay(100); } void loop() { if (udp_socket->parsePacket()) { if (missed_ticks != 0) missed_ticks = 0; uint8_t buffer[6 * (HORIZONTAL_LEDS + VERTICAL_LEDS)]; udp_socket->readBytes(buffer, 6 * (HORIZONTAL_LEDS + VERTICAL_LEDS)); for (uint16_t p = 0; p < 2 * (HORIZONTAL_LEDS + VERTICAL_LEDS); p++) { #ifndef SMOOTH_FADING strip->SetPixelColor(p, RgbColor(buffer[0 + 3 * p], buffer[1 + 3 * p], buffer[2 + 3 * p])); #else RgbColor color = RgbColor((uint8_t) (0.5 * (buffer[0 + 3 * p] + strip->GetPixelColor(p).R)), (uint8_t) (0.5 * (buffer[1 + 3 * p] + strip->GetPixelColor(p).G)), (uint8_t) (0.5 * (buffer[2 + 3 * p] + strip->GetPixelColor(p).B))), color_next = p < 2 * (HORIZONTAL_LEDS + VERTICAL_LEDS) - 1 ? strip->GetPixelColor((uint16_t) (p + 1)) : strip->GetPixelColor(0), color_prev = p > 0 ? strip->GetPixelColor((uint16_t) (p - 1)) : strip->GetPixelColor(2 * (HORIZONTAL_LEDS + VERTICAL_LEDS) - 1); strip->SetPixelColor(p, RgbColor((uint8_t) (0.3 * color_prev.R + 0.4 * color.R + 0.3 * color_next.R), (uint8_t) (0.3 * color_prev.G + 0.4 * color.G + 0.3 * color_next.G), (uint8_t) (0.3 * color_prev.B + 0.4 * color.B + 0.3 * color_next.B))); #endif } strip->Show(); } else if (missed_ticks >= 500000) { for (uint16_t p = 0; p < 2 * (HORIZONTAL_LEDS + VERTICAL_LEDS); p++) { strip->SetPixelColor(p, RgbColor(0, 0, 0)); } strip->Show(); missed_ticks = -1; } else if (missed_ticks >= 0) { missed_ticks++; } else { ArduinoOTA.handle(); delay(500); } yield(); // WATCHDOG/WIFI feed } <commit_msg>Add AP fallback for LE46B650<commit_after>#include <Arduino.h> #include <ArduinoOTA.h> #include <ESP8266mDNS.h> #include <NeoPixelBus.h> #define WIFI_SSID "****" #define WIFI_PASS "****" #define HORIZONTAL_LEDS 60 #define VERTICAL_LEDS 34 #define SMOOTH_FADING #define WIFI_CONNECTION_TIMEOUT_MIN 10 #define WIFI_FALLBACK_AP "LE46B650-AP" static WiFiUDP *udp_socket; static int missed_ticks = 0; static NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod> *strip; void ICACHE_FLASH_ATTR setup() { Serial.begin(115200); strip = new NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod>(2 * (HORIZONTAL_LEDS + VERTICAL_LEDS), 0); strip->Begin(); WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASS); for (int i = 0; WiFi.status() != WL_CONNECTED && i < 1200 * WIFI_CONNECTION_TIMEOUT_MIN; i++) { delay(50); Serial.print("."); } if (WiFi.status() != WL_CONNECTED) { WiFi.mode(WIFI_AP); WiFi.softAP(WIFI_FALLBACK_AP); Serial.print("AP: "WIFI_FALLBACK_AP" created"); } else { Serial.print("STA connected."); } udp_socket = new WiFiUDP(); udp_socket->begin(65000); ArduinoOTA.setPort(8266); ArduinoOTA.begin(); delay(100); } void loop() { if (udp_socket->parsePacket()) { if (missed_ticks != 0) missed_ticks = 0; uint8_t buffer[6 * (HORIZONTAL_LEDS + VERTICAL_LEDS)]; udp_socket->readBytes(buffer, 6 * (HORIZONTAL_LEDS + VERTICAL_LEDS)); for (uint16_t p = 0; p < 2 * (HORIZONTAL_LEDS + VERTICAL_LEDS); p++) { #ifndef SMOOTH_FADING strip->SetPixelColor(p, RgbColor(buffer[0 + 3 * p], buffer[1 + 3 * p], buffer[2 + 3 * p])); #else RgbColor color = RgbColor((uint8_t) (0.5 * (buffer[0 + 3 * p] + strip->GetPixelColor(p).R)), (uint8_t) (0.5 * (buffer[1 + 3 * p] + strip->GetPixelColor(p).G)), (uint8_t) (0.5 * (buffer[2 + 3 * p] + strip->GetPixelColor(p).B))), color_next = p < 2 * (HORIZONTAL_LEDS + VERTICAL_LEDS) - 1 ? strip->GetPixelColor((uint16_t) (p + 1)) : strip->GetPixelColor(0), color_prev = p > 0 ? strip->GetPixelColor((uint16_t) (p - 1)) : strip->GetPixelColor(2 * (HORIZONTAL_LEDS + VERTICAL_LEDS) - 1); strip->SetPixelColor(p, RgbColor((uint8_t) (0.3 * color_prev.R + 0.4 * color.R + 0.3 * color_next.R), (uint8_t) (0.3 * color_prev.G + 0.4 * color.G + 0.3 * color_next.G), (uint8_t) (0.3 * color_prev.B + 0.4 * color.B + 0.3 * color_next.B))); #endif } strip->Show(); } else if (missed_ticks >= 500000) { for (uint16_t p = 0; p < 2 * (HORIZONTAL_LEDS + VERTICAL_LEDS); p++) { strip->SetPixelColor(p, RgbColor(0, 0, 0)); } strip->Show(); missed_ticks = -1; } else if (missed_ticks >= 0) { missed_ticks++; } else { ArduinoOTA.handle(); delay(500); } yield(); // WATCHDOG/WIFI feed } <|endoftext|>
<commit_before>/** * Clever programming language * Copyright (c) 2011-2012 Clever Team * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <iostream> #include "core/cthread.h" #include "core/value.h" #include "types/function.h" #include "core/pkgmanager.h" #include "modules/std/io/io.h" namespace clever { namespace packages { namespace std { namespace io { Mutex io_mutex; // print(object a, [ ...]) // Prints the object values without trailing newline static CLEVER_FUNCTION(print) { for (size_t i = 0, size = args.size(); i < size; ++i) { args[i]->dump(); } } // println(object a, [ ...]) // Prints the object values with trailing newline static CLEVER_FUNCTION(println) { for (size_t i = 0, size = args.size(); i < size; ++i) { args[i]->dump(); ::std::cout << ::std::endl; } } // safeprint(object a, [ ...]) // Prints the object values without trailing newline [thread safed] static CLEVER_FUNCTION(safeprint) { io_mutex.lock(); for (size_t i = 0, size = args.size(); i < size; ++i) { args[i]->dump(); } io_mutex.unlock(); } // safeprintln(object a, [ ...]) // Prints the object values with trailing newline [thread safed] static CLEVER_FUNCTION(safeprintln) { io_mutex.lock(); for (size_t i = 0, size = args.size(); i < size; ++i) { args[i]->dump(); ::std::cout << ::std::endl; } io_mutex.unlock(); } } // namespace io /// Initializes Standard module CLEVER_MODULE_INIT(IOModule) { using namespace io; io_mutex.init(); BEGIN_DECLARE_FUNCTION(); addFunction(new Function("safeprint", &CLEVER_FUNC_NAME(safeprint))); addFunction(new Function("safeprintln", &CLEVER_FUNC_NAME(safeprintln))); addFunction(new Function("print", &CLEVER_FUNC_NAME(print))); addFunction(new Function("println", &CLEVER_FUNC_NAME(println))); END_DECLARE(); } }}} // clever::packages::std <commit_msg>- Cosmetics<commit_after>/** * Clever programming language * Copyright (c) 2011-2012 Clever Team * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <iostream> #include "core/cthread.h" #include "core/value.h" #include "types/function.h" #include "core/pkgmanager.h" #include "modules/std/io/io.h" namespace clever { namespace packages { namespace std { namespace io { Mutex io_mutex; // print(object a, [ ...]) // Prints the object values without trailing newline static CLEVER_FUNCTION(print) { for (size_t i = 0, size = args.size(); i < size; ++i) { args[i]->dump(); } } // println(object a, [ ...]) // Prints the object values with trailing newline static CLEVER_FUNCTION(println) { for (size_t i = 0, size = args.size(); i < size; ++i) { args[i]->dump(); ::std::cout << ::std::endl; } } // safeprint(object a, [ ...]) // Prints the object values without trailing newline [thread safed] static CLEVER_FUNCTION(safeprint) { io_mutex.lock(); for (size_t i = 0, size = args.size(); i < size; ++i) { args[i]->dump(); } io_mutex.unlock(); } // safeprintln(object a, [ ...]) // Prints the object values with trailing newline [thread safed] static CLEVER_FUNCTION(safeprintln) { io_mutex.lock(); for (size_t i = 0, size = args.size(); i < size; ++i) { args[i]->dump(); ::std::cout << ::std::endl; } io_mutex.unlock(); } } // namespace io /// Initializes Standard module CLEVER_MODULE_INIT(IOModule) { using namespace io; io_mutex.init(); BEGIN_DECLARE_FUNCTION(); addFunction(new Function("safeprint", &CLEVER_FUNC_NAME(safeprint))); addFunction(new Function("safeprintln", &CLEVER_FUNC_NAME(safeprintln))); addFunction(new Function("print", &CLEVER_FUNC_NAME(print))); addFunction(new Function("println", &CLEVER_FUNC_NAME(println))); END_DECLARE(); } }}} // clever::packages::std <|endoftext|>
<commit_before>//************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Author: Arshad Ahmad Masoodi <[email protected]> * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //************************************************************************** /** @file AliHLTMUONClusterHistoComponent.cxx @author Arshad Ahmad <[email protected]> @date 27 Nov 2009 @brief Component for onlinehistograms */ #if __GNUC__>= 3 using namespace std; #endif #include "AliHLTMUONClusterHistoComponent.h" #include "AliCDBEntry.h" #include "AliCDBManager.h" #include "AliHLTDataTypes.h" #include "AliHLTMUONConstants.h" #include "AliHLTMUONClustersBlockStruct.h" #include "AliHLTMUONDataBlockReader.h" #include <TFile.h> #include <TString.h> #include "TObjString.h" #include "TObjArray.h" /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTMUONClusterHistoComponent); AliHLTMUONClusterHistoComponent::AliHLTMUONClusterHistoComponent() : AliHLTMUONProcessor(), fChargePerClusterBending(NULL), fChargePerClusterNonBending(NULL), fNumberOfClusters(NULL), fPlotChargePerClusterBending(kTRUE), fPlotChargePerClusterNonBending(kTRUE), fPlotNClusters(kTRUE) { // see header file for class documentation } AliHLTMUONClusterHistoComponent::~AliHLTMUONClusterHistoComponent() { // see header file for class documentation if (fChargePerClusterBending) delete fChargePerClusterBending; if (fChargePerClusterNonBending) delete fChargePerClusterNonBending; if (fNumberOfClusters) delete fNumberOfClusters; } // Public functions to implement AliHLTComponent's interface. // These functions are required for the registration process const char* AliHLTMUONClusterHistoComponent::GetComponentID() { // see header file for class documentation return AliHLTMUONConstants::ClusterHistogrammerId(); // return "MUONClusterHistogrammer"; } void AliHLTMUONClusterHistoComponent::GetInputDataTypes(AliHLTComponentDataTypeList& list) { // see header file for class documentation list.clear(); list.push_back(AliHLTMUONConstants::ClusterBlockDataType() ); //list.push_back( AliHLTMUONConstants::RecHitsBlockDataType() ); //list.push_back( AliHLTMUONConstants::TriggerRecordsBlockDataType() ); } AliHLTComponentDataType AliHLTMUONClusterHistoComponent::GetOutputDataType() { // see header file for class documentation return kAliHLTDataTypeHistogram; } int AliHLTMUONClusterHistoComponent::GetOutputDataTypes(AliHLTComponentDataTypeList& tgtList) { // see header file for class documentation tgtList.clear(); tgtList.push_back( AliHLTMUONConstants::HistogramDataType() ); return tgtList.size(); } void AliHLTMUONClusterHistoComponent::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier ) { // see header file for class documentation // The total constant size is the size of the TH1F object, the space needed for // the arrays of data points and finally we add 4k for any extra streamer meta data // etc. added by ROOT. constBase = sizeof(TH1F)*3 + sizeof(Double_t)*(400*2+101) + 4*1024*3; // The multiplier can be zero since the histograms generated are a constant size // independent of the input data size. inputMultiplier = 0; } AliHLTComponent* AliHLTMUONClusterHistoComponent::Spawn() { // see header file for class documentation return new AliHLTMUONClusterHistoComponent; } int AliHLTMUONClusterHistoComponent::DoInit( int argc, const char** argv ) { // see header file for class documentation fPlotChargePerClusterBending=kTRUE; fPlotChargePerClusterNonBending=kTRUE; fPlotNClusters=kTRUE; if(fPlotChargePerClusterBending) fChargePerClusterBending = new TH1F("fChargePerClusterBending","Total Charge of clusters ",400,0,4000); if(fPlotChargePerClusterNonBending) fChargePerClusterNonBending = new TH1F("fChargePerClusterNonBending","Total Charge of clusters ",400,0,4000); if(fPlotNClusters) fNumberOfClusters = new TH1F("fNumberOfClusters","Total Number of Clusters",101,0,100); int iResult=0; TString configuration=""; TString argument=""; for (int i=0; i<argc && iResult>=0; i++) { argument=argv[i]; if (!configuration.IsNull()) configuration+=" "; configuration+=argument; } if (!configuration.IsNull()) { iResult=Configure(configuration.Data()); } return iResult; } int AliHLTMUONClusterHistoComponent::DoDeinit() { // see header file for class documentation if(fChargePerClusterBending!=NULL) delete fChargePerClusterBending; if(fChargePerClusterNonBending!=NULL) delete fChargePerClusterNonBending; if(fNumberOfClusters!=NULL) delete fNumberOfClusters; return 0; } int AliHLTMUONClusterHistoComponent::DoEvent(const AliHLTComponentEventData& /*evtData*/, const AliHLTComponentBlockData* /*blocks*/, AliHLTComponentTriggerData& /*trigData*/, AliHLTUInt8_t* /*outputPtr*/, AliHLTUInt32_t& size, AliHLTComponentBlockDataList& /*outputBlocks*/) { AliHLTUInt32_t specification = 0x0; if ( GetFirstInputBlock( kAliHLTDataTypeSOR ) || GetFirstInputBlock( kAliHLTDataTypeEOR ) ) return 0; for (const AliHLTComponentBlockData* block = GetFirstInputBlock(AliHLTMUONConstants::ClusterBlockDataType()); block != NULL;block = GetNextInputBlock()){ if (block->fDataType != AliHLTMUONConstants::ClusterBlockDataType()) continue; specification |= block->fSpecification; // The specification bit pattern should indicate all the DDLs that contributed. HLTDebug("Handling block: %u, with fDataType = '%s', fPtr = %p and fSize = %u bytes.", i, DataType2Text(block->fDataType).c_str(), block->fPtr, block->fSize ); AliHLTMUONClustersBlockReader clusterBlock(block->fPtr, block->fSize); if (not BlockStructureOk(clusterBlock)) { //FIXME: Need to inherit AliHLTMUONProcessor DoInit functionality properly for // the following Dump feature to work properly. Like in AliHLTMUONRawDataHistoComponent. //if (DumpDataOnError()) DumpEvent(evtData, blocks, trigData, outputPtr, size, outputBlocks); continue; } const AliHLTMUONClusterStruct *cluster=clusterBlock.GetArray(); for (AliHLTUInt32_t i = 0; i < clusterBlock.Nentries(); ++i){ //commented for future use //AliHLTInt32_t detelement=cluster->fDetElemId; // Detector ID number from AliRoot geometry AliHLTUInt16_t nchannelsB=cluster->fNchannelsB; // Number of channels/pads in the cluster in bending plane. AliHLTUInt16_t nchannelsNB=cluster->fNchannelsNB; // Number of channels/pads in the cluster in non-bending plane. AliHLTFloat32_t BCharge= cluster->fChargeB; // Cluster charge in bending plane. Can be -1 if invalid or uncomputed. AliHLTFloat32_t NBCharge= cluster->fChargeNB; // Cluster charge in bending plane. Can be -1 if invalid or uncomputed. if(fPlotChargePerClusterBending) fChargePerClusterBending->Fill(BCharge); if(fPlotChargePerClusterNonBending) fChargePerClusterNonBending->Fill(NBCharge); cluster++; } // forloop clusterBlock.Nentries if(fPlotNClusters and clusterBlock.Nentries()>0) fNumberOfClusters->Fill(clusterBlock.Nentries()); }//forloop clusterblock if( fPlotChargePerClusterBending ) PushBack( fChargePerClusterBending, AliHLTMUONConstants::HistogramDataType(), specification); if( fPlotChargePerClusterNonBending ) PushBack( fChargePerClusterBending, AliHLTMUONConstants::HistogramDataType(), specification); if( fPlotNClusters ) PushBack( fNumberOfClusters, AliHLTMUONConstants::HistogramDataType(), specification); return 0; } int AliHLTMUONClusterHistoComponent::Reconfigure(const char* cdbEntry, const char* chainId) { // see header file for class documentation int iResult=0; const char* path="HLT/ConfigMUON/MUONHistoComponent"; const char* defaultNotify=""; if (cdbEntry) { path=cdbEntry; defaultNotify=" (default)"; } if (path) { HLTInfo("reconfigure from entry %s%s, chain id %s", path, defaultNotify,(chainId!=NULL && chainId[0]!=0)?chainId:"<none>"); AliCDBEntry *pEntry = AliCDBManager::Instance()->Get(path/*,GetRunNo()*/); if (pEntry) { TObjString* pString=dynamic_cast<TObjString*>(pEntry->GetObject()); if (pString) { HLTInfo("received configuration object string: \'%s\'", pString->GetString().Data()); iResult=Configure(pString->GetString().Data()); } else { HLTError("configuration object \"%s\" has wrong type, required TObjString", path); } } else { HLTError("can not fetch object \"%s\" from CDB", path); } } return iResult; } int AliHLTMUONClusterHistoComponent::Configure(const char* arguments) { int iResult=0; if (!arguments) return iResult; TString allArgs=arguments; TString argument; TObjArray* pTokens=allArgs.Tokenize(" "); if (pTokens) { for (int i=0; i<pTokens->GetEntries() && iResult>=0; i++) { argument=((TObjString*)pTokens->At(i))->GetString(); if (argument.IsNull()) continue; } delete pTokens; } return iResult; } <commit_msg>Fix compile error in debug mode<commit_after>//************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Author: Arshad Ahmad Masoodi <[email protected]> * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //************************************************************************** /** @file AliHLTMUONClusterHistoComponent.cxx @author Arshad Ahmad <[email protected]> @date 27 Nov 2009 @brief Component for onlinehistograms */ #if __GNUC__>= 3 using namespace std; #endif #include "AliHLTMUONClusterHistoComponent.h" #include "AliCDBEntry.h" #include "AliCDBManager.h" #include "AliHLTDataTypes.h" #include "AliHLTMUONConstants.h" #include "AliHLTMUONClustersBlockStruct.h" #include "AliHLTMUONDataBlockReader.h" #include <TFile.h> #include <TString.h> #include "TObjString.h" #include "TObjArray.h" /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTMUONClusterHistoComponent); AliHLTMUONClusterHistoComponent::AliHLTMUONClusterHistoComponent() : AliHLTMUONProcessor(), fChargePerClusterBending(NULL), fChargePerClusterNonBending(NULL), fNumberOfClusters(NULL), fPlotChargePerClusterBending(kTRUE), fPlotChargePerClusterNonBending(kTRUE), fPlotNClusters(kTRUE) { // see header file for class documentation } AliHLTMUONClusterHistoComponent::~AliHLTMUONClusterHistoComponent() { // see header file for class documentation if (fChargePerClusterBending) delete fChargePerClusterBending; if (fChargePerClusterNonBending) delete fChargePerClusterNonBending; if (fNumberOfClusters) delete fNumberOfClusters; } // Public functions to implement AliHLTComponent's interface. // These functions are required for the registration process const char* AliHLTMUONClusterHistoComponent::GetComponentID() { // see header file for class documentation return AliHLTMUONConstants::ClusterHistogrammerId(); // return "MUONClusterHistogrammer"; } void AliHLTMUONClusterHistoComponent::GetInputDataTypes(AliHLTComponentDataTypeList& list) { // see header file for class documentation list.clear(); list.push_back(AliHLTMUONConstants::ClusterBlockDataType() ); //list.push_back( AliHLTMUONConstants::RecHitsBlockDataType() ); //list.push_back( AliHLTMUONConstants::TriggerRecordsBlockDataType() ); } AliHLTComponentDataType AliHLTMUONClusterHistoComponent::GetOutputDataType() { // see header file for class documentation return kAliHLTDataTypeHistogram; } int AliHLTMUONClusterHistoComponent::GetOutputDataTypes(AliHLTComponentDataTypeList& tgtList) { // see header file for class documentation tgtList.clear(); tgtList.push_back( AliHLTMUONConstants::HistogramDataType() ); return tgtList.size(); } void AliHLTMUONClusterHistoComponent::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier ) { // see header file for class documentation // The total constant size is the size of the TH1F object, the space needed for // the arrays of data points and finally we add 4k for any extra streamer meta data // etc. added by ROOT. constBase = sizeof(TH1F)*3 + sizeof(Double_t)*(400*2+101) + 4*1024*3; // The multiplier can be zero since the histograms generated are a constant size // independent of the input data size. inputMultiplier = 0; } AliHLTComponent* AliHLTMUONClusterHistoComponent::Spawn() { // see header file for class documentation return new AliHLTMUONClusterHistoComponent; } int AliHLTMUONClusterHistoComponent::DoInit( int argc, const char** argv ) { // see header file for class documentation fPlotChargePerClusterBending=kTRUE; fPlotChargePerClusterNonBending=kTRUE; fPlotNClusters=kTRUE; if(fPlotChargePerClusterBending) fChargePerClusterBending = new TH1F("fChargePerClusterBending","Total Charge of clusters ",400,0,4000); if(fPlotChargePerClusterNonBending) fChargePerClusterNonBending = new TH1F("fChargePerClusterNonBending","Total Charge of clusters ",400,0,4000); if(fPlotNClusters) fNumberOfClusters = new TH1F("fNumberOfClusters","Total Number of Clusters",101,0,100); int iResult=0; TString configuration=""; TString argument=""; for (int i=0; i<argc && iResult>=0; i++) { argument=argv[i]; if (!configuration.IsNull()) configuration+=" "; configuration+=argument; } if (!configuration.IsNull()) { iResult=Configure(configuration.Data()); } return iResult; } int AliHLTMUONClusterHistoComponent::DoDeinit() { // see header file for class documentation if(fChargePerClusterBending!=NULL) delete fChargePerClusterBending; if(fChargePerClusterNonBending!=NULL) delete fChargePerClusterNonBending; if(fNumberOfClusters!=NULL) delete fNumberOfClusters; return 0; } int AliHLTMUONClusterHistoComponent::DoEvent(const AliHLTComponentEventData& /*evtData*/, const AliHLTComponentBlockData* /*blocks*/, AliHLTComponentTriggerData& /*trigData*/, AliHLTUInt8_t* /*outputPtr*/, AliHLTUInt32_t& size, AliHLTComponentBlockDataList& /*outputBlocks*/) { AliHLTUInt32_t specification = 0x0; if ( GetFirstInputBlock( kAliHLTDataTypeSOR ) || GetFirstInputBlock( kAliHLTDataTypeEOR ) ) return 0; for (const AliHLTComponentBlockData* block = GetFirstInputBlock(AliHLTMUONConstants::ClusterBlockDataType()); block != NULL;block = GetNextInputBlock()){ if (block->fDataType != AliHLTMUONConstants::ClusterBlockDataType()) continue; specification |= block->fSpecification; // The specification bit pattern should indicate all the DDLs that contributed. HLTDebug("Handling block: with fDataType = '%s', fPtr = %p and fSize = %u bytes.", DataType2Text(block->fDataType).c_str(), block->fPtr, block->fSize ); AliHLTMUONClustersBlockReader clusterBlock(block->fPtr, block->fSize); if (not BlockStructureOk(clusterBlock)) { //FIXME: Need to inherit AliHLTMUONProcessor DoInit functionality properly for // the following Dump feature to work properly. Like in AliHLTMUONRawDataHistoComponent. //if (DumpDataOnError()) DumpEvent(evtData, blocks, trigData, outputPtr, size, outputBlocks); continue; } const AliHLTMUONClusterStruct *cluster=clusterBlock.GetArray(); for (AliHLTUInt32_t i = 0; i < clusterBlock.Nentries(); ++i){ //commented for future use //AliHLTInt32_t detelement=cluster->fDetElemId; // Detector ID number from AliRoot geometry AliHLTUInt16_t nchannelsB=cluster->fNchannelsB; // Number of channels/pads in the cluster in bending plane. AliHLTUInt16_t nchannelsNB=cluster->fNchannelsNB; // Number of channels/pads in the cluster in non-bending plane. AliHLTFloat32_t BCharge= cluster->fChargeB; // Cluster charge in bending plane. Can be -1 if invalid or uncomputed. AliHLTFloat32_t NBCharge= cluster->fChargeNB; // Cluster charge in bending plane. Can be -1 if invalid or uncomputed. if(fPlotChargePerClusterBending) fChargePerClusterBending->Fill(BCharge); if(fPlotChargePerClusterNonBending) fChargePerClusterNonBending->Fill(NBCharge); cluster++; } // forloop clusterBlock.Nentries if(fPlotNClusters and clusterBlock.Nentries()>0) fNumberOfClusters->Fill(clusterBlock.Nentries()); }//forloop clusterblock if( fPlotChargePerClusterBending ) PushBack( fChargePerClusterBending, AliHLTMUONConstants::HistogramDataType(), specification); if( fPlotChargePerClusterNonBending ) PushBack( fChargePerClusterBending, AliHLTMUONConstants::HistogramDataType(), specification); if( fPlotNClusters ) PushBack( fNumberOfClusters, AliHLTMUONConstants::HistogramDataType(), specification); return 0; } int AliHLTMUONClusterHistoComponent::Reconfigure(const char* cdbEntry, const char* chainId) { // see header file for class documentation int iResult=0; const char* path="HLT/ConfigMUON/MUONHistoComponent"; const char* defaultNotify=""; if (cdbEntry) { path=cdbEntry; defaultNotify=" (default)"; } if (path) { HLTInfo("reconfigure from entry %s%s, chain id %s", path, defaultNotify,(chainId!=NULL && chainId[0]!=0)?chainId:"<none>"); AliCDBEntry *pEntry = AliCDBManager::Instance()->Get(path/*,GetRunNo()*/); if (pEntry) { TObjString* pString=dynamic_cast<TObjString*>(pEntry->GetObject()); if (pString) { HLTInfo("received configuration object string: \'%s\'", pString->GetString().Data()); iResult=Configure(pString->GetString().Data()); } else { HLTError("configuration object \"%s\" has wrong type, required TObjString", path); } } else { HLTError("can not fetch object \"%s\" from CDB", path); } } return iResult; } int AliHLTMUONClusterHistoComponent::Configure(const char* arguments) { int iResult=0; if (!arguments) return iResult; TString allArgs=arguments; TString argument; TObjArray* pTokens=allArgs.Tokenize(" "); if (pTokens) { for (int i=0; i<pTokens->GetEntries() && iResult>=0; i++) { argument=((TObjString*)pTokens->At(i))->GetString(); if (argument.IsNull()) continue; } delete pTokens; } return iResult; } <|endoftext|>
<commit_before>/* * Illarionserver - server for the game Illarion * Copyright 2011 Illarion e.V. * * This file is part of Illarionserver. * * Illarionserver is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * Illarionserver is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * Illarionserver. If not, see <http://www.gnu.org/licenses/>. */ #include "LongTimeEffect.hpp" #include <sstream> #include <iostream> #include <boost/cstdint.hpp> #include "data/LongTimeEffectTable.hpp" #include "db/Connection.hpp" #include "db/ConnectionManager.hpp" #include "db/InsertQuery.hpp" #include "script/LuaLongTimeEffectScript.hpp" #include "Character.hpp" #include "Player.hpp" #include "TableStructs.hpp" #include "World.hpp" extern LongTimeEffectTable *LongTimeEffects; LongTimeEffect::LongTimeEffect(uint16_t effectId, uint32_t nextCalled) : _effectId(effectId), _effectName(""), _nextCalled(nextCalled), _numberCalled(0), _lastCalled(0), _firstadd(true) { LongTimeEffectStruct effect; LongTimeEffects->find(_effectId, effect); _effectName = effect.effectname; _values.clear(); } LongTimeEffect::LongTimeEffect(std::string name, uint32_t nextCalled) : _effectId(0), _effectName(name), _nextCalled(nextCalled), _numberCalled(0), _lastCalled(0), _firstadd(true) { LongTimeEffectStruct effect; LongTimeEffects->find(_effectId, effect); _effectId = effect.effectid; _values.clear(); } LongTimeEffect::~LongTimeEffect() { _values.clear(); } bool LongTimeEffect::callEffect(Character *target) { bool ret = false; LongTimeEffectStruct effect; if (LongTimeEffects->find(_effectId, effect)) { if (effect.script) { ret = effect.script->callEffect(this, target); _lastCalled = _nextCalled; _numberCalled++; } } else { std::cout<<"can't find effect with id: "<<_effectId<<" to call the script."<<std::endl; } return ret; } void LongTimeEffect::addValue(std::string name, uint32_t value) { VALUETABLE::iterator it = _values.find(name.c_str()); if (it != _values.end()) { it->second = value; } else { char *sname = new char[name.length() + 1]; strcpy(sname, name.c_str()); sname[ name.length()] = 0; _values[ sname ] = value; } } void LongTimeEffect::removeValue(std::string name) { VALUETABLE::iterator it = _values.find(name.c_str()); if (it != _values.end()) { _values.erase(it); } } bool LongTimeEffect::findValue(std::string name, uint32_t &ret) { VALUETABLE::iterator it = _values.find(name.c_str()); if (it != _values.end()) { ret = it->second; return true; } else { return false; } } bool LongTimeEffect::save(uint32_t playerid) { using namespace Database; PConnection connection = ConnectionManager::getInstance().getConnection(); try { connection->beginTransaction(); { InsertQuery insQuery(connection); insQuery.setServerTable("playerlteffects"); const InsertQuery::columnIndex userColumn = insQuery.addColumn("plte_playerid"); const InsertQuery::columnIndex effectColumn = insQuery.addColumn("plte_effectid"); const InsertQuery::columnIndex nextCalledColumn = insQuery.addColumn("plte_nextcalled"); const InsertQuery::columnIndex lastCalledColumn = insQuery.addColumn("plte_lastcalled"); const InsertQuery::columnIndex numberCalledColumn = insQuery.addColumn("plte_numberCalled"); insQuery.addValue(userColumn, playerid); insQuery.addValue(effectColumn, _effectId); insQuery.addValue(nextCalledColumn, _nextCalled); insQuery.addValue(lastCalledColumn, _lastCalled); insQuery.addValue(numberCalledColumn, _numberCalled); insQuery.execute(); } { InsertQuery insQuery(connection); insQuery.setServerTable("playerlteffectvalues"); const InsertQuery::columnIndex userColumn = insQuery.addColumn("pev_playerid"); const InsertQuery::columnIndex effectColumn = insQuery.addColumn("pev_effectid"); const InsertQuery::columnIndex nameColumn = insQuery.addColumn("pev_name"); insQuery.addColumn("pev_value"); insQuery.addValues<const char *, uint32_t, ltstr >(nameColumn, _values, InsertQuery::keysAndValues); insQuery.addValues(userColumn, playerid, InsertQuery::FILL); insQuery.addValues(effectColumn, _effectId, InsertQuery::FILL); insQuery.execute(); } connection->commitTransaction(); return true; } catch (std::exception &e) { std::cerr << "caught exception during saving lt effects: " << e.what() << std::endl; connection->rollbackTransaction(); return false; } return true; } <commit_msg>fix saving ltes<commit_after>/* * Illarionserver - server for the game Illarion * Copyright 2011 Illarion e.V. * * This file is part of Illarionserver. * * Illarionserver is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * Illarionserver is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * Illarionserver. If not, see <http://www.gnu.org/licenses/>. */ #include "LongTimeEffect.hpp" #include <sstream> #include <iostream> #include <boost/cstdint.hpp> #include "data/LongTimeEffectTable.hpp" #include "db/Connection.hpp" #include "db/ConnectionManager.hpp" #include "db/InsertQuery.hpp" #include "script/LuaLongTimeEffectScript.hpp" #include "Character.hpp" #include "Player.hpp" #include "TableStructs.hpp" #include "World.hpp" extern LongTimeEffectTable *LongTimeEffects; LongTimeEffect::LongTimeEffect(uint16_t effectId, uint32_t nextCalled) : _effectId(effectId), _effectName(""), _nextCalled(nextCalled), _numberCalled(0), _lastCalled(0), _firstadd(true) { LongTimeEffectStruct effect; LongTimeEffects->find(_effectId, effect); _effectName = effect.effectname; _values.clear(); } LongTimeEffect::LongTimeEffect(std::string name, uint32_t nextCalled) : _effectId(0), _effectName(name), _nextCalled(nextCalled), _numberCalled(0), _lastCalled(0), _firstadd(true) { LongTimeEffectStruct effect; LongTimeEffects->find(_effectId, effect); _effectId = effect.effectid; _values.clear(); } LongTimeEffect::~LongTimeEffect() { _values.clear(); } bool LongTimeEffect::callEffect(Character *target) { bool ret = false; LongTimeEffectStruct effect; if (LongTimeEffects->find(_effectId, effect)) { if (effect.script) { ret = effect.script->callEffect(this, target); _lastCalled = _nextCalled; _numberCalled++; } } else { std::cout<<"can't find effect with id: "<<_effectId<<" to call the script."<<std::endl; } return ret; } void LongTimeEffect::addValue(std::string name, uint32_t value) { VALUETABLE::iterator it = _values.find(name.c_str()); if (it != _values.end()) { it->second = value; } else { char *sname = new char[name.length() + 1]; strcpy(sname, name.c_str()); sname[ name.length()] = 0; _values[ sname ] = value; } } void LongTimeEffect::removeValue(std::string name) { VALUETABLE::iterator it = _values.find(name.c_str()); if (it != _values.end()) { _values.erase(it); } } bool LongTimeEffect::findValue(std::string name, uint32_t &ret) { VALUETABLE::iterator it = _values.find(name.c_str()); if (it != _values.end()) { ret = it->second; return true; } else { return false; } } bool LongTimeEffect::save(uint32_t playerid) { using namespace Database; PConnection connection = ConnectionManager::getInstance().getConnection(); try { connection->beginTransaction(); { InsertQuery insQuery(connection); insQuery.setServerTable("playerlteffects"); const InsertQuery::columnIndex userColumn = insQuery.addColumn("plte_playerid"); const InsertQuery::columnIndex effectColumn = insQuery.addColumn("plte_effectid"); const InsertQuery::columnIndex nextCalledColumn = insQuery.addColumn("plte_nextcalled"); const InsertQuery::columnIndex lastCalledColumn = insQuery.addColumn("plte_lastcalled"); const InsertQuery::columnIndex numberCalledColumn = insQuery.addColumn("plte_numbercalled"); insQuery.addValue(userColumn, playerid); insQuery.addValue(effectColumn, _effectId); insQuery.addValue(nextCalledColumn, _nextCalled); insQuery.addValue(lastCalledColumn, _lastCalled); insQuery.addValue(numberCalledColumn, _numberCalled); insQuery.execute(); } { InsertQuery insQuery(connection); insQuery.setServerTable("playerlteffectvalues"); const InsertQuery::columnIndex userColumn = insQuery.addColumn("pev_playerid"); const InsertQuery::columnIndex effectColumn = insQuery.addColumn("pev_effectid"); const InsertQuery::columnIndex nameColumn = insQuery.addColumn("pev_name"); insQuery.addColumn("pev_value"); insQuery.addValues<const char *, uint32_t, ltstr >(nameColumn, _values, InsertQuery::keysAndValues); insQuery.addValues(userColumn, playerid, InsertQuery::FILL); insQuery.addValues(effectColumn, _effectId, InsertQuery::FILL); insQuery.execute(); } connection->commitTransaction(); return true; } catch (std::exception &e) { std::cerr << "caught exception during saving lt effects: " << e.what() << std::endl; connection->rollbackTransaction(); return false; } return true; } <|endoftext|>