This commit is contained in:
Page Asgardius 2024-10-23 09:41:33 -07:00
parent 6faa7bf05d
commit 95934d1c1c
3622 changed files with 9989830 additions and 0 deletions

View file

@ -0,0 +1,235 @@
.. _doc_2d_skeletons:
2D skeletons
============
Introduction
------------
When working with 3D, skeletal deforms are common for characters and creatures
and most 3D modelling applications support it. For 2D, as this function is not
used as often, it's difficult to find mainstream software aimed for this.
One option is to create animations in third-party software such as Spine or
Dragonbones. From Godot 3.1 onwards, though, this functionality is supported
built-in.
Why would you want to do skeletal animations directly in Godot? The answer is
that there are many advantages to it:
* Better integration with the engine, so less hassle importing and editing from
an external tool.
* Ability to control particle systems, shaders, sounds, call scripts, colors,
transparency, etc. in animations.
* The built-in skeletal system in Godot is very efficient and designed for
performance.
The following tutorial will, then, explain 2D skeletal deformations.
Setup
-----
.. seealso::
Before starting, we recommend you to go through the
:ref:`doc_cutout_animation` tutorial to gain a general understanding of
animating within Godot.
For this tutorial, we will be using a single image to construct our character.
Download it from :download:`gBot_pieces.png <img/gBot_pieces.png>` or save the
image below.
.. image:: img/gBot_pieces.png
It is also advised to download the final character image
:download:`gBot_complete.png <img/gBot_complete.png>` to have a good reference
for putting the different pieces together.
.. image:: img/gBot_complete.png
Creating the polygons
---------------------
Create a new scene for your model (if it's going to be an animated character,
you may want to use a ``KinematicBody2D``). For ease of use, an empty 2D node is
created as a root for the polygons.
Begin with a ``Polygon2D`` node. There is no need to place it anywhere in the
scene for now, so simply create it like this:
.. image:: img/skel2d1.png
Select it and assign the texture with the character pieces you have downloaded
before:
.. image:: img/skel2d2.png
Drawing a polygon directly is not advised. Instead, open the "UV" dialog for the
polygon:
.. image:: img/skel2d3.png
Head over to the *Points* mode, select the pencil and draw a polygon around the
desired piece:
.. image:: img/skel2d4.png
Duplicate the polygon node and give it a proper name. Then, enter the "UV"
dialog again and replace the old polygon with another one in the new desired
piece.
When you duplicate nodes and the next piece has a similar shape, you can edit
the previous polygon instead of drawing a new one.
After moving the polygon, remember to update the UV by selecting Edit -> "Polygon
-> UV" in the Polygon 2D UV Editor.
.. image:: img/skel2d5.png
Keep doing this until you mapped all pieces.
.. image:: img/skel2d6.png
You will notice that pieces for nodes appear in the same layout as they do in
the original texture. This is because by default, when you draw a polygon, the
UV and points are the same.
Rearrange the pieces and build the character. This should be pretty quick. There
is no need to change pivots, so don't bother making sure rotation pivots for
each piece are right; you can leave them be for now.
.. image:: img/skel2d7.png
Ah, the visual order of the pieces is not correct yet, as some are covering
wrong pieces. Rearrange the order of the nodes to fix this:
.. image:: img/skel2d8.png
And there you go! It was definitely much easier than in the cutout tutorial.
Creating the skeleton
---------------------
Create a ``Skeleton2D`` node as a child of the root node. This will be the base
of our skeleton:
.. image:: img/skel2d9.png
Create a ``Bone2D`` node as a child of the skeleton. Put it on the hip (usually
skeletons start here). The bone will be pointing to the right, but you can
ignore this for now.
.. image:: img/skel2d10.png
Keep creating bones in hierarchy and naming them accordingly.
.. image:: img/skel2d11.png
At the end of this chain, there will be a *jaw* node. It is, again, very short
and pointing to the right. This is normal for bones without children. The length
of *tip* bones can be changed with a property in the inspector:
.. image:: img/skel2d12.png
In this case, we don't need to rotate the bone (coincidentally the jaw points
right in the sprite), but in case you need to, feel free to do it. Again, this
is only really needed for tip bones as nodes with children don't usually need a
length or a specific rotation.
Keep going and build the whole skeleton:
.. image:: img/skel2d13.png
You will notice that all bones raise an annoying warning about a missing rest
pose. This means that it's time to set one. Go to the *skeleton* node and create
a rest pose. This pose is the default one, you can come back to it anytime you
want (which is very handy for animating):
.. image:: img/skel2d14.png
The warnings will go away. If you modify the skeleton (add/remove bones) you
will need to set the rest pose again.
Deforming the polygons
----------------------
Select the previously created polygons and assign the skeleton node to their
``Skeleton`` property. This will ensure that they can eventually be deformed by
it.
.. image:: img/skel2d15.png
Click the property highlighted above and select the skeleton node:
.. image:: img/skel2d16.png
Again, open the UV editor for the polygon and go to the *Bones* section.
.. image:: img/skel2d17.png
You will not be able to paint weights yet. For this you need to synchronize the
list of bones from the skeleton with the polygon. This step is done only once
and manually (unless you modify the skeleton by adding/removing/renaming bones).
It ensures that your rigging information is kept in the polygon, even if a
skeleton node is accidentally lost or the skeleton modified. Push the "Sync
Bones to Polygon" button to sync the list.
.. image:: img/skel2d18.png
The list of bones will automatically appear. By default, your polygon has no
weight assigned to any of them. Select the bones you want to assign weight to
and paint them:
.. image:: img/skel2d19.png
Points in white have a full weight assigned, while points in black are not
influenced by the bone. If the same point is painted white for multiple bones,
the influence will be distributed amongst them (so usually there is not that
much need to use shades in-between unless you want to polish the bending
effect).
.. image:: img/skel2d20.gif
After painting the weights, animating the bones (NOT the polygons!) will have
the desired effect of modifying and bending the polygons accordingly. As you
only need to animate bones in this approach, work becomes much easier!
But it's not all roses. Trying to animate bones that bend the polygon will often
yield unexpected results:
.. image:: img/skel2d21.gif
This happens because Godot generates internal triangles that connect the points
when drawing the polygon. They don't always bend the way you would expect. To
solve this, you need to set hints in the geometry to clarify how you expect it
to deform.
Internal vertices
-----------------
Open the UV menu for each bone again and go to the *Points* section. Add some
internal vertices in the regions where you expect the geometry to bend:
.. image:: img/skel2d22.png
Now, go to the *Polygon* section and redraw your own polygons with more detail.
Imagine that, as your polygons bend, you need to make sure they deform the least
possible, so experiment a bit to find the right setup.
.. image:: img/skel2d23.png
Once you start drawing, the original polygon will disappear and you will be free
to create your own:
.. image:: img/skel2d24.png
This amount of detail is usually fine, though you may want to have more
fine-grained control over where triangles go. Experiment by yourself until you
get the results you like.
**Note:** Don't forget that your newly added internal vertices also need weight
painting! Go to the *Bones* section again to assign them to the right bones.
Once you are all set, you will get much better results:
.. image:: img/skel2d25.gif

View file

@ -0,0 +1,292 @@
.. _doc_animation_tree:
Using AnimationTree
===================
Introduction
------------
With :ref:`AnimationPlayer <class_AnimationPlayer>`, Godot has one of the most flexible animation systems that you can find in any game engine.
The ability to animate almost any property in any node or resource, as well as having dedicated transform, bezier,
function calling, audio and sub-animation tracks, is pretty much unique.
However, the support for blending those animations via ``AnimationPlayer`` is relatively limited, as only a fixed cross-fade transition time can be set.
:ref:`AnimationTree <class_AnimationTree>` is a new node introduced in Godot 3.1 to deal with advanced transitions.
It supersedes the ancient ``AnimationTreePlayer``, while adding a huge amount of features and flexibility.
Creating an AnimationTree
-------------------------
Before starting, it must be made clear that an ``AnimationTree`` node does not contain its own animations.
Instead, it uses animations contained in an ``AnimationPlayer`` node. This way, you can edit your animations (or import them from a 3D scene)
as usual and then use this extra node to control the playback.
The most common way to use ``AnimationTree`` is in a 3D scene. When importing your scenes from a 3D exchange format, they will usually come
with animations built-in (either multiple ones or split from a large one on import).
At the end, the imported Godot scene will contain the animations in a ``AnimationPlayer`` node.
As you rarely use imported scenes directly in Godot (they are either instantiated or inherited from), you can place the ``AnimationTree`` node in your
new scene which contains the imported one. Afterwards, point the ``AnimationTree`` node to the ``AnimationPlayer`` that was created in the imported scene.
This is how it's done in the `Third Person Shooter demo <https://github.com/godotengine/tps-demo>`_, for reference:
.. image:: img/animtree1.png
A new scene was created for the player with a ``KinematicBody`` as root. Inside this scene, the original ``.dae`` (Collada) file was instantiated
and an ``AnimationTree`` node was created.
Creating a tree
---------------
There are three main types of nodes that can be used in ``AnimationTree``:
1. Animation nodes, which reference an animation from the linked ``AnimationTree``.
2. Animation Root nodes, which are used to blend sub-nodes.
3. Animation Blend nodes, which are used within ``AnimationNodeBlendTree`` as single-graph blending via multiple input ports.
To set a root node in ``AnimationTree``, a few types are available:
.. image:: img/animtree2.png
* ``AnimationNodeAnimation``: Selects an animation from the list and plays it. This is the simplest root node, and generally not used directly as root.
* ``AnimationNodeBlendTree``: Contains many *blend* type nodes, such as mix, blend2, blend3, one shot, etc. This is one of the most commonly used roots.
* ``AnimationNodeStateMachine``: Contains multiple root nodes as children in a graph. Each node is used as a *state*, and provides multiple functions to alternate between states.
* ``AnimationNodeBlendSpace2D``: Allows placing root nodes in a 2D blend space. Control the blend position in 2D to mix between multiple animations.
* ``AnimationNodeBlendSpace1D``: Simplified version of the above (1D).
Blend tree
----------
An ``AnimationNodeBlendTree`` can contain both root and regular nodes used for blending. Nodes are added to the graph from a menu:
.. image:: img/animtree3.png
All blend trees contain an ``Output`` node by default, and something has to be connected to it in order for animations to play.
The easiest way to test this functionality is to connect an ``Animation`` node to it directly:
.. image:: img/animtree4.png
This will simply play back the animation. Make sure that the ``AnimationTree`` is active for something to actually happen.
Following is a short description of available nodes:
Blend2 / Blend3
^^^^^^^^^^^^^^^
These nodes will blend between two or three inputs by a user-specified blend value:
.. image:: img/animtree5.gif
For more complex blending, it is advised to use blend spaces instead.
Blending can also use filters, i.e. you can control individually which tracks go through the blend function.
This is very useful for layering animations on top of each other.
.. image:: img/animtree6.png
OneShot
^^^^^^^
This node will execute a sub-animation and return once it finishes. Blend times for fading in and out can be customized, as well as filters.
.. image:: img/animtree6b.gif
Seek
^^^^
This node can be used to cause a seek command to happen to any sub-children of the animation graph. Use this node type to play an ``Animation`` from the start or a certain playback position inside the ``AnimationNodeBlendTree``.
After setting the time and changing the animation playback, the seek node automatically goes into sleep mode on the next process frame by setting its ``seek_position`` value to ``-1.0``.
.. tabs::
.. code-tab:: gdscript GDScript
# Play child animation from the start.
anim_tree.set("parameters/Seek/seek_position", 0.0)
# Alternative syntax (same result as above).
anim_tree["parameters/Seek/seek_position"] = 0.0
# Play child animation from 12 second timestamp.
anim_tree.set("parameters/Seek/seek_position", 12.0)
# Alternative syntax (same result as above).
anim_tree["parameters/Seek/seek_position"] = 12.0
.. code-tab:: csharp
// Play child animation from the start.
animTree.Set("parameters/Seek/seek_position", 0.0);
// Play child animation from 12 second timestamp.
animTree.Set("parameters/Seek/seek_position", 12.0);
TimeScale
^^^^^^^^^
Allows scaling the speed of the animation (or reverse it) in any children nodes. Setting it to 0 will pause the animation.
Transition
^^^^^^^^^^
Very simple state machine (when you don't want to cope with a ``StateMachine`` node). Animations can be connected to the outputs and transition times can be specified.
BlendSpace2D
^^^^^^^^^^^^
``BlendSpace2D`` is a node to do advanced blending in two dimensions. Points are added to a two-dimensional space and then a position
can be controlled to determine blending:
.. image:: img/animtree7.gif
The ranges in X and Y can be controlled (and labeled for convenience). By default, points can be placed anywhere (just right-click on
the coordinate system or use the *add point* button) and triangles will be generated automatically using Delaunay.
.. image:: img/animtree8.gif
It is also possible to draw the triangles manually by disabling the *auto triangle* option, though this is rarely necessary:
.. image:: img/animtree9.png
Finally, it is possible to change the blend mode. By default, blending happens by interpolating points inside the closest triangle.
When dealing with 2D animations (frame by frame), you may want to switch to *Discrete* mode.
Alternatively, if you want to keep the current play position when switching between discrete animations, there is a *Carry* mode.
This mode can be changed in the *Blend* menu:
.. image:: img/animtree10.png
BlendSpace1D
^^^^^^^^^^^^
This is similar to 2D blend spaces, but in one dimension (so triangles are not needed).
StateMachine
^^^^^^^^^^^^
This node acts as a state machine with root nodes as states. Root nodes can be created and connected via lines. States are connected via *Transitions*,
which are connections with special properties. Transitions are uni-directional, but two can be used to connect in both directions.
.. image:: img/animtree11.gif
There are many types of transition:
.. image:: img/animtree12.png
* *Immediate*: Will switch to the next state immediately. The current state will end and blend into the beginning of the new one.
* *Sync*: Will switch to the next state immediately, but will seek the new state to the playback position of the old state.
* *At End*: Will wait for the current state playback to end, then switch to the beginning of the next state animation.
Transitions also have a few properties. Click any transition and it will be displayed in the inspector dock:
.. image:: img/animtree13.png
* *Switch Mode* is the transition type (see above), it can be modified after creation here.
* *Auto Advance* will turn on the transition automatically when this state is reached. This works best with the *At End* switch mode.
* *Advance Condition* will turn on auto advance when this condition is set. This is a custom text field that can be filled with a variable name.
The variable can be modified from code (more on this later).
* *Xfade Time* is the time to cross-fade between this state and the next.
* *Priority* is used together with the ``travel()`` function from code (more on this later). Lower priority transitions are preferred when travelling through the tree.
* *Disabled* toggles disabling this transition (when disabled, it will not be used during travel or auto advance).
Root motion
-----------
When working with 3D animations, a popular technique is for animators to use the root skeleton bone to give motion to the rest of the skeleton.
This allows animating characters in a way where steps actually match the floor below. It also allows precise interaction with objects during cinematics.
When playing back the animation in Godot, it is possible to select this bone as the *root motion track*. Doing so will cancel the bone
transformation visually (the animation will stay in place).
.. image:: img/animtree14.png
Afterwards, the actual motion can be retrieved via the :ref:`AnimationTree <class_AnimationTree>` API as a transform:
.. tabs::
.. code-tab:: gdscript GDScript
anim_tree.get_root_motion_transform()
.. code-tab:: csharp
animTree.GetRootMotionTransform();
This can be fed to functions such as :ref:`KinematicBody.move_and_slide <class_KinematicBody_method_move_and_slide>` to control the character movement.
There is also a tool node, ``RootMotionView``, that can be placed in a scene and will act as a custom floor for your
character and animations (this node is disabled by default during the game).
.. image:: img/animtree15.gif
Controlling from code
---------------------
After building the tree and previewing it, the only question remaining is "How is all this controlled from code?".
Keep in mind that the animation nodes are just resources and, as such, they are shared between all instances using them.
Setting values in the nodes directly will affect all instances of the scene that uses this ``AnimationTree``.
This is generally undesirable, but does have some cool use cases, e.g. you can copy and paste parts of your animation tree,
or reuse nodes with a complex layout (such as a state machine or blend space) in different animation trees.
The actual animation data is contained in the ``AnimationTree`` node and is accessed via properties.
Check the "Parameters" section of the ``AnimationTree`` node to see all the parameters that can be modified in real-time:
.. image:: img/animtree16.png
This is handy because it makes it possible to animate them from an ``AnimationPlayer``, or even the ``AnimationTree`` itself,
allowing the realization of very complex animation logic.
To modify these values from code, the property path must be obtained. This is done easily by hovering the mouse over any of the parameters:
.. image:: img/animtree17.png
Which allows setting them or reading them:
.. tabs::
.. code-tab:: gdscript GDScript
anim_tree.set("parameters/eye_blend/blend_amount", 1.0)
# Simpler alternative form:
anim_tree["parameters/eye_blend/blend_amount"] = 1.0
.. code-tab:: csharp
animTree.Set("parameters/eye_blend/blend_amount", 1.0);
State machine travel
--------------------
One of the nice features in Godot's ``StateMachine`` implementation is the ability to travel. The graph can be instructed to go from the
current state to another one, while visiting all the intermediate ones. This is done via the A\* algorithm.
In the absence of any viable set of transitions starting at the current state and finishing at the destination state, the graph teleports
to the destination state.
To use the travel ability, you should first retrieve the :ref:`AnimationNodeStateMachinePlayback <class_AnimationNodeStateMachinePlayback>`
object from the ``AnimationTree`` node (it is exported as a property).
.. tabs::
.. code-tab:: gdscript GDScript
var state_machine = anim_tree["parameters/playback"]
.. code-tab:: csharp
AnimationNodeStateMachinePlayback stateMachine = (AnimationNodeStateMachinePlayback)animTree.Get("parameters/playback");
Once retrieved, it can be used by calling one of the many functions it offers:
.. tabs::
.. code-tab:: gdscript GDScript
state_machine.travel("SomeState")
.. code-tab:: csharp
stateMachine.Travel("SomeState");
The state machine must be running before you can travel. Make sure to either call ``start()`` or choose a node to **Autoplay on Load**.
.. image:: img/animtree18.png

View file

@ -0,0 +1,371 @@
.. _doc_cutout_animation:
Cutout animation
================
What is it?
~~~~~~~~~~~
Traditionally, `cutout animation <https://en.wikipedia.org/wiki/Cutout_animation>`__
is a type of `stop motion animation <https://en.wikipedia.org/wiki/Stop_motion>`__
in which pieces of paper (or other thin material) are cut into special shapes
and arranged in two-dimensional representations of characters and objects.
Characters' bodies are usually made out of several pieces. The pieces are
arranged and photographed once for each frame of the film. The animator moves
and rotates the parts in small increments between each shot to create the
illusion of movement when the images are played back quickly in sequence.
Simulations of cutout animation can now be created using software as seen in
`South Park <https://en.wikipedia.org/wiki/South_Park>`__ and `Jake and the Never
Land Pirates <https://en.wikipedia.org/wiki/Jake_and_the_Never_Land_Pirates>`__.
In video games, this technique has also become popular. Examples of
this are `Paper Mario <https://en.wikipedia.org/wiki/Super_Paper_Mario>`__ or
`Rayman Origins <https://en.wikipedia.org/wiki/Rayman_Origins>`__ .
Cutout animation in Godot
~~~~~~~~~~~~~~~~~~~~~~~~~
Godot provides tools for working with cutout rigs, and is ideal for the workflow:
- **The animation system is fully integrated with the engine**: This
means animations can control much more than just motion of objects. Textures,
sprite sizes, pivots, opacity, color modulation, and more, can all be animated
and blended.
- **Combine animation styles**: AnimatedSprite allows traditional cel animation
to be used alongside cutout animation. In cel animation different animation
frames use entirely different drawings rather than the same pieces positioned
differently. In an otherwise cutout-based animation, cel animation can be used
selectively for complex parts such as hands, feet, changing facial expressions,
etc.
- **Custom Shaped Elements**: Custom shapes can be created with
:ref:`Polygon2D <class_Polygon2D>`
allowing UV animation, deformations, etc.
- **Particle Systems**: A cutout animation rig can be combined with particle
systems. This can be useful for magic effects, jetpacks, etc.
- **Custom Colliders**: Set colliders and influence areas in different
parts of the skeletons, great for bosses and fighting games.
- **Animation Tree**: Allows complex combinations and blending between
several animations, the same way it works in 3D.
And much more!
Making of GBot
~~~~~~~~~~~~~~
For this tutorial, we will use as demo content the pieces of the
`GBot <https://www.youtube.com/watch?v=S13FrWuBMx4&list=UUckpus81gNin1aV8WSffRKw>`__
character, created by Andreas Esau.
.. image:: img/tuto_cutout_walk.gif
Get your assets: :download:`gbot_resources.zip <files/gbot_resources.zip>`.
Setting up the rig
~~~~~~~~~~~~~~~~~~
Create an empty Node2D as root of the scene, we will work under it:
.. image:: img/tuto_cutout1.png
The first node of the model is the hip.
Generally, both in 2D and 3D, the hip is the root of the skeleton. This
makes it easier to animate:
.. image:: img/tuto_cutout2.png
Next will be the torso. The torso needs to be a child of the hip, so
create a child sprite and load the torso texture, later accommodate it properly:
.. image:: img/tuto_cutout3.png
This looks good. Let's see if our hierarchy works as a skeleton by
rotating the torso. We can do this be pressing :kbd:`E` to enter rotate mode,
and dragging with the left mouse button. To exit rotate mode hit :kbd:`ESC`.
.. image:: img/tutovec_torso1.gif
The rotation pivot is wrong and needs to be adjusted.
This small cross in the middle of the :ref:`Sprite <class_Sprite>` is
the rotation pivot:
.. image:: img/tuto_cutout4.png
Adjusting the pivot
~~~~~~~~~~~~~~~~~~~
The pivot can be adjusted by changing the *offset* property in the
Sprite:
.. image:: img/tuto_cutout5.png
The pivot can also be adjusted *visually*. While hovering over the
desired pivot point, press :kbd:`V` to move the pivot there for the
selected Sprite. There is also a tool in the tool bar that has a
similar function.
.. image:: img/tutovec_torso2.gif
Continue adding body pieces, starting with the
right arm. Make sure to put each sprite in its correct place in the hierarchy,
so its rotations and translations are relative to its parent:
.. image:: img/tuto_cutout6.png
With the left arm there's a problem. In 2D, child nodes appear in front of
their parents:
.. image:: img/tuto_cutout7.png
We want the left arm to appear *behind*
the hip and the torso. We could move the left arm nodes behind the hip (above
the hip node in the scene hierarchy), but then the left arm is no longer in its
proper place in the hierarchy. This means it wouldn't be affected by the movement
of the torso. We'll fix this problem with ``RemoteTransform2D`` nodes.
.. note:: You can also fix depth ordering problems by adjusting the Z property
of any node inheriting from Node2D.
RemoteTransform2D node
~~~~~~~~~~~~~~~~~~~~~~
The :ref:`RemoteTransform2D <class_RemoteTransform2D>` node transforms nodes
somewhere else in the hierarchy. This node applies its own transform (including
any transformation it inherits from its parents) to the remote node it targets.
This allows us to correct the visibility order of our elements, independently of
the locations of those parts in the cutout hierarchy.
Create a ``RemoteTransform2D`` node as a child of the torso. Call it ``remote_arm_l``.
Create another RemoteTransform2D node inside the first and call it ``remote_hand_l``.
Use the ``Remote Path`` property of the two new nodes to target the ``arm_l`` and
``hand_l`` sprites respectively:
.. image:: img/tuto_cutout9.png
Moving the ``RemoteTransform2D`` nodes now moves the sprites. So we can create
animations by adjusting the ``RemoteTransform2D`` transforms:
.. image:: img/tutovec_torso4.gif
Completing the skeleton
~~~~~~~~~~~~~~~~~~~~~~~
Complete the skeleton by following the same steps for the rest of the
parts. The resulting scene should look similar to this:
.. image:: img/tuto_cutout10.png
The resulting rig will be easy to animate. By selecting the nodes and
rotating them you can animate forward kinematics (FK) efficiently.
For simple objects and rigs this is fine, but there are limitations:
- Selecting sprites in the main viewport can become difficult in complex rigs.
The scene tree ends up being used to select parts instead, which can be slower.
- Inverse Kinematics (IK) is useful for animating extremities like hands and
feet, and can't be used with our rig in its current state.
To solve these problems we'll use Godot's skeletons.
Skeletons
~~~~~~~~~
In Godot there is a helper to create "bones" between nodes. The bone-linked
nodes are called skeletons.
As an example, let's turn the right arm into a skeleton. To create
a skeleton, a chain of nodes must be selected from top to bottom:
.. image:: img/tuto_cutout11.png
Then, click on the Skeleton menu and select ``Make Bones``.
.. image:: img/tuto_cutout12.png
This will add bones covering the arm, but the result may be surprising.
.. image:: img/tuto_cutout13.png
Why does the hand lack a bone? In Godot, a bone connects a
node with its parent. And there's currently no child of the hand node.
With this knowledge let's try again.
The first step is creating an endpoint node. Any kind of node will do,
but :ref:`Position2D <class_Position2D>` is preferred because it's
visible in the editor. The endpoint node will ensure that the last bone
has orientation.
.. image:: img/tuto_cutout14.png
Now select the whole chain, from the endpoint to the arm and create
bones:
.. image:: img/tuto_cutout15.png
The result resembles a skeleton a lot more, and now the arm and forearm
can be selected and animated.
Create endpoints for all important extremities. Generate bones for all
articulable parts of the cutout, with the hip as the ultimate connection
between all of them.
You may notice that an extra bone is created when connecting the hip and torso.
Godot has connected the hip node to the scene root with a bone, and we don't
want that. To fix this, select the root and hip node, open the Skeleton menu,
click ``clear bones``.
.. image:: img/tuto_cutout15_2.png
Your final skeleton should look something like this:
.. image:: img/tuto_cutout16.png
You might have noticed a second set of endpoints in the hands. This will make
sense soon.
Now that the whole figure is rigged, the next step is setting up the IK
chains. IK chains allow for more natural control of extremities.
IK chains
~~~~~~~~~
IK stands for inverse kinematics. It's a convenient technique for animating the
position of hands, feet and other extremities of rigs like the one we've made.
Imagine you want to pose a character's foot in a specific position on the ground.
Without IK chains, each motion of the foot would require rotating and positioning
several other bones (the shin and the thigh at least). This would be quite
complex and lead to imprecise results.
IK allows us to move directly the foot while the shin and thigh self-adjust.
To create an IK chain, select a chain of bones from endpoint to
the base for the chain. For example, to create an IK chain for the right
leg, select the following:
.. image:: img/tuto_cutout17.png
Then enable this chain for IK. Go to Edit > Make IK Chain.
.. image:: img/tuto_cutout18.png
As a result, the base of the chain will turn *Yellow*.
.. image:: img/tuto_cutout19.png
Once the IK chain is set-up grab any child or grand-child of the base of the
chain (e.g. a foot) and move it. You'll see the rest of the chain adjust as you
adjust its position.
.. image:: img/tutovec_torso5.gif
Animation tips
~~~~~~~~~~~~~~
The following section will be a collection of tips for creating animation for
your cutout rigs. For more information on how the animation system in Godot
works, see :ref:`doc_introduction_animation`.
Setting keyframes and excluding properties
------------------------------------------
Special contextual elements appear in the top toolbar when the animation editor
window is open:
.. image:: img/tuto_cutout20.png
The key button inserts location, rotation, and scale keyframes for the
selected objects or bones at the current playhead position.
The "loc", "rot", and "scl" toggle buttons to the left of the key button modify
its function, allowing you to specify which of the three properties keyframes
will be created for.
Here's an illustration of how this can be useful: Imagine you have a node which
already has two keyframes animating its scale only. You want to add an
overlapping rotation movement to the same node. The rotation movement should
begin and end at different times from the scale change that's already set up.
You can use the toggle buttons to have only rotation information added when you
add a new keyframe. This way, you can avoid adding unwanted scale keyframes
which would disrupt the existing scale animation.
Creating a rest pose
~~~~~~~~~~~~~~~~~~~~
Think of a rest pose as a default pose that your cutout rig should be set to
when no other pose is active in your game. Create a rest pose as follows:
1. Make sure the rig parts are positioned in what looks like a "resting"
arrangement.
2. Create a new animation, rename it "rest".
3. Select all nodes in your rig (box selection should work fine).
4. Make sure the "loc", "rot", and "scl" toggle buttons are all active in the
toolbar.
5. Press the key button. Keys will be inserted for all selected parts storing
their current arrangement. This pose can now be recalled when necessary in
your game by playing the "rest" animation you've created.
.. image:: img/tuto_cutout21.png
Modifying rotation only
~~~~~~~~~~~~~~~~~~~~~~~
When animating a cutout rig, often it's only the rotation of the nodes that
needs to change.
Location and scale are rarely used.
So when inserting keys, you might find it convenient to have only the "rot"
toggle active most of the time:
.. image:: img/tuto_cutout22.png
This will avoid the creation of unwanted animation tracks for position
and scale.
Keyframing IK chains
~~~~~~~~~~~~~~~~~~~~
When editing IK chains, it's not necessary to select the whole chain to
add keyframes. Selecting the endpoint of the chain and inserting a
keyframe will automatically insert keyframes for all other parts of the chain too.
Visually move a sprite behind its parent
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sometimes it is necessary to have a node change its visual depth relative to
its parent node during an animation. Think of a character facing the camera,
who pulls something out from behind his back and holds it out in front of him.
During this animation the whole arm and the object in his hand would need to
change their visual depth relative to the body of the character.
To help with this there's a keyframable "Behind Parent" property on all
Node2D-inheriting nodes. When planning your rig, think about the movements it
will need to perform and give some thought to how you'll use "Behind Parent"
and/or RemoteTransform2D nodes. They provide overlapping functionality.
.. image:: img/tuto_cutout23.png
Setting easing curves for multiple keys
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To apply the same easing curve to multiple keyframes at once:
1. Select the relevant keys.
2. Click on the pencil icon in the bottom right of the animation panel. This
will open the transition editor.
3. In the transition editor, click on the desired curve to apply it.
.. image:: img/tuto_cutout24.png
2D Skeletal deform
~~~~~~~~~~~~~~~~~~
Skeletal deform can be used to augment a cutout rig, allowing single pieces to
deform organically (e.g. antennae that wobble as an insect character walks).
This process is described in a :ref:`separate tutorial <doc_2d_skeletons>`.

View file

@ -0,0 +1,12 @@
Animation
=========
.. toctree::
:maxdepth: 1
:name: toc-learn-features-animation
introduction
cutout_animation
2d_skeletons
animation_tree
playing_videos

View file

@ -0,0 +1,409 @@
.. _doc_introduction_animation:
Introduction to the animation features
======================================
The :ref:`class_AnimationPlayer` node allows you to create anything
from simple to complex animations.
In this guide you learn to:
- Work with the Animation Panel
- Animate any property of any node
- Create a simple animation
- Call functions with the powerful Call Function Tracks
In Godot, you can animate anything available in the Inspector, such as
Node transforms, sprites, UI elements, particles, visibility and color
of materials, and so on. You can also modify values of script variables
and call any function.
Create an AnimationPlayer node
------------------------------
To use the animation tools we first have to create an
:ref:`class_AnimationPlayer` node.
The AnimationPlayer node type is the data container for your animations.
One AnimationPlayer node can hold multiple animations, that can
automatically transition to one another.
.. figure:: img/animation_create_animationplayer.png
:alt: The AnimationPlayer node
The AnimationPlayer node
After creating one click on the AnimationPlayer node in the Node tab to
open the Animation Panel at the bottom of the viewport.
.. figure:: img/animation_animation_panel.png
:alt: The animation panel position
The animation panel position
It consists of four parts:
.. figure:: img/animation_animation_panel_overview.png
:alt: The animation panel
The animation panel
- Animation controls (i.e. add, load, save, and delete animations)
- The tracks listing
- The timeline with keyframes
- The timeline and track controls, where you can zoom the timeline and
edit tracks for example.
Computer animation relies on keyframes
--------------------------------------
A keyframe defines the value of a property at a certain point in time.
Diamond shapes represent keyframes in the timeline. A line between two
keyframes indicates that the value hasn't changed.
.. figure:: img/animation_keyframes.png
:alt: Keyframes in Godot
Keyframes in Godot
The engine interpolates values between keyframes, resulting in a gradual
change in values over time.
.. figure:: img/animation_illustration.png
:alt: Two keyframes are all it takes to obtain a smooth motion
Two keyframes are all it takes to obtain a smooth motion
The timeline lets you insert keyframes and change their timing. It also
defines how long the animation is.
.. figure:: img/animation_timeline.png
:alt: The timeline in the animation panel
The timeline in the animation panel
Each line of the Animation Panel is an animation track. Normal and
Transform tracks reference node properties. Their name or id is a path
to the node and the affected property.
.. figure:: img/animation_normal_track.png
:alt: Example of Normal animation tracks
Example of Normal animation tracks
.. tip::
If you animate the wrong property, you can edit a track's path anytime.
Double click on it and type the new path. Play the animation using the
"Play from beginning" button |Play from beginning| (or pressing
:kbd:`Shift + D` on keyboard) to see the changes instantly.
Tutorial: Creating a simple animation
-------------------------------------
Scene setup
~~~~~~~~~~~
For this tutorial, we'll create a Sprite node with an AnimationPlayer as
its child. We will animate the sprite to move between two points on the screen.
.. figure:: img/animation_animation_player_tree.png
:alt: Our scene setup
Our scene setup
.. warning::
AnimationPlayer inherits from Node instead of Node2D or Spatial, which means
that the child nodes will not inherit the transform from the parent nodes
due to a bare Node being present in the hierarchy.
Therefore, it is not recommended to add nodes that have a 2D/3D transform
as a child of an AnimationPlayer node.
The sprite holds an image texture. We animate that sprite to move
between two points on the screen. For this tutorial, use the default Godot
icon as the sprite's texture. As a starting point, move the sprite
to a left position on the screen.
Select the AnimationPlayer node, then click the "Animation" button in the
animation editor. From the list select "New" (|Add
Animation|) to add a new animation. And Enter a name for the animation in the
dialog box.
.. figure:: img/animation_create_new_animation.png
:alt: Add a new animation
Add a new animation
Adding a track
~~~~~~~~~~~~~~
To add a new track for our sprite, select it and take a look in the
toolbar:
.. figure:: img/animation_convenience_buttons.png
:alt: Convenience buttons
Convenience buttons
These switches and buttons allow you to add keyframes for the selected
node's location, rotation, and scale respectively.
Deselect rotation, because we are only interested in the location of our
sprite for this tutorial and click on the key button.
As we don't have a track already set up for the transform/location
property, Godot asks whether it should set it up for us. Click **Create**.
This creates a new track and our first keyframe at the beginning of
the timeline:
.. figure:: img/animation_track.png
:alt: The sprite track
The sprite track
The second keyframe
~~~~~~~~~~~~~~~~~~~
Now we need to set the destination where our sprite should be headed and
how much time it takes to get there.
Let's say, we want it to take 2 seconds to go to the other point. By
default the animation is set to last only 1 second, so change this in
the timeline controls in animation panel's lower panel to 2.
.. figure:: img/animation_set_length.png
:alt: Animation length
Animation length
Click on the timeline header near the 2-second mark and move the sprite
to the target destination on the right side.
Again, click the key button in the toolbar. This creates our second
keyframe.
Run the animation
~~~~~~~~~~~~~~~~~
Click on the "Play from beginning" (|Play from beginning|) button.
Yay! Our animation runs:
.. figure:: img/animation_simple.gif
:alt: The animation
The animation
Back and forth
~~~~~~~~~~~~~~
Godot has an additional feature here. Like said before,
Godot always calculates the frames between two keyframes. In a loop, the
first keyframe is also the last keyframe, if no keyframe is specified at
the end.
.. figure:: img/animation_loop.png
:alt: Animation loop
Animation loop
If you set the animation length to 4 seconds now, the animation moves
back and forth. You can change this behavior if you change the track's
loop mode. This is covered in the next chapter.
Track settings
~~~~~~~~~~~~~~
Each track has a settings panel at the end, where you can set the update
mode, the track interpolation, and the loop mode.
.. figure:: img/animation_track_settings.png
:alt: Track settings
Track settings
The update mode of a track tells Godot when to update the property
values. This can be:
- **Continuous:** Update the property on each frame.
- **Discrete:** Only update the property on keyframes.
- **Trigger:** Only update the property on keyframes or triggers.
Triggers are a type of keyframe used by the
``current_animation`` property of a :ref:`class_AnimationPlayer`,
and Animation Playback tracks.
- **Capture:** If the first keyframe's time is greater than ``0.0``, the
current value of the property will be remembered and
will be blended with the first animation key. For example, you
could use the Capture mode to move a node that's located anywhere
to a specific location.
.. figure:: img/animation_track_rate.png
:alt: Track mode
Track mode
In normal animations, you usually use "Continuous". The other types are
used to script complex animations.
The interpolation tells Godot how to calculate the frame values between
the keyframes. These interpolation modes are supported:
- Nearest: Set the nearest keyframe value
- Linear: Set the value based on a linear function calculation between
the two keyframes
- Cubic: Set the value based on a cubic function calculation between
the two keyframes
.. figure:: img/animation_track_interpolation.png
:alt: Track interpolation
Track interpolation
Cubic interpolation leads to a more natural movement, where the
animation is slower at a keyframe and faster between keyframes. This is
usually used for character animation. Linear interpolation creates more
of a robotic movement.
Godot supports two loop modes, which affect the animation if it's set to
loop:
.. figure:: img/animation_track_loop_modes.png
:alt: Loop modes
Loop modes
- Clamp loop interpolation: When this is selected, the animation stops
after the last keyframe for this track. When the first keyframe is
reached again, the animation will reset to its values.
- Wrap loop interpolation: When this is selected, Godot calculates the
animation after the last keyframe to reach the values of the first
keyframe again.
Keyframes for other properties
------------------------------
Godot doesn't restrict you to only edit transform properties. Every
property can be used as a track where you can set keyframes.
If you select your sprite while the animation panel is visible, you get
a small keyframe button for all the sprite's properties. Click on
this button and Godot automatically adds a track and keyframe to the
current animation.
.. figure:: img/animation_properties_keyframe.png
:alt: Keyframes for other properties
Keyframes for other properties
Edit keyframes
--------------
For advanced use and to edit keyframes in detail, You can click on them
to bring up the keyframe editor in the inspector. You can use this to
directly edit its values.
.. figure:: img/animation_keyframe_editor_key.png
:alt: Keyframe editor editing a key
Keyframe editor editing a key
Additionally, you can also edit the easing value for this keyframe by
clicking and dragging the easing setting. This tells Godot, how to change
the property values when it reaches this keyframe.
You usually tweak your animations this way, when the movement doesn't
"look right".
Advanced: Call Method tracks
----------------------------
Godot's animation engine doesn't stop here. If you're already
comfortable with Godot's scripting language
:ref:`doc_gdscript` and :doc:`/classes/index` you
know that each node type is a class and has a bunch of callable
methods.
For example, the :ref:`class_AudioStreamPlayer` node type has a
method to play an audio stream.
Wouldn't it be great to use a method at a specific keyframe in an
animation? This is where "Call Method Tracks" come in handy. These tracks
reference a node again, this time without a reference to a property.
Instead, a keyframe holds the name and arguments of a method, that
Godot should call when it reaches this keyframe.
To demonstrate, we're going to use a call method track to play audio at a
specific keyframe. Normally to play audio you should use an audio track,
but for the sake of demonstrating methods we're going to do it this way.
Add a :ref:`class_AudioStreamPlayer` to the Scene Tree and setup a
stream using an audio file you put in your project.
Click on "Add track" (|Add track|) on the animation panel's track
controls.
Select "Add Call Method Track" from the list of possible track types.
.. figure:: img/animation_add_call_method_track.png
:alt: Add Call Method Track
Add Call Method Track
Select the :ref:`class_AudioStreamPlayer` node in the selection
window. Godot adds the track with the reference to the node.
.. figure:: img/animation_select_audiostreamplayer.png
:alt: Select AudioStreamPlayer
Select AudioStreamPlayer
Right click the timeline where Godot should play the sample and
click the "Insert Key" option. This will bring up a list of methods
that can be called for the AudioStreamPlayer node. Select the first
one.
.. image:: img/animation_method_options.png
When Godot reaches the keyframe, Godot calls the
:ref:`class_AudioStreamPlayer` node's "play" function and the stream
plays.
You can change its position by dragging it on the timeline, you can also
click on the keyframe and use the keyframe settings in the inspector.
.. image:: img/animation_call_method_keyframe.png
.. |Play from beginning| image:: img/animation_play_from_beginning.png
.. |Add Animation| image:: img/animation_add.png
.. |Add track| image:: img/animation_add_track.png
Using RESET tracks
------------------
You can set up a special *RESET* animation to contain the "default pose".
This is used to ensure that the default pose is restored when you save
the scene and open it again in the editor.
For existing tracks, you can add an animation called "RESET" (case-sensitive),
then add tracks for each property that you want to reset.
The only keyframe should be at time 0, and give it the desired default value
for each track.
If AnimationPlayer's **Reset On Save** property is set to ``true``,
the scene will be saved with the effects of the reset animation applied
(as if it had been seeked to time ``0.0``).
This only affects the saved file the property tracks in the editor stay
where they were.
If you want to reset the tracks in the editor, select the AnimationPlayer node,
open the **Animation** bottom panel then choose **Apply Reset** in the
animation editor's **Edit** dropdown menu.
When adding tracks on new animations, the editor will ask you to automatically
create a RESET track when using the keyframe icon next to a property in the inspector.
This does not apply on tracks created with Godot versions prior to 3.4,
as the animation reset track feature was added in 3.4.

View file

@ -0,0 +1,234 @@
.. _doc_playing_videos:
Playing videos
==============
Godot supports video playback with the :ref:`class_VideoPlayer` node.
Supported playback formats
--------------------------
The only supported format in core is **Ogg Theora** (not to be confused with Ogg
Vorbis audio). It's possible for extensions to bring support for additional
formats, but no such extensions exist yet as of July 2022.
H.264 and H.265 cannot be supported in core Godot, as they are both encumbered
by software patents. AV1 is royalty-free, but it remains slow to decode on the
CPU and hardware decoding support isn't readily available on all GPUs in use
yet.
WebM is supported in core in Godot 3.x, but support for it will be removed in 4.0
as it proved to be too buggy and difficult to maintain.
Therefore, **using WebM is not recommended**.
.. note::
You may find videos with an ``.ogg`` or ``.ogx`` extensions, which are generic
extensions for data within an Ogg container.
Renaming these file extensions to ``.ogv`` *may* allow the videos to be
imported in Godot. However, not all files with ``.ogg`` or ``.ogx``
extensions are videos - some of them may only contain audio.
Setting up VideoPlayer
----------------------------
1. Create a VideoPlayer node using the Create New Node dialog.
2. Select the VideoPlayer node in the scene tree dock, go to the inspector
and load an ``.ogv`` file in the Stream property.
- If you don't have your video in Ogg Theora format yet, jump to
:ref:`doc_playing_videos_recommended_theora_encoding_settings`.
3. If you want the video to play as soon as the scene is loaded, check
**Autoplay** in the inspector. If not, leave **Autoplay** disabled and call
``play()`` on the VideoPlayer node in a script to start playback when
desired.
Handling resizing and different aspect ratios
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
By default in Godot 4.0, the VideoPlayer will automatically be resized to match
the video's resolution. You can make it follow usual :ref:`class_Control` sizing
by enabling **Expand** on the VideoPlayer node.
To adjust how the VideoPlayer node resizes depending on window size,
adjust the anchors using the **Layout** menu at the top of the 2D editor
viewport. However, this setup may not be powerful enough to handle all use
cases, such as playing fullscreen videos without distorting the video (but with
empty space on the edges instead). For more control, you can use an
:ref:`class_AspectRatioContainer` node, which is designed to handle this kind of
use case:
Add an AspectRatioContainer node. Make sure it is not a child of any other
container node. Select the AspectRatioContainer node, then set its **Layout** at
the top of the 2D editor to **Full Rect**. Set **Ratio** in the
AspectRatioContainer node to match your video's aspect ratio. You can use math
formulas in the inspector to help yourself. Remember to make one of the operands
a float. Otherwise, the division's result will always be an integer.
.. figure:: img/playing_videos_aspect_ratio_container.png
:figclass: figure-w480
:align: center
:alt: AspectRatioContainer's Ratio property being modified in the editor inspector
This will evaluate to (approximately) 1.777778
Once you've configured the AspectRatioContainer, reparent your VideoPlayer
node to be a child of the AspectRatioContainer node. Make sure **Expand** is
disabled on the VideoPlayer. Your video should now scale automatically
to fit the whole screen while avoiding distortion.
.. seealso::
See :ref:`doc_multiple_resolutions` for more tips on supporting multiple
aspect ratios in your project.
Displaying a video on a 3D surface
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Using a VideoPlayer node as a child of a :ref:`class_Viewport` node,
it's possible to display any 2D node on a 3D surface. For example, this can be
used to display animated billboards when frame-by-frame animation would require
too much memory.
This can be done with the following steps:
1. Create a :ref:`class_Viewport` node. Set its size to match your video's size
in pixels.
2. Create a VideoPlayer node *as a child of the Viewport node* and specify
a video path in it. Make sure **Expand** is disabled, and enable **Autoplay** if needed.
3. Create a MeshInstance node with a PlaneMesh or QuadMesh resource in its Mesh property.
Resize the mesh to match the video's aspect ratio (otherwise, it will appear distorted).
4. Create a new SpatialMaterial resource in the **Material Override** property
in the GeometryInstance section.
5. Enable **Local To Scene** in the SpatialMaterial's Resource section (at the bottom).
This is *required* before you can use a ViewportTexture in its Albedo Texture property.
6. In the SpatialMaterial, set the **Albedo > Texture** property to **New ViewportTexture**.
Edit the new resource by clicking it, then specify the path to the Viewport node
in the **Viewport Path** property.
7. Enable **Albedo Tex Force sRGB** in the SpatialMaterial to prevent colors
from being washed out.
8. If the billboard is supposed to emit its own light, enable
**Flags > Unshaded** to improve rendering performance.
See :ref:`doc_viewports` and the
`GUI in 3D demo <https://github.com/godotengine/godot-demo-projects/tree/master/viewport/gui_in_3d>`__
for more information on setting this up.
Video decoding conditions and recommended resolutions
-----------------------------------------------------
Video decoding is performed on the CPU, as GPUs don't have hardware acceleration
for decoding Theora videos. Modern desktop CPUs can decode Ogg Theora videos at
1440p @ 60 FPS or more, but low-end mobile CPUs will likely struggle with
high-resolution videos.
To ensure your videos decode smoothly on varied hardware:
- When developing games for desktop platforms, it's recommended to encode in
1080p at most (preferably at 30 FPS). Most people are still using 1080p or
lower resolution displays, so encoding higher-resolution videos may not be
worth the increased file size and CPU requirements.
- When developing games for mobile or web platforms, it's recommended to encode
in 720p at most (preferably at 30 FPS or even lower). The visual difference
between 720p and 1080p videos on a mobile device is usually not that
noticeable.
Playback limitations
--------------------
There are several limitations with the current implementation of video playback in Godot:
- Seeking a video to a certain point is not supported.
- Changing playback speed is not supported. VideoPlayer also won't follow
:ref:`Engine.time_scale<class_Engine_property_time_scale>`.
- Looping is not supported, but you can connect a VideoPlayer's
:ref:`finished <class_VideoPlayer_signal_finished>` signal to a function
that plays the video again. However, this will cause a black frame to be
visible when the video restarts. This can be worked around by adding a fade to
black in the video file before the video ends, or by hiding the video for one
frame and displaying a TextureRect with a screenshot of the first frame of the
video until the video is restarted.
- Streaming a video from a URL is not supported.
.. _doc_playing_videos_recommended_theora_encoding_settings:
Recommended Theora encoding settings
------------------------------------
A word of advice is to **avoid relying on built-in Ogg Theora exporters** (most of the time).
There are 2 reasons you may want to favor using an external program to encode your video:
- Some programs such as Blender can render to Ogg Theora. However, the default
quality presets are usually very low by today's standards. You may be able to
increase the quality options in the software you're using, but you may find
the output quality to remain less than ideal (given the increased file size).
This usually means that the software only supports encoding to constant bit
rate (CBR), instead of variable bit rate (VBR). VBR encoding should be
preferred in most scenarios as it provides a better quality to file size
ratio.
- Some other programs can't render to Ogg Theora at all.
In this case, you can **render the video to an intermediate high-quality format**
(such as a high-bitrate H.264 video) then re-encode it to Ogg Theora. Ideally,
you should use a lossless or uncompressed format as an intermediate format to
maximize the quality of the output Ogg Theora video, but this can require a lot
of disk space.
`HandBrake <https://handbrake.fr/>`__
(GUI) and `FFmpeg <https://ffmpeg.org/>`__ (CLI) are popular open source tools
for this purpose. FFmpeg has a steeper learning curve, but it's more powerful.
Here are example FFmpeg commands to convert a MP4 video to Ogg Theora. Since
FFmpeg supports a lot of input formats, you should be able to use the commands
below with almost any input video format (AVI, MOV, WebM, …).
.. note::
Make sure your copy of FFmpeg is compiled with libtheora and libvorbis support.
You can check this by running ``ffmpeg`` without any arguments, then looking
at the ``configuration:`` line in the command output.
Balancing quality and file size
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The **video quality** level (``-q:v``) must be between ``1`` and ``10``. Quality
``6`` is a good compromise between quality and file size. If encoding at a high
resolution (such as 1440p or 4K), you will probably want to decrease ``-q:v`` to
``5`` to keep file sizes reasonable. Since pixel density is higher on a 1440p or
4K video, lower quality presets at higher resolutions will look as good or
better compared to low-resolution videos.
The **audio quality** level (``-q:a``) must be between ``-1`` and ``10``. Quality
``6`` provides a good compromise between quality and file size. In contrast to
video quality, increasing audio quality doesn't increase the output file size
nearly as much. Therefore, if you want the cleanest audio possible, you can
increase this to ``9`` to get *perceptually lossless* audio. This is especially
valuable if your input file already uses lossy audio compression. See
`this page <https://wiki.hydrogenaud.io/index.php?title=Recommended_Ogg_Vorbis#Recommended_Encoder_Settings>`__
for a table listing Ogg Vorbis audio quality presets and their respective
variable bitrates.
FFmpeg: Convert while preserving original video resolution
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The following command converts the video while keeping its original resolution.
The video and audio's bitrate will be variable to maximize quality while saving
space in parts of the video/audio that don't require a high bitrate (such as
static scenes).
::
ffmpeg -i input.mp4 -q:v 6 -q:a 6 output.ogv
FFmpeg: Resize the video then convert it
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The following command resizes a video to be 720 pixels tall (720p), while
preserving its existing aspect ratio. This helps decrease the file size
significantly if the source is recorded at a higher resolution than 720p:
::
ffmpeg -i input.mp4 -vf "scale=-1:720" -q:v 6 -q:a 6 output.ogv