batching.rst 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. .. _doc_batching:
  2. Optimization using batching
  3. ===========================
  4. Introduction
  5. ~~~~~~~~~~~~
  6. Game engines have to send a set of instructions to the GPU to tell the GPU what
  7. and where to draw. These instructions are sent using common instructions called
  8. :abbr:`APIs (Application Programming Interfaces)`. Examples of graphics APIs are
  9. OpenGL, OpenGL ES, and Vulkan.
  10. Different APIs incur different costs when drawing objects. OpenGL handles a lot
  11. of work for the user in the GPU driver at the cost of more expensive draw calls.
  12. As a result, applications can often be sped up by reducing the number of draw
  13. calls.
  14. .. note::
  15. 2D batching is currently only supported when using the GLES2 renderer.
  16. Draw calls
  17. ^^^^^^^^^^
  18. In 2D, we need to tell the GPU to render a series of primitives (rectangles,
  19. lines, polygons etc). The most obvious technique is to tell the GPU to render
  20. one primitive at a time, telling it some information such as the texture used,
  21. the material, the position, size, etc. then saying "Draw!" (this is called a
  22. draw call).
  23. While this is conceptually simple from the engine side, GPUs operate very slowly
  24. when used in this manner. GPUs work much more efficiently if you tell them to
  25. draw a number of similar primitives all in one draw call, which we will call a
  26. "batch".
  27. It turns out that they don't just work a bit faster when used in this manner;
  28. they work a *lot* faster.
  29. As Godot is designed to be a general-purpose engine, the primitives coming into
  30. the Godot renderer can be in any order, sometimes similar, and sometimes
  31. dissimilar. To match Godot's general-purpose nature with the batching
  32. preferences of GPUs, Godot features an intermediate layer which can
  33. automatically group together primitives wherever possible and send these batches
  34. on to the GPU. This can give an increase in rendering performance while
  35. requiring few (if any) changes to your Godot project.
  36. How it works
  37. ~~~~~~~~~~~~
  38. Instructions come into the renderer from your game in the form of a series of
  39. items, each of which can contain one or more commands. The items correspond to
  40. Nodes in the scene tree, and the commands correspond to primitives such as
  41. rectangles or polygons. Some items such as TileMaps and text can contain a
  42. large number of commands (tiles and glyphs respectively). Others, such as
  43. sprites, may only contain a single command (a rectangle).
  44. The batcher uses two main techniques to group together primitives:
  45. - Consecutive items can be joined together.
  46. - Consecutive commands within an item can be joined to form a batch.
  47. Breaking batching
  48. ^^^^^^^^^^^^^^^^^
  49. Batching can only take place if the items or commands are similar enough to be
  50. rendered in one draw call. Certain changes (or techniques), by necessity, prevent
  51. the formation of a contiguous batch, this is referred to as "breaking batching".
  52. Batching will be broken by (amongst other things):
  53. - Change of texture.
  54. - Change of material.
  55. - Change of primitive type (say, going from rectangles to lines).
  56. .. note::
  57. For example, if you draw a series of sprites each with a different texture,
  58. there is no way they can be batched.
  59. Determining the rendering order
  60. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  61. The question arises, if only similar items can be drawn together in a batch, why
  62. don't we look through all the items in a scene, group together all the similar
  63. items, and draw them together?
  64. In 3D, this is often exactly how engines work. However, in Godot's 2D renderer,
  65. items are drawn in "painter's order", from back to front. This ensures that
  66. items at the front are drawn on top of earlier items when they overlap.
  67. This also means that if we try and draw objects on a per-texture basis, then
  68. this painter's order may break and objects will be drawn in the wrong order.
  69. In Godot, this back-to-front order is determined by:
  70. - The order of objects in the scene tree.
  71. - The Z index of objects.
  72. - The canvas layer.
  73. - :ref:`class_YSort` nodes.
  74. .. note::
  75. You can group similar objects together for easier batching. While doing so
  76. is not a requirement on your part, think of it as an optional approach that
  77. can improve performance in some cases. See the
  78. :ref:`doc_batching_diagnostics` section to help you make this decision.
  79. A trick
  80. ^^^^^^^
  81. And now, a sleight of hand. Even though the idea of painter's order is that
  82. objects are rendered from back to front, consider 3 objects ``A``, ``B`` and
  83. ``C``, that contain 2 different textures: grass and wood.
  84. .. image:: img/overlap1.png
  85. In painter's order they are ordered::
  86. A - wood
  87. B - grass
  88. C - wood
  89. Because of the texture changes, they can't be batched and will be rendered in 3
  90. draw calls.
  91. However, painter's order is only needed on the assumption that they will be
  92. drawn *on top* of each other. If we relax that assumption, i.e. if none of these
  93. 3 objects are overlapping, there is *no need* to preserve painter's order. The
  94. rendered result will be the same. What if we could take advantage of this?
  95. Item reordering
  96. ^^^^^^^^^^^^^^^
  97. .. image:: img/overlap2.png
  98. It turns out that we can reorder items. However, we can only do this if the
  99. items satisfy the conditions of an overlap test, to ensure that the end result
  100. will be the same as if they were not reordered. The overlap test is very cheap
  101. in performance terms, but not absolutely free, so there is a slight cost to
  102. looking ahead to decide whether items can be reordered. The number of items to
  103. lookahead for reordering can be set in project settings (see below), in order to
  104. balance the costs and benefits in your project.
  105. ::
  106. A - wood
  107. C - wood
  108. B - grass
  109. Since the texture only changes once, we can render the above in only 2 draw
  110. calls.
  111. Lights
  112. ~~~~~~
  113. Although the batching system's job is normally quite straightforward, it becomes
  114. considerably more complex when 2D lights are used. This is because lights are
  115. drawn using additional passes, one for each light affecting the primitive.
  116. Consider 2 sprites ``A`` and ``B``, with identical texture and material. Without
  117. lights, they would be batched together and drawn in one draw call. But with 3
  118. lights, they would be drawn as follows, each line being a draw call:
  119. .. image:: img/lights_overlap.png
  120. ::
  121. A
  122. A - light 1
  123. A - light 2
  124. A - light 3
  125. B
  126. B - light 1
  127. B - light 2
  128. B - light 3
  129. That is a lot of draw calls: 8 for only 2 sprites. Now, consider we are drawing
  130. 1,000 sprites. The number of draw calls quickly becomes astronomical and
  131. performance suffers. This is partly why lights have the potential to drastically
  132. slow down 2D rendering.
  133. However, if you remember our magician's trick from item reordering, it turns out
  134. we can use the same trick to get around painter's order for lights!
  135. If ``A`` and ``B`` are not overlapping, we can render them together in a batch,
  136. so the drawing process is as follows:
  137. .. image:: img/lights_separate.png
  138. ::
  139. AB
  140. AB - light 1
  141. AB - light 2
  142. AB - light 3
  143. That is only 4 draw calls. Not bad, as that is a 2× reduction. However, consider
  144. that in a real game, you might be drawing closer to 1,000 sprites.
  145. - **Before:** 1000 × 4 = 4,000 draw calls.
  146. - **After:** 1 × 4 = 4 draw calls.
  147. That is a 1000× decrease in draw calls, and should give a huge increase in
  148. performance.
  149. Overlap test
  150. ^^^^^^^^^^^^
  151. However, as with the item reordering, things are not that simple. We must first
  152. perform the overlap test to determine whether we can join these primitives. This
  153. overlap test has a small cost. Again, you can choose the number of primitives to
  154. lookahead in the overlap test to balance the benefits against the cost. With
  155. lights, the benefits usually far outweigh the costs.
  156. Also consider that depending on the arrangement of primitives in the viewport,
  157. the overlap test will sometimes fail (because the primitives overlap and
  158. therefore shouldn't be joined). In practice, the decrease in draw calls may be
  159. less dramatic than in a perfect situation with no overlapping at all. However,
  160. performance is usually far higher than without this lighting optimization.
  161. Light scissoring
  162. ~~~~~~~~~~~~~~~~
  163. Batching can make it more difficult to cull out objects that are not affected or
  164. partially affected by a light. This can increase the fill rate requirements
  165. quite a bit and slow down rendering. *Fill rate* is the rate at which pixels are
  166. colored. It is another potential bottleneck unrelated to draw calls.
  167. In order to counter this problem (and speed up lighting in general), batching
  168. introduces light scissoring. This enables the use of the OpenGL command
  169. ``glScissor()``, which identifies an area outside of which the GPU won't render
  170. any pixels. We can greatly optimize fill rate by identifying the intersection
  171. area between a light and a primitive, and limit rendering the light to
  172. *that area only*.
  173. Light scissoring is controlled with the :ref:`scissor_area_threshold
  174. <class_ProjectSettings_property_rendering/batching/lights/scissor_area_threshold>`
  175. project setting. This value is between 1.0 and 0.0, with 1.0 being off (no
  176. scissoring), and 0.0 being scissoring in every circumstance. The reason for the
  177. setting is that there may be some small cost to scissoring on some hardware.
  178. That said, scissoring should usually result in performance gains when you're
  179. using 2D lighting.
  180. The relationship between the threshold and whether a scissor operation takes
  181. place is not always straightforward. Generally, it represents the pixel area
  182. that is potentially "saved" by a scissor operation (i.e. the fill rate saved).
  183. At 1.0, the entire screen's pixels would need to be saved, which rarely (if
  184. ever) happens, so it is switched off. In practice, the useful values are close
  185. to 0.0, as only a small percentage of pixels need to be saved for the operation
  186. to be useful.
  187. The exact relationship is probably not necessary for users to worry about, but
  188. is included in the appendix out of interest:
  189. :ref:`doc_batching_light_scissoring_threshold_calculation`
  190. .. figure:: img/scissoring.png
  191. :alt: Light scissoring example diagram
  192. Bottom right is a light, the red area is the pixels saved by the scissoring
  193. operation. Only the intersection needs to be rendered.
  194. Vertex baking
  195. ~~~~~~~~~~~~~
  196. The GPU shader receives instructions on what to draw in 2 main ways:
  197. - Shader uniforms (e.g. modulate color, item transform).
  198. - Vertex attributes (vertex color, local transform).
  199. However, within a single draw call (batch), we cannot change uniforms. This
  200. means that naively, we would not be able to batch together items or commands
  201. that change ``final_modulate`` or an item's transform. Unfortunately, that
  202. happens in an awful lot of cases. For instance, sprites are typically
  203. individual nodes with their own item transform, and they may have their own
  204. color modulate as well.
  205. To get around this problem, the batching can "bake" some of the uniforms into
  206. the vertex attributes.
  207. - The item transform can be combined with the local transform and sent in a
  208. vertex attribute.
  209. - The final modulate color can be combined with the vertex colors, and sent in a
  210. vertex attribute.
  211. In most cases, this works fine, but this shortcut breaks down if a shader expects
  212. these values to be available individually rather than combined. This can happen
  213. in custom shaders.
  214. Custom shaders
  215. ^^^^^^^^^^^^^^
  216. As a result of the limitation described above, certain operations in custom
  217. shaders will prevent vertex baking and therefore decrease the potential for
  218. batching. While we are working to decrease these cases, the following caveats
  219. currently apply:
  220. - Reading or writing ``COLOR`` or ``MODULATE`` disables vertex color baking.
  221. - Reading ``VERTEX`` disables vertex position baking.
  222. Project Settings
  223. ~~~~~~~~~~~~~~~~
  224. To fine-tune batching, a number of project settings are available. You can
  225. usually leave these at default during development, but it's a good idea to
  226. experiment to ensure you are getting maximum performance. Spending a little time
  227. tweaking parameters can often give considerable performance gains for very
  228. little effort. See the on-hover tooltips in the Project Settings for more
  229. information.
  230. rendering/batching/options
  231. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  232. - :ref:`use_batching
  233. <class_ProjectSettings_property_rendering/batching/options/use_batching>` -
  234. Turns batching on or off.
  235. - :ref:`use_batching_in_editor
  236. <class_ProjectSettings_property_rendering/batching/options/use_batching_in_editor>`
  237. Turns batching on or off in the Godot editor.
  238. This setting doesn't affect the running project in any way.
  239. - :ref:`single_rect_fallback
  240. <class_ProjectSettings_property_rendering/batching/options/single_rect_fallback>` -
  241. This is a faster way of drawing unbatchable rectangles. However, it may lead
  242. to flicker on some hardware so it's not recommended.
  243. rendering/batching/parameters
  244. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  245. - :ref:`max_join_item_commands <class_ProjectSettings_property_rendering/batching/parameters/max_join_item_commands>` -
  246. One of the most important ways of achieving batching is to join suitable
  247. adjacent items (nodes) together, however they can only be joined if the
  248. commands they contain are compatible. The system must therefore do a lookahead
  249. through the commands in an item to determine whether it can be joined. This
  250. has a small cost per command, and items with a large number of commands are
  251. not worth joining, so the best value may be project dependent.
  252. - :ref:`colored_vertex_format_threshold
  253. <class_ProjectSettings_property_rendering/batching/parameters/colored_vertex_format_threshold>` -
  254. Baking colors into vertices results in a larger vertex format. This is not
  255. necessarily worth doing unless there are a lot of color changes going on
  256. within a joined item. This parameter represents the proportion of commands
  257. containing color changes / the total commands, above which it switches to
  258. baked colors.
  259. - :ref:`batch_buffer_size
  260. <class_ProjectSettings_property_rendering/batching/parameters/batch_buffer_size>` -
  261. This determines the maximum size of a batch, it doesn't have a huge effect
  262. on performance but can be worth decreasing for mobile if RAM is at a premium.
  263. - :ref:`item_reordering_lookahead
  264. <class_ProjectSettings_property_rendering/batching/parameters/item_reordering_lookahead>` -
  265. Item reordering can help especially with interleaved sprites using different
  266. textures. The lookahead for the overlap test has a small cost, so the best
  267. value may change per project.
  268. rendering/batching/lights
  269. ^^^^^^^^^^^^^^^^^^^^^^^^^
  270. - :ref:`scissor_area_threshold
  271. <class_ProjectSettings_property_rendering/batching/lights/scissor_area_threshold>` -
  272. See light scissoring.
  273. - :ref:`max_join_items
  274. <class_ProjectSettings_property_rendering/batching/lights/max_join_items>` -
  275. Joining items before lighting can significantly increase
  276. performance. This requires an overlap test, which has a small cost, so the
  277. costs and benefits may be project dependent, and hence the best value to use
  278. here.
  279. rendering/batching/debug
  280. ^^^^^^^^^^^^^^^^^^^^^^^^
  281. - :ref:`flash_batching
  282. <class_ProjectSettings_property_rendering/batching/debug/flash_batching>` -
  283. This is purely a debugging feature to identify regressions between the
  284. batching and legacy renderer. When it is switched on, the batching and legacy
  285. renderer are used alternately on each frame. This will decrease performance,
  286. and should not be used for your final export, only for testing.
  287. - :ref:`diagnose_frame
  288. <class_ProjectSettings_property_rendering/batching/debug/diagnose_frame>` -
  289. This will periodically print a diagnostic batching log to
  290. the Godot IDE / console.
  291. rendering/batching/precision
  292. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  293. - :ref:`uv_contract
  294. <class_ProjectSettings_property_rendering/batching/precision/uv_contract>` -
  295. On some hardware (notably some Android devices) there have been reports of
  296. tilemap tiles drawing slightly outside their UV range, leading to edge
  297. artifacts such as lines around tiles. If you see this problem, try enabling uv
  298. contract. This makes a small contraction in the UV coordinates to compensate
  299. for precision errors on devices.
  300. - :ref:`uv_contract_amount
  301. <class_ProjectSettings_property_rendering/batching/precision/uv_contract_amount>` -
  302. Hopefully, the default amount should cure artifacts on most devices,
  303. but this value remains adjustable just in case.
  304. .. _doc_batching_diagnostics:
  305. Diagnostics
  306. ~~~~~~~~~~~
  307. Although you can change parameters and examine the effect on frame rate, this
  308. can feel like working blindly, with no idea of what is going on under the hood.
  309. To help with this, batching offers a diagnostic mode, which will periodically
  310. print out (to the IDE or console) a list of the batches that are being
  311. processed. This can help pinpoint situations where batching isn't occurring
  312. as intended, and help you fix these situations to get the best possible performance.
  313. Reading a diagnostic
  314. ^^^^^^^^^^^^^^^^^^^^
  315. .. code-block:: cpp
  316. canvas_begin FRAME 2604
  317. items
  318. joined_item 1 refs
  319. batch D 0-0
  320. batch D 0-2 n n
  321. batch R 0-1 [0 - 0] {255 255 255 255 }
  322. joined_item 1 refs
  323. batch D 0-0
  324. batch R 0-1 [0 - 146] {255 255 255 255 }
  325. batch D 0-0
  326. batch R 0-1 [0 - 146] {255 255 255 255 }
  327. joined_item 1 refs
  328. batch D 0-0
  329. batch R 0-2560 [0 - 144] {158 193 0 104 } MULTI
  330. batch D 0-0
  331. batch R 0-2560 [0 - 144] {158 193 0 104 } MULTI
  332. batch D 0-0
  333. batch R 0-2560 [0 - 144] {158 193 0 104 } MULTI
  334. canvas_end
  335. This is a typical diagnostic.
  336. - **joined_item:** A joined item can contain 1 or
  337. more references to items (nodes). Generally, joined_items containing many
  338. references is preferable to many joined_items containing a single reference.
  339. Whether items can be joined will be determined by their contents and
  340. compatibility with the previous item.
  341. - **batch R:** A batch containing rectangles. The second number is the number of
  342. rects. The second number in square brackets is the Godot texture ID, and the
  343. numbers in curly braces is the color. If the batch contains more than one rect,
  344. ``MULTI`` is added to the line to make it easy to identify.
  345. Seeing ``MULTI`` is good as it indicates successful batching.
  346. - **batch D:** A default batch, containing everything else that is not currently
  347. batched.
  348. Default batches
  349. ^^^^^^^^^^^^^^^
  350. The second number following default batches is the number of commands in the
  351. batch, and it is followed by a brief summary of the contents::
  352. l - line
  353. PL - polyline
  354. r - rect
  355. n - ninepatch
  356. PR - primitive
  357. p - polygon
  358. m - mesh
  359. MM - multimesh
  360. PA - particles
  361. c - circle
  362. t - transform
  363. CI - clip_ignore
  364. You may see "dummy" default batches containing no commands; you can ignore those.
  365. Frequently asked questions
  366. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  367. I don't get a large performance increase when enabling batching.
  368. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  369. - Try the diagnostics, see how much batching is occurring, and whether it can be
  370. improved
  371. - Try changing batching parameters in the Project Settings.
  372. - Consider that batching may not be your bottleneck (see bottlenecks).
  373. I get a decrease in performance with batching.
  374. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  375. - Try the steps described above to increase the number of batching opportunities.
  376. - Try enabling :ref:`single_rect_fallback
  377. <class_ProjectSettings_property_rendering/batching/options/single_rect_fallback>`.
  378. - The single rect fallback method is the default used without batching, and it
  379. is approximately twice as fast. However, it can result in flickering on some
  380. hardware, so its use is discouraged.
  381. - After trying the above, if your scene is still performing worse, consider
  382. turning off batching.
  383. I use custom shaders and the items are not batching.
  384. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  385. - Custom shaders can be problematic for batching, see the custom shaders section
  386. I am seeing line artifacts appear on certain hardware.
  387. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  388. - See the :ref:`uv_contract
  389. <class_ProjectSettings_property_rendering/batching/precision/uv_contract>`
  390. project setting which can be used to solve this problem.
  391. I use a large number of textures, so few items are being batched.
  392. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  393. - Consider using texture atlases. As well as allowing batching, these
  394. reduce the need for state changes associated with changing textures.
  395. Appendix
  396. ~~~~~~~~
  397. .. _doc_batching_light_scissoring_threshold_calculation:
  398. Light scissoring threshold calculation
  399. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  400. The actual proportion of screen pixel area used as the threshold is the
  401. :ref:`scissor_area_threshold
  402. <class_ProjectSettings_property_rendering/batching/lights/scissor_area_threshold>`
  403. value to the power of 4.
  404. For example, on a screen size of 1920×1080, there are 2,073,600 pixels.
  405. At a threshold of 1,000 pixels, the proportion would be::
  406. 1000 / 2073600 = 0.00048225
  407. 0.00048225 ^ (1/4) = 0.14819
  408. So a :ref:`scissor_area_threshold
  409. <class_ProjectSettings_property_rendering/batching/lights/scissor_area_threshold>`
  410. of ``0.15`` would be a reasonable value to try.
  411. Going the other way, for instance with a :ref:`scissor_area_threshold
  412. <class_ProjectSettings_property_rendering/batching/lights/scissor_area_threshold>`
  413. of ``0.5``::
  414. 0.5 ^ 4 = 0.0625
  415. 0.0625 * 2073600 = 129600 pixels
  416. If the number of pixels saved is greater than this threshold, the scissor is
  417. activated.