Windows flip display buffers

Flipping Surfaces (Direct3D 9)

A Direct3D application typically displays an animated sequence by generating the frames of the animation in back buffers and presenting them in sequence. Back buffers are organized into swap chains. A swap chain is a series of buffers that «flip» to the screen one after another. This can be used to render one scene in memory and then flip the scene to the screen when rendering is complete. This avoids the phenomenon known as tearing and allows for smoother animation.

Each device created in Direct3D has at least one swap chain. When you initialize the first Direct3D device, you set the BackBufferCount member of D3DPRESENT_PARAMETERS, which tells Direct3D the number of back buffers that will be in the swap chain. The call to IDirect3D9::CreateDevice then creates the Direct3D device and corresponding swap chain.

When you use IDirect3DDevice9::Present to request a surface flip operation, the pointers to surface memory for the front buffer and back buffers are swapped. Flipping is performed by switching pointers that the display device uses for referencing memory, not by copying surface memory. When a flipping chain contains a front buffer and more than one back buffer, the pointers are switched in a circular pattern, as shown in the following diagram.

You can create addition swap chains for a device by calling IDirect3DDevice9::CreateAdditionalSwapChain. An application can create one swap chain per view and associate each swap chain with a particular window. The application renders images in the back buffers of each swap chain, and then presents them individually. The two parameters that IDirect3DDevice9::CreateAdditionalSwapChain takes are a pointer to a D3DPRESENT_PARAMETERS structure and the address of a pointer to an IDirect3DSwapChain9 interface. You can then use IDirect3DSwapChain9::Present to display the contents of the next back buffer to the front buffer. Note that a device can only have one full-screen swap chain.

You can gain access to a specific back buffer by calling the IDirect3DDevice9::GetBackBuffer or IDirect3DSwapChain9::GetBackBuffer methods, which return a pointer to an IDirect3DSurface9 interface that represents the returned back buffer surface. Note that calling this method increases the internal reference count on the IDirect3DDevice9 interface so be sure to call IUnknown when you are done using this surface or you will have a memory leak.

Remember, Direct3D flips surfaces by swapping surface memory pointers within the swap chain, not by swapping the surfaces themselves. This means that you will always render to the back buffer that will be displayed next.

It is important to note the distinction between a «flipping operation,» as performed by a display adapter driver, and a «Present» operation applied to a swap chain created with D3DSWAPEFFECT_FLIP.

The term «flip» conventionally denotes an operation that alters the range of video memory addresses that a display adapter uses to generate its output signal, thus causing the contents of a previously hidden back buffer to be displayed. In Direct3D 9, the term is often used more generally to describe the presentation of a back buffer in any swap chain created with the D3DSWAPEFFECT_FLIP swap effect.

While such «Present» operations are almost invariably implemented by flip operations when the swap chain is a full-screen one, they are necessarily implemented by copy operations when the swap chain is windowed. Furthermore, a display adapter driver may use flipping to implement Present operations against full-screen swap chains based on the D3DSWAPEFFECT_DISCARD and D3DSWAPEFFECT_COPY.

The discussion above applies to the commonly used case of a full-screen swap chain created with D3DSWAPEFFECT_FLIP.

For a more general discussion of the different swap effects for both windowed and full-screen swap chains, see D3DSWAPEFFECT.

Flipping

Using a back buffer that can be flipped with a front buffer is the best way to take advantage of DirectDraw. Page flipping is essential for smooth, tear-free animation in games and video playback.

The primary surface is the area of memory that is being read from to draw the screen that is currently being displayed. If a primary surface has one or more attached back buffers, it is a flippable surface.

Flipping structures are used to page flip in DirectDraw. Conceptually, they can be thought of as linked lists made of surfaces. The front buffer is the «visible» buffer. The back buffer and all attached flippable surfaces must be the same size and pixel depth as the front buffer. Most modern graphics cards have enough memory for flippable front and back buffers in high resolution modes.

All types of surfaces can be flipped in DirectDraw; page flipping is the common special case. For instance, flipping is not limited to the primary surface on cards that support overlays, or on 3D capable display cards that have texture memory. In these cases, overlays and textures can be flipped in the same way as the primary surface, with the same driver entry point.

Читайте также:  Улучшение качества звука windows

Surfaces that are not used for flipping can have any dimension and can store nonflippable objects such as image data. Image data may also be stored in system memory, but in that case DirectDraw may use the hardware emulation layer (HEL) because hardware blitters cannot normally reach system memory to blit the image data. Some cards allow hardware blitters to have direct memory access (DMA) to system memory, so DirectDraw performs a check for DMA.

The following figure illustrates the relationship between two flippable surfaces.

If a front buffer has one or more back buffers attached, it is a flippable surface, as shown in the preceding figure. The back buffer and all attached flippable surfaces must be the same size and pixel depth as the front buffer. A back buffer surface becomes the primary surface using a flip. A flip simply changes a pointer so it points to a different flippable surface, thereby displaying the new surface. The front buffer (which is no longer the primary surface) then becomes accessible, and can have new data written to it.

Flipping solves most screen flicker problems. The ability to render to a surface that is not being displayed allows smooth, tear-free animation for game play and video playback.

Буферы экрана консоли Console Screen Buffers

Буфер экрана — это двумерный массив символов и данных о цвете для вывода в окне консоли. A screen buffer is a two-dimensional array of character and color data for output in a console window. Консоль может иметь несколько буферов экрана. A console can have multiple screen buffers. Буфер активного экрана отображается на экране. The active screen buffer is the one that is displayed on the screen.

Система создает буфер экрана каждый раз при создании новой консоли. The system creates a screen buffer whenever it creates a new console. Чтобы открыть дескриптор для активного буфера экрана консоли, укажите значение CONOUT$ в вызове к функции CreateFile. To open a handle to a console’s active screen buffer, specify the CONOUT$ value in a call to the CreateFile function. Процесс может использовать функцию CreateConsoleScreenBuffer для создания дополнительных буферов экрана консоли. A process can use the CreateConsoleScreenBuffer function to create additional screen buffers for its console. Новый буфер экрана не активен, пока его дескриптор не будет указан в вызове функции SetConsoleActiveScreenBuffer. A new screen buffer is not active until its handle is specified in a call to the SetConsoleActiveScreenBuffer function. Но доступ к буферам экрана для чтения и записи можно получить независимо от того, активны они или неактивны. However, screen buffers can be accessed for reading and writing whether they are active or inactive.

Каждый буфер экрана содержит собственный двумерный массив записей с данными о символах. Each screen buffer has its own two-dimensional array of character information records. Данные о каждом символе хранятся в структуре CHAR_INFO, которая указывает символ Юникода или ANSI, а также цвета переднего плана и фона для отображения символа. The data for each character is stored in a CHAR_INFO structure that specifies the Unicode or ANSI character and the foreground and background colors in which that character is displayed.

Некоторые свойства, связанные с буфером экрана, можно задать независимо для каждого буфера. A number of properties associated with a screen buffer can be set independently for each screen buffer. Это означает, что изменение активного буфера экрана может привести к значительному изменению внешнего вида окна консоли. This means that changing the active screen buffer can have a dramatic effect on the appearance of the console window. Свойства, связанные с буфером экрана, включают следующие: The properties associated with a screen buffer include:

  • Размер буфера экрана, в символьных строках и столбцах. Screen buffer size, in character rows and columns.
  • Атрибуты текста (цвета переднего плана и фона для отображения текста, записываемого функцией WriteFile или WriteConsole). Text attributes (foreground and background colors for displaying text to be written by the WriteFile or WriteConsole function).
  • Размер и расположение окна (прямоугольная область буфера экрана консоли, отображаемого в окне консоли). Window size and location (the rectangular region of the console screen buffer that is displayed in the console window).
  • Позиция, внешний вид и видимость курсора. Cursor position, appearance, and visibility.
  • Режимы вывода (ENABLE_PROCESSED_OUTPUT и ENABLE_WRAP_AT_EOL_OUTPUT). Output modes (ENABLE_PROCESSED_OUTPUT and ENABLE_WRAP_AT_EOL_OUTPUT). Дополнительные сведения о режимах вывода консоли см. в статье Высокоуровневые режимы консоли. For more information about console output modes, see High-Level Console Modes.

Созданный буфер экрана содержит пробелы в каждой из позиций. When a screen buffer is created, it contains space characters in every position. Его курсор отображается и размещается в точке начала буфера (0,0), при этом окно располагается таким образом, что его верхний левый угол находится в месте начала буфера. Its cursor is visible and positioned at the buffer’s origin (0,0), and the window is positioned with its upper left corner at the buffer’s origin. Размер буфера экрана консоли, размер окна, атрибуты текста и внешний вид курсора определяются пользователем или системными параметрами по умолчанию. The size of the console screen buffer, the window size, the text attributes, and the appearance of the cursor are determined by the user or by the system defaults. Чтобы получить текущие значения различных свойств, связанных с буфером экрана консоли, используйте функции GetConsoleScreenBufferInfo, GetConsoleCursorInfo и GetConsoleMode. To retrieve the current values of the various properties associated with the console screen buffer, use the GetConsoleScreenBufferInfo, GetConsoleCursorInfo, and GetConsoleMode functions.

Читайте также:  Creating windows service installer

Приложения, изменяющие любые свойства буфера экрана консоли, должны либо создать собственный буфер экрана, либо сохранить состояние наследуемого буфера экрана во время запуска и восстановить его при выходе. Applications that change any of the console screen buffer properties should either create their own screen buffer or save the state of the inherited screen buffer during startup and restore it at exit. Такое скоординированное поведение гарантирует, что изменения не будут затрагивать другие приложения, совместно использующие один сеанс консоли. This cooperative behavior is required to ensure that other applications sharing the same console session are not impacted by the changes.

Рекомендуется использовать режим альтернативного буфера, а не создавать второй буфер экрана для этой цели. It is recommended to use the alternate buffer mode going forward, if possible, instead of creating a second screen buffer for this purpose. Режим альтернативного буфера обеспечивает повышенную совместимость для удаленных устройств и с другими платформами. Alternate buffer mode offers increased compatibility across remote devices and with other platforms. Дополнительные сведения см. в статье о классических API консоли и виртуальном терминале. Please see our discussion on classic console APIs versus virtual terminal for more information.

Внешний вид и расположение курсора Cursor Appearance and Position

Курсор буфера экрана может быть видимым или скрытым. A screen buffer’s cursor can be visible or hidden. Если он отображается, курсор может иметь самый разный вид — от горизонтальной линии внизу ячейки до полного заполнения символьной ячейки. When it is visible, its appearance can vary, ranging from completely filling a character cell to appearing as a horizontal line at the bottom of the cell. Чтобы получить сведения о внешнем виде и видимости курсора, используйте функцию GetConsoleCursorInfo. To retrieve information about the appearance and visibility of the cursor, use the GetConsoleCursorInfo function. Эта функция сообщает, виден ли курсор, и описывает вид курсора с указанием процентного отношения заполнения им символьной ячейки. This function reports whether the cursor is visible and describes the appearance of the cursor as the percentage of a character cell that it fills. Чтобы задать внешний вид и видимость курсора, используйте функцию SetConsoleCursorInfo. To set the appearance and visibility of the cursor, use the SetConsoleCursorInfo function.

Высокоуровневые функции ввода-вывода консоли записывают символы в текущее расположение курсора и переводят его в следующую позицию. Characters written by the high-level console I/O functions are written at the current cursor location, advancing the cursor to the next location. Чтобы определить текущую позицию курсора в системе координат буфера экрана, используйте функцию GetConsoleScreenBufferInfo. To determine the current cursor position in the coordinate system of a screen buffer, use GetConsoleScreenBufferInfo. Вы можете использовать функцию SetConsoleCursorPosition, чтобы задавать позицию курсора и таким образом управлять размещением текста, который записывается высокоуровневыми функциями или выводится ими. You can use SetConsoleCursorPosition to set the cursor position and, thereby, control the placement of text that is written or echoed by the high-level I/O functions. Если переместить курсор, текст в новом расположении будет перезаписан. If you move the cursor, text at the new cursor location is overwritten.

Не рекомендуется использовать низкоуровневые функции для поиска позиции курсора. Using the low-level functions to find the cursor position is discouraged. При необходимости используйте последовательности виртуального терминала для запрашивания этой позиции для расширенных макетов. It is recommended to use virtual terminal sequences to query this position if necessary for advanced layouts. Дополнительные сведения о предпочтительных последовательностях виртуального терминала см. в документе о классических функциях и виртуальном терминале . More information about preferring virtual terminal sequences can be found in the classic functions versus virtual terminal document.

Расположение, внешний вид и видимость курсора задаются для каждого буфера экрана независимо. The position, appearance, and visibility of the cursor are set independently for each screen buffer.

Атрибуты символов Character Attributes

Атрибуты символов можно разделить на два класса: Color и DBCS. Character attributes can be divided into two classes: color and DBCS. Приведенные ниже атрибуты определены в файле заголовка WinCon.h . The following attributes are defined in the WinCon.h header file.

attribute Attribute Значение Meaning
FOREGROUND_BLUE FOREGROUND_BLUE Текст содержит синий цвет. Text color contains blue.
FOREGROUND_GREEN FOREGROUND_GREEN Текст содержит зеленый цвет. Text color contains green.
FOREGROUND_RED FOREGROUND_RED Текст содержит красный цвет. Text color contains red.
FOREGROUND_INTENSITY FOREGROUND_INTENSITY Для цвета текста изменена интенсивность. Text color is intensified.
BACKGROUND_BLUE BACKGROUND_BLUE Фон содержит синий цвет. Background color contains blue.
BACKGROUND_GREEN BACKGROUND_GREEN Фон содержит зеленый цвет. Background color contains green.
BACKGROUND_RED BACKGROUND_RED Фон содержит красный цвет. Background color contains red.
BACKGROUND_INTENSITY BACKGROUND_INTENSITY Для цвета фона изменена интенсивность. Background color is intensified.
COMMON_LVB_LEADING_BYTE COMMON_LVB_LEADING_BYTE Начальный байт. Leading byte.
COMMON_LVB_TRAILING_BYTE COMMON_LVB_TRAILING_BYTE Конечный байт. Trailing byte.
COMMON_LVB_GRID_HORIZONTAL COMMON_LVB_GRID_HORIZONTAL Верхний горизонтальный. Top horizontal.
COMMON_LVB_GRID_LVERTICAL COMMON_LVB_GRID_LVERTICAL Левый вертикальный. Left vertical.
COMMON_LVB_GRID_RVERTICAL COMMON_LVB_GRID_RVERTICAL Правый вертикальный. Right vertical.
COMMON_LVB_REVERSE_VIDEO COMMON_LVB_REVERSE_VIDEO Обратить атрибуты переднего плана и фона. Reverse foreground and background attributes.
COMMON_LVB_UNDERSCORE COMMON_LVB_UNDERSCORE Знак подчеркивания. Underscore.

Атрибуты переднего плана задают цвет текста. The foreground attributes specify the text color. Атрибуты фона задают цвет, используемый для заполнения фона ячейки. The background attributes specify the color used to fill the cell’s background. Другие атрибуты используются с DBCS. The other attributes are used with DBCS.

Приложение может сочетать константы переднего плана и фона для отображения различных цветов. An application can combine the foreground and background constants to achieve different colors. Например, следующее сочетание приводит к отображению светло-голубого текста на синем фоне. For example, the following combination results in bright cyan text on a blue background.

FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE

Если константа фона не указана, фон будет черным. Если не указана ни одна из констант переднего плана, текст будет черным. If no background constant is specified, the background is black, and if no foreground constant is specified, the text is black. Например, следующее сочетание приводит к отображению черного цвета на белом фоне. For example, the following combination produces black text on a white background.

BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED

Каждая символьная ячейка буфера экрана хранит атрибуты цвета для цветов, используемых при отрисовке переднего плана (текста) и фона такой ячейки. Each screen buffer character cell stores the color attributes for the colors used in drawing the foreground (text) and background of that cell. Приложение может задавать данные цвета отдельно для каждой символьной ячейки, сохраняя данные в элементе Attributes структуры CHAR_INFO для каждой ячейки. An application can set the color data for each character cell individually, storing the data in the Attributes member of the CHAR_INFO structure for each cell. Текущие текстовые атрибуты для каждого буфера экрана используются для символов, которые последовательно записываются или выводятся высокоуровневыми функциями. The current text attributes of each screen buffer are used for characters subsequently written or echoed by the high-level functions.

Приложение может использовать функцию GetConsoleScreenBufferInfo, чтобы определить текущие атрибуты текста для буфера экрана, и функцию SetConsoleTextAttribute, чтобы задать атрибуты символов. An application can use GetConsoleScreenBufferInfo to determine the current text attributes of a screen buffer and the SetConsoleTextAttribute function to set the character attributes. Изменение атрибутов буфера экрана не повлияет на отображение уже записанных символов. Changing a screen buffer’s attributes does not affect the display of characters previously written. Такие атрибуты текста не влияют на символы, записанные низкоуровневыми функциями ввода-вывода консоли (например, WriteConsoleOutput или WriteConsoleOutputCharacter), которые явно задают атрибуты для каждой записываемой ячейки или оставляют атрибуты без изменений. These text attributes do not affect characters written by the low-level console I/O functions (such as the WriteConsoleOutput or WriteConsoleOutputCharacter function), which either explicitly specify the attributes for each cell that is written or leave the attributes unchanged.

Мы не рекомендуем использовать низкоуровневые функции для изменения атрибутов текста (в том числе атрибутов по умолчанию). Using the low-level functions to manipulate default and specific text attributes is discouraged. Чтобы задать атрибуты текста, используйте последовательности виртуального терминала. It is recommended to use virtual terminal sequences to set text attributes. Дополнительные сведения о предпочтительных последовательностях виртуального терминала см. в документе о классических функциях и виртуальном терминале . More information about preferring virtual terminal sequences can be found in the classic functions versus virtual terminal document.

Атрибуты шрифтов Font Attributes

Функция GetCurrentConsoleFont получает сведения о текущем шрифте консоли. The GetCurrentConsoleFont function retrieves information about the current console font. В структуре CONSOLE_FONT_INFO хранятся такие сведения, как ширина и высота каждого символа в шрифте. The information stored in the CONSOLE_FONT_INFO structure includes the width and height of each character in the font.

Функция GetConsoleFontSize получает данные о размере шрифта, используемые конкретным буфером экрана консоли. The GetConsoleFontSize function retrieves the size of the font used by the specified console screen buffer.

Мы не рекомендуем использовать функции для поиска и изменения данных шрифтов. Using functions to find and manipulate font information is discouraged. Придерживайтесь нейтральности шрифтов в приложениях командной строки, чтобы обеспечить совместимость с другими платформами, а также совместимость со средами размещения, которые разрешают пользователям настраивать шрифты. It is recommended to operate command-line applications in a font neutral manner to ensure cross-platform compatibility as well as compatibility with host environments that allow the user to customize the font. Дополнительные сведения о предпочтениях пользователей и средах размещения (в том числе о терминалах), см. в статье о стратегии развития экосистемы . More information user preferences and host environments including terminals, please see the ecosystem roadmap.

Оцените статью
Adblock
detector