Created
August 26, 2017 21:14
-
-
Save kim366/960f6f8900a18fff259872ac426c2dd9 to your computer and use it in GitHub Desktop.
SFML Layer Mask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <SFML/Graphics.hpp> | |
int main() | |
{ | |
sf::Texture bg_tex; | |
bg_tex.loadFromFile("bg.jpg"); | |
sf::Sprite bg{bg_tex}; | |
sf::Texture mask_tex; | |
mask_tex.loadFromFile("mask.png"); | |
sf::Texture fg_tex; | |
fg_tex.loadFromFile("fg.jpg"); | |
sf::Shader shader; | |
shader.loadFromFile("Mix.frag", sf::Shader::Fragment); | |
shader.setUniform("tex1", bg_tex); | |
shader.setUniform("tex2", fg_tex); | |
sf::CircleShape circle_shape{100.f}; | |
circle_shape.setOrigin(100.f, 100.f); | |
sf::RenderTexture circle_tex; | |
circle_tex.create(1280, 720); | |
sf::Sprite sprite{circle_tex.getTexture()}; | |
sf::RenderWindow window({1280, 720}, "SFML Layer Mask"); | |
bool lmb_pressed{false}; | |
while (window.isOpen()) | |
{ | |
sf::Event event; | |
while (window.pollEvent(event)) | |
{ | |
if (event.type == sf::Event::Closed) | |
window.close(); | |
if (event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Left) | |
lmb_pressed = true; | |
if (event.type == sf::Event::MouseButtonReleased && event.mouseButton.button == sf::Mouse::Left) | |
lmb_pressed = false; | |
} | |
if (lmb_pressed) | |
circle_shape.setPosition(static_cast<sf::Vector2f>(sf::Mouse::getPosition(window))); | |
circle_tex.clear(); | |
circle_tex.draw(circle_shape); | |
circle_tex.display(); | |
window.clear(); | |
window.draw(sprite, &shader); | |
window.display(); | |
} | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Most credit to @fallahn | |
#version 120 | |
uniform sampler2D tex1; | |
uniform sampler2D tex2; | |
uniform sampler2D maskTex; | |
void main() | |
{ | |
vec2 coord = gl_TexCoord[0].xy; | |
coord.y = 1.0 - coord.y; | |
vec4 mixed = texture2D(maskTex, gl_TexCoord[0].xy); | |
vec4 color = mix(texture2D(tex1, coord), texture2D(tex2, coord), mixed); | |
gl_FragColor = color; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment