sfml.graphics
2D graphics module: sprites, text, shapes, ...
Attributes
Members list
Type members
Classlikes
Blending modes for drawing.
Blending modes for drawing.
BlendMode is a class that represents a blend mode.
A blend mode determines how the colors of an object you draw are mixed with the colors that are already in the buffer.
The class is composed of 6 components, each of which has its own public member variable:
- Color Source Factor (
colorSrcFactor
) - Color Destination Factor (
colorDstFactor
) - Color Blend Equation (
colorEquation
) - Alpha Source Factor (
alphaSrcFactor
) - Alpha Destination Factor (
alphaDstFactor
) - Alpha Blend Equation (
alphaEquation
)
The source factor specifies how the pixel you are drawing contributes to the final color. The destination factor specifies how the pixel already drawn in the buffer contributes to the final color.
The color channels RGB (red, green, blue; simply referred to as color) and A (alpha; the transparency) can be treated separately. This separation can be useful for specific blend modes, but most often you won't need it and will simply treat the color as a single unit.
The blend factors and equations correspond to their OpenGL equivalents. In general, the color of the resulting pixel is calculated according to the following formula (src
is the color of the source pixel, dst
the color of the destination pixel, the other variables correspond to the public members, with the equations being + or - operators):
dst.rgb = colorSrcFactor * src.rgb (colorEquation) colorDstFactor * dst.rgb
dst.a = alphaSrcFactor * src.a (alphaEquation) alphaDstFactor * dst.a
All factors and colors are represented as floating point numbers between 0 and 1. Where necessary, the result is clamped to fit in that range.
The most common blending modes are defined as constants:
val alphaBlending = BlendMode.Alpha()
val additiveBlending = BlendMode.Add()
val multiplicativeBlending = BlendMode.Multiply()
val noBlending = BlendMode.None()
In SFML, a blend mode can be specified every time you draw a Drawable object to a render target. It is part of the RenderStates compound that is passed to the member function RenderTarget.draw().
Value parameters
- alphaDstFactor
-
Destination blending factor for the alpha channel.
- alphaEquation
-
Blending equation for the alpha channel.
- alphaSrcFactor
-
Source blending factor for the alpha channel.
- colorDstFactor
-
Destination blending factor for the color channels.
- colorEquation
-
Blending equation for the color channels.
- colorSrcFactor
-
Source blending factor for the color channels.
Attributes
- See also
- Companion
- object
- Supertypes
-
class Objecttrait Matchableclass Any
Specialized shape representing a circle.
Specialized shape representing a circle.
This class inherits all the functions of Transformable (position, rotation, scale, bounds, ...) as well as the functions of Shape (outline, color, texture, ...).
Since the graphics card can't draw perfect circles, we have to fake them with multiple triangles connected to each other. The "points count" property of CircleShape defines how many of these triangles to use, and therefore defines the quality of the circle.
The number of points can also be used for another purpose; with small numbers you can create any regular polygon shape: equilateral triangle, square, pentagon, hexagon, ...
val window: RenderWindow = ???
val circle = CircleShape()
circle.radius = 150
circle.outlineColor = Color.Red()
circle.outlineThickness = 5
circle.position = (10, 20)
window.draw(circle)
Attributes
- See also
- Companion
- object
- Supertypes
Attributes
- Companion
- trait
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
CircleShape.type
Utility class for manipulating RGBA colors.
Utility class for manipulating RGBA colors.
Color is a simple color class composed of 4 components:
- Red
- Green
- Blue
- Alpha (opacity)
Each component is a public member, an unsigned integer in the range [0, 255]. Thus, colors can be constructed and manipulated very easily:
val color = Color(255, 0, 0) // red
val black = color.copy(r = 0) // make it black
val blue = color.copy(b = 128.toByte) // make it dark blue
The fourth component of colors, named "alpha", represents the opacity of the color. A color with an alpha value of 255 will be fully opaque, while an alpha value of 0 will make a color fully transparent, whatever the value of the other components is.
The most common colors are already defined as static variables:
val black = Color.Black()
val white = Color.White()
val red = Color.Red()
val green = Color.Green()
val blue = Color.Blue()
val yellow = Color.Yellow()
val magenta = Color.Magenta()
val cyan = Color.Cyan()
val transparent = Color.Transparent()
Value parameters
- a
-
Alpha (opacity) component.
- b
-
Blue component.
- g
-
Green component.
- r
-
Red component.
Attributes
- Companion
- object
- Supertypes
-
class Objecttrait Matchableclass Any
Abstract base class for objects that can be drawn to a render target.
Abstract base class for objects that can be drawn to a render target.
Drawable is a very simple base class that allows objects of derived classes to be drawn to a RenderTarget.
All you have to do in your derived class is to override the draw function.
Note that inheriting from Drawable is not mandatory, but it allows this nice syntax window.draw(object)
rather than object.draw(window)
, which is more consistent with other SFML classes.
class MyDrawable(sprite: Sprite) extends Drawable:
override def draw(target: RenderTarget, states: RenderStates): Unit =
// You can draw other high-level objects
target.draw(sprite, states)
Attributes
- See also
- Companion
- object
- Supertypes
-
class Objecttrait Matchableclass Any
- Known subtypes
Class for loading and manipulating character fonts.
Class for loading and manipulating character fonts.
Fonts can be loaded from a file, from memory or from a custom stream, and supports the most common types of fonts.
See the loadFromFile function for the complete list of supported formats.
Once it is loaded, a Font instance provides three types of information about the font:
- Global metrics, such as the line spacing
- Per-glyph metrics, such as bounding box or kerning
- Pixel representation of glyphs
Fonts alone are not very useful: they hold the font data but cannot make anything useful of it. To do so you need to use the Text class, which is able to properly output text with several options such as character size, style, color, position, rotation, etc. This separation allows more flexibility and better performances: indeed a Font is a heavy resource, and any operation on it is slow (often too slow for real-time applications). On the other side, a Text is a lightweight object which can combine the glyphs data and metrics of a Font to display any text on a render target. Note that it is also possible to bind several Text instances to the same Font.
It is important to note that the Text instance doesn't copy the font that it uses, it only keeps a reference to it. Thus, a Font must not be destructed while it is used by a Text (i.e. never write a function that uses a local Font instance for creating a text).
// Declare a new font
val font = Font()
// Load it from a file
if !(font.loadFromFile("arial.ttf")) then
// error...
???
// Create a text which uses our font
val text1 = Text();
text1.font = font
text1.characterSize = 30
// Create another text using the same font, but with different parameters
val text2 = Text()
text2.font = font
text2.characterSize = 50
Apart from loading font files, and passing them to instances of Text, you should normally not have to deal directly with this class. However, it may be useful to access the font metrics or rasterized glyphs for advanced usage.
Note that if the font is a bitmap font, it is not scalable, thus not all requested sizes will be available to use. This needs to be taken into consideration when using Text. If you need to display text of a certain size, make sure the corresponding bitmap font that supports that size is used.
Attributes
- See also
- Companion
- object
- Supertypes
-
class Objecttrait Matchableclass Any
Attributes
- Companion
- object
- Supertypes
-
class Objecttrait Matchableclass Any
Attributes
- Companion
- object
- Supertypes
-
class Objecttrait Matchableclass Any
Specialized shape representing a rectangle.
Specialized shape representing a rectangle.
This class inherits all the functions of Transformable (position, rotation, scale, bounds, ...) as well as the functions of Shape (outline, color, texture, ...).
val window: RenderWindow = ???
val rectangle = RectangleShape()
rectangle.size = (100, 50)
rectangle.outlineColor = Color.Red()
rectangle.outlineThickness = 5
rectangle.position = (10, 20)
window.draw(rectangle)
Attributes
- See also
- Companion
- object
- Supertypes
Attributes
- Companion
- trait
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
RectangleShape.type
Attributes
- Companion
- object
- Supertypes
-
class Objecttrait Matchableclass Any
Attributes
- Companion
- trait
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
RenderStates.type
Base class for all render targets (window, texture, ...)
Base class for all render targets (window, texture, ...)
RenderTarget defines the common behavior of all the 2D render targets usable in the graphics module.
It makes it possible to draw 2D entities like sprites, shapes, text without using any OpenGL command directly.
A RenderTarget is also able to use views (View), which are a kind of 2D cameras. With views you can globally scroll, rotate or zoom everything that is drawn, without having to transform every single entity. See the documentation of View for more details and sample pieces of code about this class.
On top of that, render targets are still able to render direct OpenGL stuff. It is even possible to mix together OpenGL calls and regular SFML drawing commands. When doing so, make sure that OpenGL states are not messed up by calling the pushGLStates/popGLStates functions.
Attributes
- See also
- Companion
- object
- Supertypes
-
class Objecttrait Matchableclass Any
- Known subtypes
-
trait RenderTexturetrait RenderWindow
Attributes
- Companion
- trait
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
RenderTarget.type
Attributes
- Companion
- object
- Supertypes
Attributes
- Companion
- trait
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
RenderTexture.type
Window that can serve as a target for 2D drawing.
Window that can serve as a target for 2D drawing.
RenderWindow is the main class of the Graphics module.
It defines an OS window that can be painted using the other classes of the graphics module.
RenderWindow is derived from Window, thus it inherits all its features: events, window management, OpenGL rendering, etc. See the documentation of Window for a more complete description of all these features, as well as code examples.
On top of that, RenderWindow adds more features related to 2D drawing with the graphics module (see its base class RenderTarget for more details). Here is a typical rendering and event loop with a RenderWindow:
import sfml.window.{Event, VideoMode}
val sprite: Sprite = ???
val circle: CircleShape = ???
val text: Text = ???
// Declare and create a new render-window
val window = RenderWindow(VideoMode(800, 600), "SFML window")
// Limit the framerate to 60 frames per second (this step is optional)
window.framerateLimit = 60;
// The main loop - ends as soon as the window is closed
while window.isOpen() do
// Event processing
for event <- window.pollEvent() do
event match
// Request for closing the window
case Event.Closed() => window.close()
case _ => ()
// Clear the whole window before rendering a new frame
window.clear()
// Draw some graphical entities
window.draw(sprite)
window.draw(circle)
window.draw(text)
// End the current frame and display its contents on screen
window.display()
Attributes
- Companion
- object
- Supertypes
Attributes
- Companion
- trait
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
RenderWindow.type
Attributes
- Supertypes
-
trait Enumtrait Serializabletrait Producttrait Equalsclass Objecttrait Matchableclass AnyShow all
Base class for textured shapes with outline.
Base class for textured shapes with outline.
Shape is a drawable class that allows to define and display a custom convex shape on a render target.
It's only an abstract base, it needs to be specialized for concrete types of shapes (circle, rectangle, convex polygon, star, ...).
In addition to the attributes provided by the specialized shape classes, a shape always has the following attributes:
- a texture
- a texture rectangle
- a fill color
- an outline color
- an outline thickness
Each feature is optional, and can be disabled easily:
- the texture can be
None
- the fill/outline colors can be Transparent
- the outline thickness can be zero
You can write your own derived shape class, there are only two functions to override:
pointCount
must return the number of points of the shapepoint
must return the points of the shape
Attributes
- See also
- Companion
- object
- Supertypes
- Known subtypes
-
trait CircleShapetrait RectangleShape
Drawable representation of a texture, with its own transformations, color, etc.
Drawable representation of a texture, with its own transformations, color, etc.
Sprite is a drawable class that allows to easily display a texture (or a part of it) on a render target.
It inherits all the functions from Transformable: position, rotation, scale, origin. It also adds sprite-specific properties such as the texture to use, the part of it to display, and some convenience functions to change the overall color of the sprite, or to get its bounding rectangle.
Sprite works in combination with the Texture class, which loads and provides the pixel data of a given texture.
The separation of Sprite and Texture allows more flexibility and better performances: indeed a Texture is a heavy resource, and any operation on it is slow (often too slow for real-time applications). On the other side, a Sprite is a lightweight object which can use the pixel data of a Texture and draw it with its own transformation/color/blending attributes.
It is important to note that the Sprite instance doesn't copy the texture that it uses, it only keeps a reference to it. Thus, a Texture must not be destroyed while it is used by a Sprite (i.e. never write a function that uses a local Texture instance for creating a sprite).
See also the note on coordinates and undistorted rendering in Transformable.
import sfml.window.VideoMode
val window: RenderWindow = ???
val texture = Texture()
texture.loadFromFile("texture.png")
val sprite = Sprite()
sprite.texture = texture
sprite.textureRect = Rect(10, 10, 50, 30)
sprite.color = Color(255, 255, 255, 200)
sprite.position = (100, 25)
window.draw(sprite)
Attributes
- See also
- Companion
- object
- Supertypes
Graphical text that can be drawn to a render target.
Graphical text that can be drawn to a render target.
Text is a drawable class that allows to easily display some text with custom style and color on a render target.
It inherits all the functions from Transformable: position, rotation, scale, origin. It also adds text-specific properties such as the font to use, the character size, the font style (bold, italic, underlined and strike through), the text color, the outline thickness, the outline color, the character spacing, the line spacing and the text to display of course. It also provides convenience functions to calculate the graphical size of the text, or to get the global position of a given character.
Text works in combination with the Font class, which loads and provides the glyphs (visual characters) of a given font.
The separation of Font and Text allows more flexibility and better performances: indeed a Font is a heavy resource, and any operation on it is slow (often too slow for real-time applications). On the other side, a Text is a lightweight object which can combine the glyphs data and metrics of a Font to display any text on a render target.
It is important to note that the Text instance doesn't copy the font that it uses, it only keeps a reference to it. Thus, a Font must not be destructed while it is used by a Text (i.e. never write a function that uses a local Font instance for creating a text).
See also the note on coordinates and undistorted rendering in Transformable.
val window: RenderWindow = ???
// Declare and load a font
val font = Font()
font.loadFromFile("arial.ttf")
// Create a text
val text = Text("hello", font)
text.characterSize = 30;
text.fillColor = Color.Red()
// Draw it
window.draw(text)
Attributes
- See also
- Companion
- object
- Supertypes
Image living on the graphics card that can be used for drawing.
Image living on the graphics card that can be used for drawing.
Texture stores pixels that can be drawn, with a sprite for example.
A texture lives in the graphics card memory, therefore it is very fast to draw a texture to a render target, or copy a render target to a texture (the graphics card can access both directly).
Being stored in the graphics card memory has some drawbacks. A texture cannot be manipulated as freely as a Image, you need to prepare the pixels first and then upload them to the texture in a single operation (see update).
Since they live in the graphics card memory, the pixels of a texture cannot be accessed without a slow copy first. And they cannot be accessed individually. Therefore, if you need to read the texture's pixels (like for pixel-perfect collisions), it is recommended to store the collision information separately, for example in an array of booleans.
Like Image, Texture can handle a unique internal representation of pixels, which is RGBA 32 bits. This means that a pixel must be composed of 8 bits red, green, blue and alpha channels – just like a Color.
val window: RenderWindow = ???
val sprite: Sprite = ???
// This example shows the most common use of Texture: drawing a sprite
// Load a texture from a file
val texture = Texture()
if !(texture.loadFromFile("texture.png")) then
// error...
???
// Assign it to a sprite sf::Sprite sprite;
sprite.texture = texture
// Draw the textured sprite
window.draw(sprite)
Attributes
- See also
- Companion
- object
- Supertypes
-
class Objecttrait Matchableclass Any
Attributes
- Companion
- object
- Supertypes
-
class Objecttrait Matchableclass Any
Decomposed transform defined by a position, a rotation and a scale.
Decomposed transform defined by a position, a rotation and a scale.
This class is provided for convenience, on top of Transform.
Transform, as a low-level class, offers a great level of flexibility but it is not always convenient to manage. Indeed, one can easily combine any kind of operation, such as a translation followed by a rotation followed by a scaling, but once the result transform is built, there's no way to go backward and, let's say, change only the rotation without modifying the translation and scaling. The entire transform must be recomputed, which means that you need to retrieve the initial translation and scale factors as well, and combine them the same way you did before updating the rotation. This is a tedious operation, and it requires to store all the individual components of the final transform.
That's exactly what Transformable was written for: it hides these variables and the composed transform behind an easy to use interface. You can set or get any of the individual components without worrying about the others. It also provides the composed transform (as a Transform), and keeps it up-to-date.
In addition to the position, rotation and scale, Transformable provides an "origin" component, which represents the local origin of the three other components. Let's take an example with a 10x10 pixels sprite. By default, the sprite is positioned/rotated/scaled relatively to its top-left corner, because it is the local point (0, 0). But if we change the origin to be (5, 5), the sprite will be positioned/rotated/scaled around its center instead. And if we set the origin to (10, 10), it will be transformed around its bottom-right corner.
To keep the Transformable class simple, there's only one origin for all the components. You cannot position the sprite relatively to its top-left corner while rotating it around its center, for example. To do such things, use Transform directly.
Transformable can be used as a base class. It is often combined with Drawable – that's what SFML's sprites, texts and shapes do.
val window: RenderWindow = ???
class MyEntity extends Transformable with Drawable:
override def draw(target: RenderTarget, states: RenderStates): Unit =
states.transform *= transform
target.draw(???, states)
val entity = MyEntity()
entity.position = (10, 20)
entity.rotation = 45
window.draw(entity)
It can also be used as a member, if you don't want to use its API directly (because you don't need all its functions, or you have different naming conventions for example).
case class MyVector2(x: Float, y: Float)
class MyEntity:
private val myTransform = Transformable()
def position_=(v: MyVector2): Unit =
myTransform.position = (v.x, v.y)
def draw(target: RenderTarget): Unit =
target.draw(???, RenderStates(myTransform.transform))
A note on coordinates and undistorted rendering: By default, SFML (or more exactly, OpenGL) may interpolate drawable objects such as sprites or texts when rendering. While this allows transitions like slow movements or rotations to appear smoothly, it can lead to unwanted results in some cases, for example blurred or distorted objects. In order to render a Drawable object pixel-perfectly, make sure the involved coordinates allow a 1:1 mapping of pixels in the window to texels (pixels in the texture). More specifically, this means:
- The object's position, origin and scale have no fractional part
- The object's and the view's rotation are a multiple of 90 degrees
- The view's center and size have no fractional part
Attributes
- See also
- Companion
- object
- Supertypes
-
class Objecttrait Matchableclass Any
- Known subtypes
Attributes
- Companion
- trait
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
Transformable.type
Attributes
- Supertypes
-
class Objecttrait Matchableclass Any
- Self type
-
VertexArray.type
2D camera that defines what region is shown on screen
2D camera that defines what region is shown on screen
View defines a camera in the 2D scene.
This is a very powerful concept: you can scroll, rotate or zoom the entire scene without altering the way that your drawable objects are drawn.
A view is composed of a source rectangle, which defines what part of the 2D scene is shown, and a target viewport, which defines where the contents of the source rectangle will be displayed on the render target (window or texture).
The viewport allows to map the scene to a custom part of the render target, and can be used for split-screen or for displaying a minimap, for example. If the source rectangle doesn't have the same size as the viewport, its contents will be stretched to fit in.
To apply a view, you have to assign it to the render target. Then, objects drawn in this render target will be affected by the view until you use another view.
val window: RenderWindow = ???
val view: View = ???
val someSprite: Sprite = ???
val someText: Text = ???
// Initialize the view to a rectangle located at (100, 100) and with a size of 400x200
view.reset((100, 100, 400, 200))
// Rotate it by 45 degrees
view.rotate(45)
// Set its target viewport to be half of the window
view.viewport = (0f, 0f, 0.5f, 1f)
// Apply it
window.view = view
// Render stuff
window.draw(someSprite)
// Set the default view back
window.view = window.defaultView
// Render stuff not affected by the view
window.draw(someText)
See also the note on coordinates and undistorted rendering in Transformable.
Attributes
- See also
- Companion
- object
- Supertypes
-
class Objecttrait Matchableclass Any