void Sun::draw(DrawData drawData) { RenderWindow* window = drawData.window; double zoom = drawData.zoom; Vector2i viewPos = drawData.viewPos; CircleShape sun; int r = radius / zoom; r = r < 2 ? 2 : r; sun.setRadius(r); sun.setPointCount(1024); sun.setPosition(globalToDrawCoords(viewPos, Vector2i(0, 0), zoom)); sun.setOrigin(Vector2f(r, r)); sun.setFillColor(Color(200, 200, 0)); window->draw(sun); for (int i = 0; i < moons.size(); i++) { moons.at(i).draw(window, zoom, viewPos); } for (int i = 0; i < planets.size(); i++) { planets.at(i).draw(window, zoom, viewPos); } }
Ball(float mX, float mY) { shape.setPosition(mX, mY); shape.setRadius(ballRadius); shape.setFillColor(Color::Red); shape.setOrigin(ballRadius, ballRadius); }
Bullet(Vector2f coord, int who, int test){ this->test.angle = test; this->who = who; shape.setPosition(coord); shape.setFillColor(Color::Red); shape.setRadius(5); }
// Let's create the Ball constructor. // (argument mX -> starting x coordinate) // (argument mY -> starting y coordinate) Ball(float mX, float mY) { // Apply position, radius, color and origin // to the CircleShape `shape`. shape.setPosition(mX, mY); shape.setRadius(ballRadius); shape.setFillColor(Color::Red); shape.setOrigin(ballRadius, ballRadius); }
void GameGraphics::drawCannonBalls(Time elapsedTime) { for (CannonBallList* cbl = game->cannonBallsManager.registeredCannonBalls; cbl != NULL; cbl=cbl->down) { CircleShape circle; circle.setRadius(CANNON_BALL_RADIUS); circle.setFillColor(Color::Yellow); circle.setOrigin(CANNON_BALL_RADIUS, CANNON_BALL_RADIUS); circle.setPosition(cbl->cannonBall.position); game->window.draw(circle); } }
void Spacecraft::draw(RenderWindow* window, double zoom, int index) { CircleShape body; body.setPosition(position); body.setRadius(zoom); window->draw(body); //draw prediction; drawPrediction(true, index, zoom, window); //drawForces(window); }
void Bullet::add(Vector2f f,Vector2f pos) { // CircleShape c; c.setPosition(pos); c.setFillColor(color); c.setRadius(2); if(timer.getElapsedTime() >= frequency && (ammunition > 0 || infinite)) { m_bullet.push_back(c); factor.push_back(f); timer.restart(); ammunition--; } }
void Crawler::DebugDraw( RenderTarget *target ) { if( !dead ) { CircleShape cs; cs.setFillColor( Color::Cyan ); cs.setRadius( 10 ); cs.setOrigin( cs.getLocalBounds().width / 2, cs.getLocalBounds().height / 2 ); V2d g = ground->GetPoint( edgeQuantity ); cs.setPosition( g.x, g.y ); //owner->window->draw( cs ); //UpdateHitboxes(); physBody.DebugDraw( target ); } // hurtBody.DebugDraw( target ); // hitBody.DebugDraw( target ); }
int main(int argc, char*argv[]) { // ████████ INITS 1 ████████ #ifndef COMMON_INITS1 cfg.init("bedlab.cfg"); ui2::init_ui(); Vec2i windowsize; Vec2i screen_resolution = { int(VideoMode::getDesktopMode().width), int(VideoMode::getDesktopMode().height) }; if (cfg.getvar<int>("auto_winsize")) { auto window_scale = cfg.getvar<Vec2>("window_scale"); windowsize = Vec2i(scal(Vec2(screen_resolution), window_scale)); } else { windowsize = cfg.getvar<Vec2i>("windowsize"); } winsize = Vec2(windowsize); //UI.init_console(); // ALWAYS AFTER SO IT CAN GET WINDOW SIZE ui2::init_console(); // ALWAYS AFTER SO IT CAN GET WINDOW SIZE wincenter = 0.5f*Vec2(windowsize); Vec2i windowpos; VideoMode::getDesktopMode().height; if (cfg.getvar<int>("stick_left")) { windowpos = Vec2i( screen_resolution.x - windowsize.x - 10, screen_resolution.y - windowsize.y - 40 ); } else windowpos = (Vec2i(5, 25)); sf::RenderWindow window(sf::VideoMode(windowsize.x, windowsize.y), "bedlab!", 7 //,sf::ContextSettings(0, 0, 1) ); window.setFramerateLimit(cfg.getvar<int>("fps_max")); frame_duration = 1.0f / cfg.getvar<int>("fps_max"); window.setPosition(windowpos); vector<string> keys; auto choice = cfg.getstr("app"); // show_keys(cfg.getstr("app"), keys); #endif // ████████ INITS2 ████████ #ifndef COMMON_INITS2 // we don't have a class/interface/struct with data, everything is local to this function, like a classic stack that all programs are anyway. // Texture cursor_tx; // if (!cursor_tx.loadFromFile(cfg.getstr("cursor"))) // cout << "did not load cursor" << endl; // Sprite cursor; // cursor.setTexture(cursor_tx); // cursor.setOrigin(3, 3); CircleShape cursor = mkcircle({ 0,0 }, Color::Transparent, 3, 1); Color background = cfg.getvar<Color>("background"); window.setMouseCursorVisible(false); Vec2 mpos; bool leftclicked = false, rightclicked = false; // view and zoom View view, ui_view; ui_view = view = window.getDefaultView(); float zoomlevel = 1; Vec2 mpos_abs; float frame_duration = 1.0f / cfg.getvar<int>("fps_max"); #endif // COMMON_INITS2 // ████████ APP ACTUAL ████████ float smaller_size = min(windowsize.y, windowsize.x); string descriptor; Transform transf; transf.translate(10, 10); transf.scale(Vec2(smaller_size, smaller_size)); transf_glob = transf; auto addvt_col = [&](Vec2 v, Color col) { glob_vert_single.append(Vertex(transf.transformPoint(v), col)); }; auto va_to_va_col = [&](mesh2d&idxd_v, Color col) { for (unsigned int i = 0; i < idxd_v.size(); ++i) { // if (i<) addvt_col(idxd_v[i].first, col); addvt_col(idxd_v[i].second, col); //addpt(idxd_v[i].first, Orange, 5); //addpt(idxd_v[i].second, Cyan, 5); } for (auto&a : idxd_v.verts) { addpt_col(a, col, 2); } }; auto stripify = [&](vector<Vec2> strip, Color col) { glob_vert_single = VertexArray(LineStrip); for (auto&a : strip) { glob_vert_single.append(Vertex(transf.transformPoint(a), col)); addpt_col(a, col, 2); } }; size_t edit_mode = 1; // ████████████████████████████████████████ sf::Sound sound; auto make_segment = [](int size, int amplitude) { vector<Int16> sample; for (int i = 0; i < size; ++i) { sample.push_back(amplitude*sin(float(i)*PI*2.0f)); } return sample; }; /* <Jonny> duration will be sample count * sample rate <Jonny> so at 44khz you'll have 44k samples per second <Jonny> if you have 88k samples that will last 2 second */ plot_bare pl; float sample_rate = 22050; auto make_tone = [&](float duration, float frequency, int amplitude_exp) { float sample_quantity = sample_rate * duration; vector<Int16> sample; int amplitude = 1 << amplitude_exp; float increment = frequency / sample_rate; float x = 0; for (int i = 0; i < sample_quantity; ++i){ sample.push_back(amplitude*sin(float(x)*PI*2.0f)); x += increment; } return sample; }; // http://sol.gfxile.net/interpolation/ auto make_tone_progressive_2 = [&](float duration, float frequency, int amplitude_exp) { float sample_quantity = sample_rate * duration; vector<Int16> sample; int amplitude = 1 << amplitude_exp; float increment = frequency / sample_rate; float x = 0; for (int i = 0; i < sample_quantity; ++i) { float soft = float(i) / sample_quantity; //soft = 1 - (1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft); soft = 1 - (1 - 2 * soft)*(1 - 2 * soft); soft *= amplitude; sample.push_back(soft*sin(float(x)*PI*2.0f)); x += increment; } return sample; }; auto make_tone_progressive_4 = [&](float duration, float frequency, int amplitude_exp) { float sample_quantity = sample_rate * duration; vector<Int16> sample; int amplitude = 1 << amplitude_exp; float increment = frequency / sample_rate; float x = 0; for (int i = 0; i < sample_quantity; ++i) { float soft = float(i) / sample_quantity; soft = 1 - (1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft); soft *= amplitude; sample.push_back(soft*sin(float(x)*PI*2.0f)); x += increment; } return sample; }; auto make_tone_progressive_6 = [&](float duration, float frequency, int amplitude_exp) { float sample_quantity = sample_rate * duration; vector<Int16> sample; int amplitude = 1 << amplitude_exp; float increment = frequency / sample_rate; float x = 0; for (int i = 0; i < sample_quantity; ++i) { float soft = float(i) / sample_quantity; soft = 1 - (1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft); soft *= amplitude; sample.push_back(soft*sin(float(x)*PI*2.0f)); x += increment; } return sample; }; auto sample_string2 = cfg.getstr("sound1"); auto spl1 = splitdelim(sample_string2, ','); auto params2 = splitdelim(spl1[0]); //float freq = parse<float>(params[1]); //float duration = parse<float>(params[2]); //float amplitude_exp = parse<float>(params[3]); float freq, duration, amplitude_exp, pause; int times, smoothstep_exp; dip_bars dbars(FONT, FONTSIZE, {400,20}); //dbars.add("sampling", &sampling,5, 10000); dbars.add("sample_rate", &sample_rate, 1000, 45000); dbars.add("freq", &freq,50,5000); dbars.add("duration", &duration, 0.5, 5); dbars.add("amplitude_exp", &litude_exp, 1, 14); SoundBuffer buffer; // always lived! auto load_sample2 = [&](){ auto delaystr = splitdelim(spl1[1]); vector<float> segment_sizes; float total = 0; for (auto&a : delaystr) { total += parse<float>(a); segment_sizes.push_back(parse<float>(a)); } int i = 0; vector<Int16> sample; vector<vector<Int16>> samples; for (auto&a : segment_sizes) a /= total; //for (auto&a : segment_sizes) msg(a*total); for (auto&a : segment_sizes){ auto scaled_back = duration * freq * a; int amplitude = i % 2 ? 0 : 1 << int(amplitude_exp); msg(scaled_back); samples.push_back(make_segment(scaled_back, amplitude)); ++i; } for (auto&a : samples){ concatenate(sample, a); } SoundBuffer buffer; // \param sampleRate Sample rate (number of samples to play per second) buffer.loadFromSamples(&sample[0], sample.size(), 1, sample.size()/duration); { // plut josting just plotting vector<Vec2> plot_this; int i = 0; for (auto&a : sample) { //plot_this.push_back({ float(i), 200 * float(a) / (1 << 12) }); plot_this.push_back({ float(i), float(a) }); i++; } pl.clear(); pl.from_data_normalized(plot_this); } return buffer; }; auto load_sample = [&]() { auto delaystr = splitdelim(spl1[1]); vector<float> segment_sizes; float total = 0; for (auto&a : delaystr) { total += parse<float>(a); segment_sizes.push_back(parse<float>(a)); } int i = 0; vector<Int16> sample; vector<vector<Int16>> samples; for (auto&a : segment_sizes) a /= total; //for (auto&a : segment_sizes) msg(a*total); if (smoothstep_exp == 2) { for (auto&a : segment_sizes) { samples.push_back(make_tone_progressive_2(duration*a, freq, i % 2 ? 0 : int(amplitude_exp))); ++i; } } else if (smoothstep_exp == 4){ for (auto&a : segment_sizes) { samples.push_back(make_tone_progressive_4(duration*a, freq, i % 2 ? 0 : int(amplitude_exp))); ++i; } } for (auto&a : samples) { concatenate(sample, a); } SoundBuffer buffer; // \param sampleRate Sample rate (number of samples to play per second) //sample = make_tone(2, 400, 8); //buffer.loadFromSamples(&sample[0], sample.size(), 1, sample.size() / duration); buffer.loadFromSamples(&sample[0], sample.size(), 1, sample.size() / duration); if (true) { // plut josting just plotting vector<Vec2> plot_this; int i = 0; for (auto&a : sample) { //plot_this.push_back({ float(i), 200 * float(a) / (1 << 12) }); plot_this.push_back({ float(i), float(a) }); i++; } pl.clear(); pl.from_data_normalized(plot_this); } return buffer; }; auto load_from_cfg = [ &freq, &duration, &litude_exp, &pause, ×, &descriptor, &smoothstep_exp]() { auto temp_cfg = configfile(); temp_cfg.init("bedlab.cfg"); auto sample_string = temp_cfg.getstr("sound2"); auto things = split2(sample_string, ","); auto params = split2(things[0], " "); auto segments = split2(things[1], " "); string segments_dashed = things[1]; if (segments_dashed[0] == ' ') segments_dashed = segments_dashed.substr(1); if (things[1][0] == ' ') things[1] = things[1].substr(1); if (things[2][0] == ' ') things[2] = things[2].substr(1); if (things[3][0] == ' ') things[3] = things[3].substr(1); if (things[4][0] == ' ') things[4] = things[4].substr(1); for (auto&c : segments_dashed) { if (c == ' ') c = '-'; } freq = parse<float>(params[0]); duration = parse<float>(params[1]); amplitude_exp = parse<float>(params[2]); pause = parse<float>(things[2]); times = parse<int>(things[3]); smoothstep_exp = parse<int>(things[4]); msgs(smoothstep_exp); descriptor = params[0] // freq + "_" + params[1] // duration + "_" + params[2] // amplitude_exp + "_" + segments_dashed + "_" + things[2] // pause + "_" + things[3] // times + "_" + things[4] // smoothstep_exp ; msgs(descriptor); return segments; }; auto segments = load_from_cfg(); auto flexible_expanse = [&]() { vector<float> segment_sizes, segment_concat; for (auto&a : segments) { segment_sizes.push_back(parse<float>(a)); } segment_sizes.push_back(pause); for (int i = 0; i < times; ++i) { concatenate(segment_concat, segment_sizes); } float total = 0; for (auto&a : segment_concat) total+=a; for (auto&a : segment_concat) a /= total; vector<vector<Int16>> samples; int i = 0; if (smoothstep_exp == 2) { for (auto&a : segment_concat) { samples.push_back(make_tone_progressive_2(duration*a, freq, i % 2 ? 0 : int(amplitude_exp))); ++i; } } else if (smoothstep_exp == 4) { for (auto&a : segment_concat) { samples.push_back(make_tone_progressive_4(duration*a, freq, i % 2 ? 0 : int(amplitude_exp))); ++i; } } else if (smoothstep_exp == 6) { for (auto&a : segment_concat) { samples.push_back(make_tone_progressive_6(duration*a, freq, i % 2 ? 0 : int(amplitude_exp))); ++i; } } vector<Int16> sample; for (auto&a : samples) { concatenate(sample, a); } SoundBuffer buffer; //buffer.loadFromSamples(&sample[0], sample.size(), 1, sample.size() / duration); buffer.loadFromSamples(&sample[0], sample.size(), 1, sample_rate); if (true) { // plut josting just plotting vector<Vec2> plot_this; int i = 0; for (auto&a : sample) { //plot_this.push_back({ float(i), 200 * float(a) / (1 << 12) }); plot_this.push_back({ float(i), float(a) }); i++; } pl.clear(); pl.from_data_normalized(plot_this); } return buffer; }; //buffer = load_sample(sample_string); auto make_sound = [&]() { //buffer = load_sample(); segments = load_from_cfg(); buffer = flexible_expanse(); sound.setBuffer(buffer); string filename = "rngtn_" + descriptor+".wav"; //buffer.saveToFile("file.wav"); buffer.saveToFile(filename); sound.play(); }; make_sound(); dbars.read_from_pointers(); // ████████ callbacks ████████ #ifndef LOOP_LAMBDAS draw = [&]() { window.setView(view); //////////////// OBJECTS THAT CAN ZOOMED //////////////// window.draw(glob_vert_single); for (auto&a : glob_pts)window.draw(a); for (auto&a : glob_rects)window.draw(a); for (auto&a : glob_vert)window.draw(a); for (auto&a : glob_texts)window.draw(a); // UI draw, AFTER ui view and BEFORE other draw window.setView(ui_view); //////////////// OBJECTS THAT CANNOT ZOOMED, MEANING UI //////////////// pl.draw(window); dbars.draw(window); //br.drawwithtext(window); UI.draw(window); window.draw(cursor); }; update = [&]() { }; treatkeyevent = [&](Keyboard::Key k) { switch (k) { case Keyboard::E: break; case Keyboard::I: break; case Keyboard::Q: break; case Keyboard::BackSpace: glob_pts.clear(); glob_texts.clear(); glob_rects.clear(); glob_vert.clear(); break; case Keyboard::Space: make_sound(); sound.play(); sound.setLoop(false); break; case Keyboard::S: screenshot(window); break; case Keyboard::Num1: case Keyboard::Num2: case Keyboard::Num3: case Keyboard::Num4: case Keyboard::Num5: break; } }; mousemoved = [&](Vec2 pos) { cursor.setPosition(pos); if (leftclicked); dbars.mouse_moved(pos); }; mouseclick = [&](sf::Mouse::Button button) { if (button == Mouse::Button::Left) leftclicked = true; if (button == Mouse::Button::Right) rightclicked = true; if (button == Mouse::Button::Left) dbars.mouse_click(mpos); }; mouserelease = [&](sf::Mouse::Button button) { if (button == Mouse::Button::Left) leftclicked = false; if (button == Mouse::Button::Right) rightclicked = false; if (button == Mouse::Button::Left) { dbars.mouse_release(); make_sound(); } }; loop = [&]() { while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::Escape) window.close(); treatkeyevent(event.key.code); break; case sf::Event::Closed: window.close(); break; case sf::Event::MouseButtonPressed: mouseclick(event.mouseButton.button); break; case sf::Event::MouseButtonReleased: mouserelease(event.mouseButton.button); break; case sf::Event::MouseMoved: mpos = Vec2(event.mouseMove.x, event.mouseMove.y); mpos_abs = window.mapPixelToCoords(Vec2i(mpos), view); mousemoved(mpos); break; default: treatotherevent(event); break; } } window.clear(background); update(); draw(); window.display(); } }; treatotherevent = [&](Event&e) { if (e.type == Event::MouseWheelMoved && e.mouseWheel.delta) { mpos_abs = window.mapPixelToCoords(Vec2i(mpos), view); //view = window.getView(); if (e.mouseWheel.delta < 0) { zoomlevel *= 2.f; view.setSize(view.getSize()*2.f); view.setCenter(interp(mpos_abs, view.getCenter(), 2.f)); //view.setCenter(interp(mpos_abs, view.getCenter(), 2.f)); } if (e.mouseWheel.delta > 0) { zoomlevel *= 0.5; view.setSize(view.getSize()*.5f); view.setCenter(.5f*(view.getCenter() + mpos_abs)); //view.setCenter(.5f*(view.getCenter() + mpos_abs)); } window.setView(view); } }; #endif // LOOP_LAMBDAS loop(); }
void Simulation::testons() { Event event; while(m_window.pollEvent(event)) { if(event.type == Event::Closed) m_window.close(); if(event.type == Event::MouseButtonReleased)//Si on clique, on ajoute un corps { if(event.mouseButton.button == Mouse::Left) { Vector2i mousePosition = Mouse::getPosition(m_window); m_test.setPosition(mousePosition.x, mousePosition.y); } } } //données: CircleShape cercle; CircleShape base; base.setPosition(390, 390); base.setRadius(10); base.setFillColor(Color::Red); double x(0), y(0), rayon(5); //int color[3]; m_test.getPosition(x, y); m_window.clear(Color::Black); cercle.setPosition((int)x-rayon, (int)y-rayon); cercle.setRadius(rayon); cercle.setFillColor(Color::White); double yb(400), xb(400); double coefdir = (yb - y) / (xb - x); double angle = atan(coefdir); if(x>xb) { angle = (angle+3.14); while(angle > 2*3.14) { angle -= 2*3.14; } } double angleD = angle*(360/(2*3.14)); RectangleShape vectorA; vectorA.setSize(Vector2f(50, 1)); vectorA.setPosition(x, y); vectorA.setRotation(angleD); RectangleShape vectorX; vectorX.setSize(Vector2f(50*cos(angle), 1)); vectorX.setPosition(x, y); vectorX.setFillColor(Color::Green); RectangleShape vectorY; vectorY.setSize(Vector2f(1, 50*sin(angle))); vectorY.setPosition(x, y); vectorY.setFillColor(Color::Green); m_window.draw(base); m_window.draw(cercle); m_window.draw(vectorA); m_window.draw(vectorX); m_window.draw(vectorY); m_affichageAux->setString("Angle: " + to_string(angleD)); m_window.draw(*m_affichageAux); m_window.display(); }
int main(int argc, char*argv[]) { // ████████ INITS 1 ████████ #ifndef COMMON_INITS1 cfg.init("bedlab.cfg"); ui2::init_ui(); Vec2i windowsize; Vec2i screen_resolution = { int(VideoMode::getDesktopMode().width), int(VideoMode::getDesktopMode().height) }; if (cfg.getvar<int>("auto_winsize")) { auto window_scale = cfg.getvar<Vec2>("window_scale"); windowsize = Vec2i(scal(Vec2(screen_resolution), window_scale)); } else { windowsize = cfg.getvar<Vec2i>("windowsize"); } winsize = Vec2(windowsize); //UI.init_console(); // ALWAYS AFTER SO IT CAN GET WINDOW SIZE ui2::init_console(); // ALWAYS AFTER SO IT CAN GET WINDOW SIZE wincenter = 0.5f*Vec2(windowsize); Vec2i windowpos; VideoMode::getDesktopMode().height; if (cfg.getvar<int>("stick_left")) { windowpos = Vec2i( screen_resolution.x - windowsize.x - 10, screen_resolution.y - windowsize.y - 40 ); } else windowpos = (Vec2i(5, 25)); sf::RenderWindow window(sf::VideoMode(windowsize.x, windowsize.y), "bedlab!", 7 //,sf::ContextSettings(0, 0, 1) ); window.setFramerateLimit(cfg.getvar<int>("fps_max")); frame_duration = 1.0f / cfg.getvar<int>("fps_max"); window.setPosition(windowpos); vector<string> keys; auto choice = cfg.getstr("app"); // show_keys(cfg.getstr("app"), keys); #endif // ████████ INITS2 ████████ #ifndef COMMON_INITS2 // we don't have a class/interface/struct with data, everything is local to this function, like a classic stack that all programs are anyway. // Texture cursor_tx; // if (!cursor_tx.loadFromFile(cfg.getstr("cursor"))) // cout << "did not load cursor" << endl; // Sprite cursor; // cursor.setTexture(cursor_tx); // cursor.setOrigin(3, 3); CircleShape cursor = mkcircle({ 0,0 }, Color::Transparent, 3, 1); Color background = cfg.getvar<Color>("background"); window.setMouseCursorVisible(false); Vec2 mpos; bool leftclicked = false, rightclicked = false; // view and zoom View view, ui_view; ui_view = view = window.getDefaultView(); float zoomlevel = 1; Vec2 mpos_abs; float frame_duration = 1.0f / cfg.getvar<int>("fps_max"); #endif // COMMON_INITS2 // ████████ APP ACTUAL ████████ { auto testarea = Vec2(winsize.y, winsize.y); auto offset = Vec2(-.5f*testarea); offset = { 0,0 }; int many = 4; float cellsize = 0.5*testarea.x / many; map<Vec2i, RectangleShape> zone_rects; for (int i = 0; i < many + 1; ++i) { for (int j = 0; j < many + 1; ++j) { auto c = rgb_from_hue((float((i + j) % many)) / many); c.a = 128; auto r = mkrect2( Vec2(i*cellsize, j*cellsize) //+ offset , Vec2(1, 1)*(cellsize - 10), Color::Transparent, 5, false ); r.setOutlineColor(c); //auto r_p = new RectangleShape(); //*r_p = r; //grid[Vec2i(i, j)].insert(r_p); zone_rects[Vec2i(i, j)] = r; lf.logw(strfy( (float((i + j) % many)) / many) + " " + strfy(c) ); } } } set<Vec2i> surround = { Vec2i(-1, -1) , Vec2i(0, -1) , Vec2i(1, -1) , Vec2i(1, 0) , Vec2i(1, 1) , Vec2i(0, 1) , Vec2i(-1, 1) , Vec2i(-1, 0), Vec2i(0, 0) }, active_chunks; float cell_size = 30; RectangleShape view_center = mkrect2({ 0,0 }, { 10,10 }, Color::Transparent, 1); RectangleShape world_center = mkrect2({ 0,0 }, { 6,6 }, Color::Red); //Vec2i reference_chunk = { 2,2 }; Vec2i reference_chunk = {0,0}; map<Vec2i, RectangleShape> chunks; for (int i = -5; i <= 5; ++i) { for (int j = -5; j <= 5; ++j) { chunks[Vec2i(i, j)] = mkrect2(cell_size*Vec2(i, j), { cell_size,cell_size }, Color::Transparent, 1); } } auto recenter_world = [&](Vec2i shift) { msgm("shifting", shift); world_center.move(Vec2(shift)*cell_size); for (auto&a : chunks) { a.second.move(Vec2(shift)*cell_size); } view.move(Vec2(shift)*cell_size); //world_center.setPosition(view.getCenter()); world_center.move(-Vec2(shift)*cell_size); //for (auto&a : chunks) { // a.second.setPosition(cell_size*Vec2(shift)); //} for (auto&a : active_chunks) { chunks[a].setFillColor(Color::Transparent); } active_chunks.clear(); // activate chunk surrounding the reference for (auto&a : surround) { auto index = reference_chunk + a; active_chunks.insert(index); //chunks[index].setPosition(cell_size*Vec2(index)); chunks[index].setFillColor(Color(255,0,0,128)); } }; recenter_world({ 0,0 }); auto recenter_check = [&]() { view_center.setPosition(view.getCenter()); //auto shift = Vec2i(2.f*view.getCenter() / (1.2f*cellsize)); auto shift = -Vec2i(0.8f * view.getCenter() / cell_size); show(view.getCenter()); //if (view.getCenter().x > cell_size*1.2f) reference_chunk.x -= 1; //if (view.getCenter().y > cell_size*1.2f) reference_chunk.y -= 1; //if (view.getCenter().x < -cell_size*1.2f) reference_chunk.x += 1; //if (view.getCenter().y < -cell_size*1.2f) reference_chunk.y += 1; //msg("recenter triggered!"); //reposition_chunks(); //reference_chunk = Vec2i(); if (shift != Vec2i{0, 0}) recenter_world(shift); reference_chunk -= shift; }; // ████████ callbacks ████████ bool panning = false; Vec2 previous_mouse_pos; view.setCenter({ 0,0 }); //view.sets #ifndef LOOP_LAMBDAS draw = [&]() { window.setView(view); //////////////// OBJECTS THAT CAN ZOOMED //////////////// window.draw(glob_vert_single); for (auto&a : glob_pts)window.draw(a); for (auto&a : glob_rects)window.draw(a); for (auto&a : glob_vert)window.draw(a); for (auto&a : glob_texts)window.draw(a); //////////////// OBJECTS THAT CAN ZOOMED //////////////// //for (auto&a : zone_rects) window.draw(a.second); for (auto&a : chunks) window.draw(a.second); window.draw(view_center); window.draw(world_center); // UI draw, AFTER ui view and BEFORE other draw window.setView(ui_view); //////////////// OBJECTS THAT CANNOT ZOOMED, MEANING UI //////////////// //br.drawwithtext(window); ui2::draw(window); //UI.draw(window); window.draw(cursor); }; update = [&]() { recenter_check(); }; treatkeyevent = [&](Keyboard::Key k) { switch (k) { case Keyboard::E: break; case Keyboard::I: break; case Keyboard::Q: break; case Keyboard::BackSpace: glob_pts.clear(); glob_texts.clear(); glob_rects.clear(); glob_vert.clear(); break; case Keyboard::Space: break; case Keyboard::S: screenshot(window); break; case Keyboard::Num1: case Keyboard::Num2: case Keyboard::Num3: case Keyboard::Num4: case Keyboard::Num5: break; } }; mousemoved = [&](Vec2 pos) { cursor.setPosition(pos); if (leftclicked); if (panning) { view.move((previous_mouse_pos - pos)); } previous_mouse_pos = pos; }; mouseclick = [&](sf::Mouse::Button button) { if (button == Mouse::Button::Left) leftclicked = true; if (button == Mouse::Button::Right) rightclicked = true; if (button == Mouse::Button::Left) { }; panning = leftclicked; }; mouserelease = [&](sf::Mouse::Button button) { if (button == Mouse::Button::Left) leftclicked = false; if (button == Mouse::Button::Right) rightclicked = false; if (button == Mouse::Button::Left) { } panning = leftclicked; }; loop = [&]() { while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::Escape) window.close(); treatkeyevent(event.key.code); break; case sf::Event::Closed: window.close(); break; case sf::Event::MouseButtonPressed: mouseclick(event.mouseButton.button); break; case sf::Event::MouseButtonReleased: mouserelease(event.mouseButton.button); break; case sf::Event::MouseMoved: mpos = Vec2(event.mouseMove.x, event.mouseMove.y); mpos_abs = window.mapPixelToCoords(Vec2i(mpos), view); mousemoved(mpos); break; default: treatotherevent(event); break; } } window.clear(background); update(); draw(); window.display(); } }; treatotherevent = [&](Event&e) { if (e.type == Event::MouseWheelMoved && e.mouseWheel.delta) { mpos_abs = window.mapPixelToCoords(Vec2i(mpos), view); //view = window.getView(); if (e.mouseWheel.delta < 0) { zoomlevel *= 2.f; view.setSize(view.getSize()*2.f); view.setCenter(interp(mpos_abs, view.getCenter(), 2.f)); //view.setCenter(interp(mpos_abs, view.getCenter(), 2.f)); } if (e.mouseWheel.delta > 0) { zoomlevel *= 0.5; view.setSize(view.getSize()*.5f); view.setCenter(.5f*(view.getCenter() + mpos_abs)); //view.setCenter(.5f*(view.getCenter() + mpos_abs)); } window.setView(view); } }; #endif // LOOP_LAMBDAS loop(); }
int main(int argc, char** argv) { RenderWindow window(sf::VideoMode(W_WIDTH,W_HEIGHT),"Hello",sf::Style::Close); View view{ FloatRect{0,0,V_WIDTH,V_HEIGHT} }; View defaultView = View{ FloatRect{ 0,0, 1600, 1200 } }; //window.setView(view); Physics physics{ {0.f, 9.8f}, 10.f }; //LightMap lights{view}; LightMap lights{ defaultView }; auto playerLight = lights.createLight("../assets/lightmask.png", 400, 370, 3.f); //lights.createLight("../assets/lightmask.png", 200, 100, 3.f); Clock clock; physics.spawnStaticBox(40.f, 60.f, 800.f, 40.f); physics.spawnStaticBox(80.f, 110.f, 800.f, 40.f); auto pPlayerBody = physics.spawnDynamicCircle(3.f, 400.f, 0.f); Texture tex; tex.loadFromFile("../assets/tile.png"); tex.setSmooth(true); Shader blendShader; if (!blendShader.loadFromFile("../src/test.frag", Shader::Fragment)) std::cout << "Failed to load blend fragment shader" << std::endl; Texture playerTex; playerTex.loadFromFile("../assets/player.png"); playerTex.setSmooth(true); sf::Event ev; Texture worldTex; worldTex.create(W_WIDTH, W_HEIGHT); Sprite displaySprite; Font font; font.loadFromFile("../assets/kenney_bold.ttf"); Text framerate; framerate.setFont(font); framerate.setCharacterSize(40); framerate.setPosition(1100, 200); framerate.setColor(sf::Color::White); while (window.isOpen()) { while (window.pollEvent(ev)) { if (ev.type == Event::Closed) { window.close(); } if (ev.type == Event::KeyPressed) { if (ev.key.code == sf::Keyboard::Left) { if (pPlayerBody->GetLinearVelocity().x - (MS_X / 100) > -(2 * MS_X / 100)) pPlayerBody->ApplyForceToCenter({-MS_X, 0.f},true); else pPlayerBody->ApplyForceToCenter({ -(2 * MS_X / 100) - pPlayerBody->GetLinearVelocity().x , 0.f }, true); } if (ev.key.code == sf::Keyboard::Right) { if (pPlayerBody->GetLinearVelocity().x + (MS_X / 100) < (2 * MS_X / 100)) pPlayerBody->ApplyForceToCenter({ MS_X, 0.f }, true); else pPlayerBody->ApplyForceToCenter({ (2 * MS_X / 100) - pPlayerBody->GetLinearVelocity().x , 0.f }, true); } if (ev.key.code == sf::Keyboard::Space) { if (pPlayerBody->GetLinearVelocity().y + (MS_X / 100) < (2 * MS_X / 100)) pPlayerBody->ApplyForceToCenter({ 0.f, -MS_X * 2 }, true); //else //pPlayerBody->ApplyForceToCenter({ 0.f, (3 * MS_X / 100) - pPlayerBody->GetLinearVelocity().y }, true); } } if (ev.type == Event::JoystickButtonPressed) { std::cout << ev.joystickButton.button << std::endl; } if (ev.type == Event::JoystickMoved) { std::cout << ev.joystickMove.axis << std::endl; } } physics.step(1.f / 30.f); window.clear(); auto playerPos = pPlayerBody->GetPosition(); view.setCenter(SCALE * playerPos.x, SCALE * playerPos.y); //window.setView(view); auto lightSize = playerLight->getSprite().getTexture()->getSize(); // 3.f is the player body radius playerLight->setPosition( playerPos.x * SCALE - lightSize.x - 3.f * SCALE * 2 , playerPos.y * SCALE - lightSize.y - 3.f * SCALE * 2); auto bodyIt = physics.getBodyList(); //lights.updateView(view); lights.render(); while (bodyIt != nullptr) { auto pos = bodyIt->GetPosition(); if (bodyIt->GetType() == b2_dynamicBody) { CircleShape sprite; sprite.setTexture(&playerTex); auto playerShape = *(b2CircleShape*)(bodyIt->GetFixtureList()->GetShape()); sprite.setRadius(playerShape.m_radius * SCALE); sprite.setOrigin(playerShape.m_radius * SCALE, playerShape.m_radius * SCALE); sprite.setPosition(SCALE * pos.x, SCALE * pos.y); sprite.setRotation(bodyIt->GetAngle() * 180 / b2_pi); window.draw(sprite); } else // ground { RectangleShape sprite; sprite.setSize({800.f, 40.f}); sprite.setOrigin(400, 20); sprite.setPosition(pos.x * SCALE, pos.y * SCALE); sprite.setRotation(bodyIt->GetAngle() * 180 / b2_pi); sprite.setTexture(&tex); window.draw(sprite); } bodyIt = bodyIt->GetNext(); } window.draw(Sprite{ lights.getLightMapTexture() }, BlendMultiply); float frameTime = 1.f / clock.getElapsedTime().asSeconds(); clock.restart(); framerate.setString(std::to_string((int)frameTime) + " fps"); window.draw(framerate); window.display(); } }
int main(int argc, char*argv[]) { #ifndef COMMON_INITS1 cfg.init("bedlab.cfg"); Vec2i windowsize; Vec2i screen_resolution = { int(VideoMode::getDesktopMode().width), int(VideoMode::getDesktopMode().height) }; if (cfg.getvar<int>("auto_winsize")) { auto winscale_which = cfg.getstr("winscale_which"); auto window_scale = cfg.getvar<Vec2>(winscale_which); windowsize = Vec2i(scal(Vec2(screen_resolution), window_scale)); } else { windowsize = cfg.getvar<Vec2i>("windowsize"); } winsize = Vec2(windowsize); UI.init_console(); // ALWAYS AFTER SO IT CAN GET WINDOW SIZE wincenter = 0.5f*Vec2(windowsize); Vec2i windowpos; VideoMode::getDesktopMode().height; if (cfg.getvar<int>("stick_left")) { windowpos = Vec2i( screen_resolution.x - windowsize.x - 10, screen_resolution.y - windowsize.y - 40 ); } else windowpos = (Vec2i(5, 25)); sf::RenderWindow window(sf::VideoMode(windowsize.x, windowsize.y), "bedlab!", 7 //,sf::ContextSettings(0, 0, 1) ); window.setFramerateLimit(cfg.getvar<int>("fps_max")); frame_duration = 1.0f / cfg.getvar<int>("fps_max"); window.setPosition(windowpos); vector<string> keys; auto choice = cfg.getstr("app"); // show_keys(cfg.getstr("app"), keys); #endif // COMMON_INITS1 #ifndef COMMON_INITS2 // we don't have a class/interface/struct with data, everything is local to this function, like a classic stack that all programs are anyway. // Texture cursor_tx; // if (!cursor_tx.loadFromFile(cfg.getstr("cursor"))) // cout << "did not load cursor" << endl; // Sprite cursor; // cursor.setTexture(cursor_tx); // cursor.setOrigin(3, 3); CircleShape cursor = mkcircle({ 0,0 }, Color::Transparent, 3, 1); Color background = cfg.getvar<Color>("background"); window.setMouseCursorVisible(false); Vec2 mpos; bool leftclicked = false, rightclicked = false; // view and zoom View view, ui_view; ui_view = view = window.getDefaultView(); float zoomlevel = 1; Vec2 mpos_abs; float frame_duration = 1.0f / cfg.getvar<int>("fps_max"); float smaller_size = 0.95*min(windowsize.y, windowsize.x); auto all_pt_mult = cfg.getvar<float>("all_pt_mult"); all_pt_size = all_pt_mult * smaller_size; //Transform transf; //transf_glob.translate(smaller_size*0.1, smaller_size*0.5); transf_glob.translate(smaller_size*0.02, smaller_size*0.02); transf_glob.scale(Vec2(smaller_size, smaller_size)); //transf_glob = transf; glob_vert_single = VertexArray(Lines); #endif // COMMON_INITS2 #ifndef COMMON_INITS3 bool point_text = cfg.getvar<int>("street_gen_point_text"); bool alternate_font = cfg.getvar<int>("alternate_font"); glob_vert = vector<VertexArray>(10, VertexArray(LineStrip)); string bar_font; Vec2 barsize; auto winscale_which = cfg.getstr("winscale_which"); if (winscale_which == "winscale_smallest" || winscale_which == "winscale_laptop") { bar_font = UI.small_font;; barsize = { 40,7 }; } else if (winscale_which == "winscale_largest" || winscale_which == "winscale_large") { bar_font = UI.default_font; barsize = { 100,15 }; } else { bar_font = UI.default_font; barsize = { 100,15 }; } //dip_bars dbars(UI.fonts["unaligned"], UI.fontsizes[UI.default_font], { 100,15 }); dip_bars dbars(UI.fonts[bar_font], UI.fontsizes[UI.default_font], barsize, { 1,1 }); // tests in lambdas map<string, function<void(void)>> test_lambdas; VertexArray grid(Lines); auto make_grid = [&](float resolution) { // dummy grid grid.clear(); Color col(64, 64, 64, 32); // glob_vert = vector<VertexArray>(10, VertexArray(Lines)); for (int i = 0; i <= int(resolution); ++i) for (int j = 0; j <= int(resolution); ++j) { grid.append(Vertex(tr(Vec2(i / resolution, 0)), col)); grid.append(Vertex(tr(Vec2(i / resolution, 1)), col)); grid.append(Vertex(tr(Vec2(0, i / resolution)), col)); grid.append(Vertex(tr(Vec2(1, i / resolution)), col)); } }; // actual tests diag_draw ddraw; function<void(void)> test_current = [&] {msg("no test configured"); }; auto street_gen_test = cfg.getstr("street_gen_test"); if (test_lambdas.count(street_gen_test)) { test_current = test_lambdas[street_gen_test]; msgm("ok, using test", street_gen_test); test_current(); } else { msg("invalid test choice string thing bing ding king ping ring sing wing wing"); } #endif // COMMON_INITS3 // █████████████████████ APP ACTUAL █████████████████████ // █████████████████████ callbacks █████████████████████ #ifndef LOOP_LAMBDAS draw = [&]() { window.setView(view); //////////////// OBJECTS THAT CAN ZOOMED //////////////// window.draw(grid); window.draw(glob_vert_single); for (auto&a : glob_pts)window.draw(a); for (auto&a : glob_rects)window.draw(a); for (auto&a : glob_vert)window.draw(a); if (point_text) for (auto&a : glob_texts)window.draw(a); ddraw.draw(window); // UI draw, AFTER ui view and BEFORE other draw window.setView(ui_view); //////////////// OBJECTS THAT CANNOT ZOOMED, MEANING UI //////////////// dbars.draw(window); //br.drawwithtext(window); UI.draw(window); window.draw(cursor); }; update = [&]() { }; treatkeyevent = [&](Keyboard::Key k) { switch (k) { case Keyboard::E: break; case Keyboard::T: point_text ^= 1; break; case Keyboard::Q: break; case Keyboard::BackSpace: glob_pts.clear(); glob_texts.clear(); glob_rects.clear(); glob_vert.clear(); break; case Keyboard::Space: break; case Keyboard::S: screenshot(window); break; case Keyboard::Num1: case Keyboard::Num2: case Keyboard::Num3: case Keyboard::Num4: case Keyboard::Num5: break; } }; mousemoved = [&](Vec2 pos) { dbars.mouse_moved(mpos); cursor.setPosition(pos); if (leftclicked); }; mouseclick = [&](sf::Mouse::Button button) { if (button == Mouse::Button::Left) leftclicked = true; if (button == Mouse::Button::Right) rightclicked = true; if (button == Mouse::Button::Left) { dbars.mouse_click(mpos); //test_search(); //test_inter(); } if (button == Mouse::Button::Right) { //test_inter(); } }; mouserelease = [&](sf::Mouse::Button button) { if (button == Mouse::Button::Left) leftclicked = false; if (button == Mouse::Button::Right) rightclicked = false; dbars.mouse_release(); test_current(); }; loop = [&]() { while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::Escape) window.close(); treatkeyevent(event.key.code); break; case sf::Event::Closed: window.close(); break; case sf::Event::MouseButtonPressed: mouseclick(event.mouseButton.button); break; case sf::Event::MouseButtonReleased: mouserelease(event.mouseButton.button); break; case sf::Event::MouseMoved: mpos = Vec2(event.mouseMove.x, event.mouseMove.y); mpos_abs = window.mapPixelToCoords(Vec2i(mpos), view); mousemoved(mpos); break; default: treatotherevent(event); break; } } window.clear(background); update(); draw(); //static bool once = true; //if (once) { // screenshot(window); // once = false; //} window.display(); } }; treatotherevent = [&](Event&e) { if (e.type == Event::MouseWheelMoved && e.mouseWheel.delta) { mpos_abs = window.mapPixelToCoords(Vec2i(mpos), view); //view = window.getView(); if (e.mouseWheel.delta < 0) { zoomlevel *= 2.f; view.setSize(view.getSize()*2.f); view.setCenter(interp(mpos_abs, view.getCenter(), 2.f)); //view.setCenter(interp(mpos_abs, view.getCenter(), 2.f)); } if (e.mouseWheel.delta > 0) { zoomlevel *= 0.5; view.setSize(view.getSize()*.5f); view.setCenter(.5f*(view.getCenter() + mpos_abs)); //view.setCenter(.5f*(view.getCenter() + mpos_abs)); } window.setView(view); } }; #endif // LOOP_LAMBDAS loop(); }