Главная » Просмотр файлов » Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008

Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (779888), страница 22

Файл №779888 Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (Symbian Books) 22 страницаWiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (779888) страница 222018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 22)

A special optimization has been made for drawing bitmaps. When a bitmap is drawn,only the handle is passed from the application to WSERV. The serverlooks up the bitmap handle in the shared bitmap server and copies thebitmap in place to the screen.That’s the basics of the Symbian OS window server’s drawing mechanism. It’s effective for sharing the screen between applications, but insome cases, the mechanism doesn’t provide the flexibility and performance required for demanding use cases such as video rendering.

Toallow for these use cases, Symbian OS supplies a direct screen accessAPI to allow efficient access to the screen, which is covered in the nextsection.DIRECT SCREEN ACCESS753.6 Direct Screen AccessDSA API OverviewLibrary to link againstws32.libHeader to includews32.hRequired platform security capabilities NoneKey classesCDirectScreenAccess,MDirectScreenAccessGame developers wishing to avoid WSERV drawing and compositionmay use the direct screen access (DSA) API. In a multitasking, highlyconnected device, direct access to the screen could cause problems withthe display content being garbled by multiple applications drawing thesame area, effectively scribbling over one another.

Symbian’s WSERVprovides the DSA APIs to marshal access to regions of the screen andmanage clients wishing to draw their own content. This section introducesthe use cases for DSA, the APIs available and discusses the alternativetechniques.DSA facilitates two modes of access to the screen pixels by providing;• a CBitmapContext-based graphics context that maps directly ontothe screen without going through WSERV• access to the raw screen pixel data (which is useful, for example, forcustom bitmap copying routines).The example code which goes with this section demonstrates how touse both techniques.The key role of DSA itself is to coordinate clients and ensure that theconsistency of the display is maintained.

It notifies clients when to stopdrawing to a region and when they may resume. This aspect of DSA isvery important because the user interface frequently pops up dialogs toannounce events such as incoming phone calls or messages (as discussedpreviously in section 3.5.2).To use DSA, an application creates a window or control as usual andassociates a DSA session with that window. The DSA session providesthe information and methods required to draw to the screen.

Whiledrawing, a game will usually be exclusively in the foreground. If thissituation changes, the DSA session notifies the application of a possibleobstruction with an AbortNow() callback. When it’s safe to resume76GRAPHICS ON SYMBIAN OSdrawing, a Restart() callback is issued and the application can restartthe DSA session.3.6.1 Abort/Restart SequenceIt should be noted that abort or resume callbacks tend to occur in pairs.The sequence of events is typically as follows:1.The game is in the foreground, drawing graphics in a timer-basedloop to the whole screen.2.The operating system detects an event, such as an incoming call,and requests WSERV to display a dialog.3.WSERV calls AbortNow() on DSA clients.4.The game synchronously stops drawing.5.WSERV displays the dialog to indicate an incoming call.6.WSERV calls Restart() on DSA clients.7.The game updates its drawing code to take into account the newdrawing region provided by DSA.8.Another event is generated.

For example, the user ends the call.9.WSERV calls AbortNow() on DSA clients.10.The game synchronously stops drawing.11.WSERV removes the incoming call dialog.12.WSERV calls Restart() on DSA clients.13.The game updates its drawing region and resumes drawing to thewhole screen.As you can see, the process of aborting and resuming the DSA sessiontakes place on each change in window arrangements, and is not just amatter of aborting on appearance and resuming on disappearance.Well written applications should not continue drawing while theyare in the background. Applications may detect being moved to theforeground or background by inheriting from the mixin class MCoeForegroundObserver and implementing the functions HandleGainingForeground() and HandleLosingForeground(). A call to CCoeEnv::AddForegroundObserverL() registers the class to receive thecallbacks when the application goes into the background and comes intothe foreground.

The Symbian OS Library in your SDK can give furtherdetails on this mechanism.DIRECT SCREEN ACCESS77As Chapter 2 describes, a game should pause when losing focus, andall drawing and timers should halt. This is important to avoid draining thebattery.The following fragments of code show how to construct a DSA sessionin order to get a graphics context for the screen. The example code formspart of a full project, which is available for download from the SymbianPress website (at developer.symbian.com/roidsgame), the class diagramfor which is shown in Figure 3.6.<<interface>>MDirectScreenAccessCTimeriStatus : TRequestStatusRunL() : voidAfter() : voidRestart() : voidAbortNow() : void1<<realize>>CGfxDirectScreenAccess1iDirectScreenAccess : CDirectScreenAccessiWindow : RWindowiIsUsingGc : intStartL(aRect : TRect) : voidStopL() : voidEndDraw() : voidProcessFrameWritePixels() : voidProcessFrameGc() : voidSetupScreenDataL() : void11CDirectScreenAccessStartL() : voidGc() : CFbsBitGcScreenDevice() :CFbsScreenDevice11HardwareBitmap():RHardwareBitmapUpdate() : void11Figure 3.6 A simplified class diagram for the example DSA codeThe example contains class CGfxDirectAccess, which containsthe code below, and also implements a timer to periodically refresh thescreen (some of the details of the class are omitted for clarity in the printedversion but the code is complete in the version available for download).The DSA session is created with the following code:void CGfxDirectAccess::ConstructL(){CTimer::ConstructL();// Create the DSA objectiDirectScreenAccess = CDirectScreenAccess::NewL(iClient,// WSERV session*(CCoeEnv::Static()->ScreenDevice()), // CWsScreenDeviceiWindow,// RWindowBase*this// MDirectScreenAccess);CActiveScheduler::Add(this);}All of the parameters come from the CCoeControl or the UI environment singleton object (CCoeEnv::Static()).

The final parameter,78GRAPHICS ON SYMBIAN OSMDirectScreenAccess, is the class that will receive the AbortNow()/Restart() callbacks.Each time the DSA is required to start drawing to the screen, thefollowing code is called:void CGfxDirectAccess::StartL(){// Initialize DSAiDirectScreenAccess->StartL();// This example is hardcoded for a 24/32bpp display// See section 3.8 for more informationif(iDirectScreenAccess->ScreenDevice()->DisplayMode16M()==ENone){User::LeaveIfError(KErrNotSupported);}SetupScreenDataL(); // Obtain the base address of// the screen and other info (see below)After(TTimeIntervalMicroSeconds32(KFrameIntervalInMicroSecs));}Each time the game loop timer fires, RunL() is called, which draws aframe and then re-queues the timer.

At this point, it is safe to draw directto the screen until notified to abort.void CGfxDirectAccess::RunL(){if(iGcDrawMode){ProcessFrameGc();}else{ProcessFrameWritePixels();}EndDraw();iFrameCounter++;After(TTimeIntervalMicroSeconds32(FrameIntervalInMicroSecs));}ProcessFrame() is where all the custom drawing code goes. Theexample code contains two methods for generating content: ProcessFrameGc(), which uses the direct screen graphics context to draw a fewlines and ProcessFrameWritePixels(), which writes pixel valuesdirectly.3.6.2 Drawing to the Screen Using a Graphics ContextThere are two major advantages of using Gc() on a DSA session:• Standard drawing functions can be used without specializing forscreen mode.DIRECT SCREEN ACCESS79• Drawing can be clipped to a region, making it suitable for partiallyobscured drawing.The following code demonstrates drawing directly to the screen usingthe DSA graphics context:void CGfxDirectAccess::ProcessFrameGc(){CBitmapContext* gc = iDirectScreenAccess->Gc();TPoint p1(0,0);TPoint p2(0,iDsaRect.Height());for(TInt x=0; x<=iDsaRect.Width(); x++){TRgb penColor((x+iFrameCounter);gc->SetPenColor(penColor);gc->DrawLine(p1,p2);p1+=TPoint(1,0);p2+=TPoint(1,0);}}Figure 3.7 shows the output to the screen of the previous examplecode.

Характеристики

Тип файла
PDF-файл
Размер
2,71 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6451
Авторов
на СтудИзбе
305
Средний доход
с одного платного файла
Обучение Подробнее