Showing posts with label graphics. Show all posts
Showing posts with label graphics. Show all posts

Wednesday, July 16, 2014

Toolbar and memory leaks

Hi guys! :)

During the last week, the most spectacular part of my progress was the implementation of some functionalities on the toolbar. Now, you can switch between normal, colorful display, and "mono-color" mode, which is there to support players with seeing difficulties. Let me illustrate it with two pictures:


Pretty kind of the original developers, isn't it? :) Besides that, thanks to ScummVM's another great feature, now you can enable this colorblind mode not just by clinking the purple sphere on the toolbar (next to Vincent's inventory), but you can also configure the engine right from the launcher, so it always runs in this mode.


To do so, I only had to add this static array to detection.h:

static const ADExtraGuiOptionsMap optionsList[] = {
  {
   GAMEOPTION_COLOR_BLIND_DEFAULT_OFF,
   {
    _s("Color Blind Mode"),
    _s("Enable Color Blind Mode by default"),
    "enable_color_blind",
    false
   }
  },

  AD_EXTRA_GUI_OPTIONS_TERMINATOR
};

And just pass it as an argument to the constructor of my subclass of AdvancedMetaEngine. It's quite awesomely simple, isn't it? :)

Another feature I added is that now you can also switch between speech-only and text-only mode using the little ear and eye icons next to the main switch on the right side of the toolbar. Of course, you can still stick with both, simply clicking on the mouth icon above the two. :)

Besides that, my last week mostly spent with fixing various newly found bugs and patching up the engine in different places so it (hopefully) leaks less memory now.
In practice, I will keep on doing that during the next week, since now (many many thanks to Arnaud) all the scenes in the game are reachable and most of them are fully or at least partially translated too. So we are absolutely not far from saying that the game is in a completable state, but there are still a lot of showstopping bugs what need to be tended

See you soon! :)

Monday, June 9, 2014

Info line, event handling and winking miniatures

Hey all! :)

First of all, let me show you the most significant progress of the week! Then I'll talk about our present difficulties.

So, the new things is the so-called 'info line':
It's the brown strip on the top of the panel at the bottom of the screen, showing 'Wacek'  - the name of our hero. :) (Arnaud decided to call him Vincent in the English translation, since that's the closest name we've got to the original.) The purpose of this line is very common in adventure games: it shows the name of the thing which the player is hovering his mouse over at the moment.

What I left out from my last post: you may also notice that the face of our protagonist at the bottom left corner of the screen is now in color. I can tell you that the small icon is also animated now: it winks and makes various faces. (You can check this in motion in my last video.) As I perceived, it's intended to display which one is the currently active character in the game, and you will be able to switch between them by clicking on their icons. (Since in the first screen you only got Vincent, only his portrait can be active.)

Now my problems:
As you can see, the misplacement of numerous objects is still a great problem. Also as I implemented the info line, which checks the screen and the coordinates of objects on it, it turned out (not unexpectedly) that the wrong handling of the z dimension manifests there also. Even worse, as I implemented the event handling of the mouse, the problem (also not so unexpectedly) came to the surface again. So now I am pretty much stuck because of that. But everything has a bright side: I also discovered what might be utterly wrong. I have a very strong suspicion that the problem is not with the numeric representation of the coordinates (that I use doubles for storing the values instead of fixed-point integers, as the original did), but with the loading of them.

Let me show you it in more depth! The problem is, that CGE2 uses some - currently a little bit mythical - reference coordinates called "eyes" in almost every function which computes the final coordinates of objects. All I could found about what this eye supposed to be is a comment in one of the original sources which calls it "camera". So I suppose it's purpose is to center the view of each scene at a particular point. And THAT'S THE PROBLEM. The original has this code for the loading of the "eye" value for each room:

static void LoadTab (void)
{
  int i;
  V2D::SetEye(Text[240]);
  for (i = 0; i < CAVE_MAX; i ++) EyeTab[i] = V2D::Eye;
  INI_FILE f(TAB_NAME);
  if (!f.Error) f.Read(EyeTab, sizeof(EyeTab));
}


To understand the problem fully, here's also the declaration of EyeTab:

V3D    EyeTab[CAVE_MAX];

And since the original stores the coordinates in V3D in the form of three FXP's (the fixed-point integer representation which we can't reimplement because we don't have the full source code of it), I wasn't able to manage to mimic it correctly. The best I've got so long is that I set all values of EyeTab to V2D::Eye which is stored plainly as numbers in a source file, like this:

240=160, 100, -200 ; camera
(See? The "camera" comment!)

...and use this one for every screen. But, as you may see, this causes all of the coordinate computations to go wrong, and here we are: I am stuck.

So, my most urgent task currently is to fix this loading (with help from Arnaud and Paul). Then, I'll have to find the point where the event triggered which gets Vincent out of his seat, and then... Who knows? Hopefully there won't be much to stop me anymore from rapid progress... :)

Monday, June 2, 2014

An almost correct display of the first screen and a bit of mouse handling

As the very verbose title of this post described, that's what you will see in this short video:


Sfinx first scene - ScummVM from Peter Bozsó on Vimeo.

You may have noticed a "little" problem above. Yes, some of the sprites are placed totally wrong on the screen. Namely it's the door, the shades on the window, the fan on the ceiling, and the wardrobe to the right. Besides that, everything seems fine, and you might have seen that I hovered the mouse cursor over the screen - yes, that's also implemented now. :)
(Also the sounds are "a bit" loud compared to the music of the game, but it really won't be a hard-to-fix thing, it's just out of my scope of attention right now.)

Back to the problem of the misplaced objects:
As far as we were able to perceive it with Arnaud, the problem is about the z-coordinates of the objects. In Sfinx, everything that is placed on the screen has not 2, but 3 coordinates. These are the traditional x and y, and there's also a z axis which describes the distance of each object from the screen - where the z-coord is equal to 0 and the further the object is, the greater the number is.
The problem here is that the original engine used a quite weird fixed-point implementation to store the coordinates of things, and until now I wasn't able to properly reimplement or mimic it completely. Right now, it's on the top priority list of ours and hopefully we will get over it soon.

Looking at the bright side, even if it's ugly, it's not an obstacle which would pull back my progress. As you may see, it didn't hold me back from implementing the basic mouse handling of the engine (which blessedly has A LOT in common with CGE1), and I am not far from actually handling the events fired by mouse-clicks. From that point, a bunch of opportunities will open, and I will be able to dive into the depths of the command handling (Snail) again.

So, these are my plans for the upcoming week, see you soon! :)

Sunday, May 25, 2014

Roaring sphinx

Hey all! :)

Before boring you with the little details of my last week's work, let me show you the actual output of the engine:


Sfinx intro - ScummVM from Peter Bozsó on Vimeo.

Promising, isn't it? :)

Actually, it is, very much, and even more. Compared to Avalanche (which was my last year's work), CGE2 engine is more advanced, and right because of that, it needed much more work to make it show us something than the previous one. On the other hand, now I have a much deeper understanding of the whole structure of the code and I also have some plans how to proceed with the engine as a whole. Finally, I've got a grab on it and it feels safe, especially in the light of the past few weeks' anxious coding. :)

Let me explain it more deeper and make the comparison cleaner!

In case of Avalanche, all I had to do is implementing the picture loading code, then choose and put the right pictures on the screen, smash the whole thing into a big main loop with the keyboard and mouse event handling, and here you go: a half-working game, with the main character running around on the screen. (Of course, I struggled much more with it anno, and it was certainly more complex, but in a nutshell, that was that.) All in all, Avalanche was more appropriate to develop step-by-step, concentrating only on one thing at a time and bothering with the game logic only when almost all was said and done regarding the graphics.

In comparison with my previous work, CGE2 engine is more complex and was harder to find a solid grab on it. It handles things differently: it has very little, almost no hard-coded logic (which took up the greatest part of Avalanche by the way), but has a pretty scpript parser system, Snail.

I was lucky, I didn't have to implement the guts of the picture loading and drawing from scratch, using the ASM code in the original, because Arnaud and Paul did it for me during the implementation of CGE1. I only had to revise the fundamental classes and add/remove or modify function slightly to fit into CGE2's different coordinate or NPC-handling. The really hard part was to track down the inner workings of the engine through the not-so-verbose variables (there are tons of variables named "a" or "b", for example) and the not always logically named or placed functions ("getCave()" - What cave?!). Nevertheless no matter how I tried, which perspective I regarded the engine from, I always ran into Snail (called CommandHandler in the ScummVM version), which is clearly far from being complete, through the fundamentals of it are now settled, and as I concentrated on the parts what are used during the displaying of the intro, now it's done and working as you may have seen above. :)

After deciphering it, the internals of the command parser are not so hard to understand. Actually, every Sprite has a file with the extension of SPR, and those what are more than only one static image (For example the backgrounds are consist of only one picture. Yes, the backgrounds are considered as sprites by the engine as well.) has a bunch of information in them about the display sequence of the animation of the sprite. For example, 00SFINX.SPR, which contains the information of the roaring sphinx animation has a pretty readable table of  the to-be-executed commands of the sprite, right under the "[near]" header in it. Especially, if you check this table of constants for the better understanding of the commands listed. So practically the intro animation is a sequence of pictures with sounds displayed right after each other, with a certain amount of delay inserted between each of them.

Luckily, I was also able to copy the main loop of the game from the ScummVM version of CGE1, and I only have to adjust some delay time to match the output of DOSBox.

My plan for the upcoming week is to proceed with the implementation of the main loop of the game and see what is needed to be implemented in order to display the first scenes of the game and very importantly: the NPC's on it and the animation of them.

See you soon! :)

Thursday, May 15, 2014

Invisible progress

Hi all!

Sorry for not posting for so long. The thing is that  I didn't want to write again until I can present you guys something visible again, but now I just don't want to postpone any more giving some signs of life about myself.

After Eugene brought it up, we reconsidered our approach with Arnaud about CGE2. Even through we decided against merging it with the previous version of the engine during the development, we did made up a new, a little bit different plan from the one that is in my proposal. Instead of concentrating immediately on the display of the scenes, we decided that I should try to implement the intro animation of the game first. We think it's important now, since as Eugene (and me) pointed it out, the two engines are painfully similar, so we should first map the differences because it could speed up my progress significantly. If I'd know what parts of CGE1 are completely reusable (like the sound code was), and what need certain modifications, I'd be able to just copy-paste the analogous parts and concentrate on the ones what need more attention.

For example, right after I started to work on the intro animation, it turned out that the graphics code itself is in the second group: even if it's very similar to it's predecessor, it uses a new form of coordinate representation and the storing and loading of sprites is very different from CGE1, even through the displaying of the pictures share the same code. (Actually, EVERY picture in Sfinx is a sprite, or part of a sprite's sequence of pictures.) For the coordinates, CGE2 introduces V2D and V3D, and for the sprites, it uses a pointer collection of them: Spare. I had great difficulty with the latter, since the original code uses an ugly DOS-specific hack for the implementation. I think I finally got it right and mimicked it in the right way. Anyway, time will tell...

If you check my repository, you can see that I am working with full power on the finishing of the implementation of movie(), which is responsible for displaying the intro animation. My next aim is to (at least partially) implement Snail, the script parser, which is responsible for the displaying of the animation by drawing the pictures of it one after the other.

Stay tuned guys! Hopefully in my next post I'll be able to give you even a roaring sphinx! ;)

Thursday, May 1, 2014

Splash screen with a little music

Progress-progress-progress! :)

As the title describes, during the past week I was able to display the splash screen at the beginning of the game (right before the intro), and play some MIDI formatted music. Let's see the result of it:

Cool, isn't it? :) (I know you can't hear the music, but please imagine some eight-bit beeping playing for the full experience. :D)
The key of my fast progress is that as we augured with Strangerke before, I was able to use most of the graphic and the sound code from CGE1 in my engine. In truth, it only needed a little bit of hammering here and there, and the biggest differences were the different file names of the music files and that Sfinx uses a screen resolution of 320x240 instead of Soltys' 320x200. I also included the WAV player in my engine, but it's testing will wait until I implement "Snail" (the script parser), because it's only used there. But, if everything goes as planned, there won't be much more difference than the different file names again.
I'd explain the working of the sounds and the graphics here, but since it's working for now, I didn't really spend much time with understanding what's under the hood yet. I am convinced that there'll be difficulties with the further implementation, and sooner or later I'll have to fully understand and modify these parts of the engine too, so I leave the explanation for that time. For now, my aim is to copy as much as I can from CGE1, get as much as possible of CGE2 working, and then modify and polish the resulting code.

See you later! I hope I'll be able to show you the intro animation or some scenes from the actual game next time! :)

Wednesday, March 12, 2014

Summary

Hey all! :)

Yes, it will be a summary of my past half year of coding on ScummVM, and practically a summary of my latest additions to the Avalanche engine. I'll go through a list of the most significant and spectacular modifications of the engine and describe them one-by-one. Of course, during that period, there were a lot of bugfixes (Even some bugs of the original were fixed!), and other additions and refactorings, but I won't mention all of them.
So... let's get started! (The pictures will become enlarged once you click on them.)

1. Game of Nim:
This was the first thing I implemented since my last post. The graphical part of it wasn't particularly hard, but the game logic got me scratching my head for a while. In the end, the Wikipedia page of the game and a lot of patience helped me trough all the troubles. You can find the - not so nicely refactored - sources in our GitHub repo.

2. Ghost Room:
Basically, it is a little animated scene, which gets triggered when you make Avvy walk to one of the "hidden" corridors of his castle. He (represented by the two grey, little floating eyeballs) walks in innocently, then got scared by the descending ghost and other appearing freaks, so he hastens out of the room. It's was pretty fun to implement, even if I had to fight a bit with the picture of the ghost to decode and display it properly.

3. Shoot em' Up:
This one may need some description: It's a basic shoot em' up mini-game, where your aim is to shoot the bad guys in the pallets. If a criminal doesn't get hit in the face with a rotten vegetable repeatedly in a certain amount of time, it will escape, and your score decreases. The more guys you keep in the pallets when the time counter reaches 0, the more points you'll get. Also, you gain score for each successful shoot, and lose some if you hit a pedestrian by accident. It's wasn't hard to implement, since I've got everything for the graphics, and just a little bit of effort needed to understand the logic behind the mini-game itself.

4. Help:
Of course, there's also the Help menu. The implementation of it was pretty straightforward, the only difficulty was with the display of the big fonts, but I came over it by time and effort too.

5. Main Menu:
 
Last but not least, I finally fought with the menu, and got out as a winner. The biggest problem here were the display of the little buttons on it, because they are all drawn together, not one-by-one, but plane-by-plane. It also uses a different display resolution then the rest of the game, but it was really a minor thing after I solved the mystery of the icons. :)

That's all folks! There are still some missing bits of the game, which you can see on the TO-DO section of the engine on our wiki, but I never said I stopped working on them. :)

By the way, I submitted my proposal just today, and hopefully I'll get accepted to this year's GSoC as well so I'll be able to blog about my progress with CGE2 engine soon. Fingers crossed! ;)

Monday, September 2, 2013

A completable game

Yes, that's it! Avalot d'Argent is actually in a completable state now! Yaaaay!

A few words about the past week: In truth, I can't say much more than the previous time. I really didn't do anything spectacular, or made actually new code, I mostly spend the week with bugfixing.
Since the game has a very unique storyline, it was hard for me to complete the original one in DOSBox, but with the help of the Pascal code, and some paper and pen (I had to draw a smaller map for one part of the game.), I finally finished it. After that, it was not so difficult to find the bugs in my code. At least it was much easier to find them, then to repair some of them. To be honest, most of the problems were mismatched array indexes and numeric constants, but it didn't make the solving of them any easier.

After the game was completable, I plunged into the implementation of the drop-down menu. As the result of that, now I can proudly present you a screenshot of it and the fact that it's fully functioning and can be controlled with the mouse! (The keyboard support is coming soon as well.)
The implementation of it in fact, wasn't that hard, since I had every tool for it from previous parts of the engine. (For example the plotting of text to the screen, and ScummVM also already implemented the drawing of colored rectangles to the screen. I really didn't need much more than these, but a lot of patience.)

That's all for now. The last weeks of Summer of Code will be spent with heavy renaming and refactoring of my code, so by the end of the program, we'll be able to merge not only a working, but a working and (hopefully) readable and understandable engine into ScummVM! :)

Monday, August 12, 2013

Bubbles

Those connected to speaking!
And I subtly showed you an entirely new (and working) room of the game! Hah!
I am writing this post because I am leaving for three days tomorrow and I'll only come back Thursday night at best (but Friday morning is more possible). So let me sum up for you the progress of the past few days now!
First and foremost let me talk about the thing which needed the most work: the speech bubbles.
In truth, the actual drawing of them wasn't really hard. ::Graphics::Surface::fillRect() and Graphics::drawdrawPieSlice() did the most of the work. The thing I had to implement was the "tails" of the bubbles. For that, I introduced a new function, Graphics::drawTriangle():
void Graphics::drawTriangle(::Graphics::Surface &surface, Common::Point *p, byte color) {
 // Draw the borders with a marking color.
 _scrolls.drawLine(p[0].x, p[0].y, p[1].x, p[1].y, 255);
 _scrolls.drawLine(p[1].x, p[1].y, p[2].x, p[2].y, 255);
 _scrolls.drawLine(p[2].x, p[2].y, p[0].x, p[0].y, 255);

 // Get the top and the bottom of the triangle.
 uint16 maxY = p[0].y, minY = p[0].y;
 for (byte i = 1; i < 3; i++) {
  if (p[i].y < minY)
   minY = p[i].y;
  if (p[i].y > maxY)
   maxY = p[i].y;
 }

 // Fill the triangle.
 for (uint16 y = minY; y <= maxY; y++) {
  uint16 x = 0;
  while (*(byte *)_scrolls.getBasePtr(x, y) != 255)
   x++;
  uint16 minX = x;
  uint16 maxX = x;
  x++;
  while ((*(byte *)_scrolls.getBasePtr(x, y) != 255) && (x != 639))
   x++;
  if (x != 639)
   maxX = x;
  if (minX != maxX)
   _scrolls.drawLine(minX, y, maxX, y, color);
 }

 // Redraw the borders with the actual color.
 _scrolls.drawLine(p[0].x, p[0].y, p[1].x, p[1].y, color);
 _scrolls.drawLine(p[1].x, p[1].y, p[2].x, p[2].y, color);
 _scrolls.drawLine(p[2].x, p[2].y, p[0].x, p[0].y, color);
}
It's clearly not the most optimized, nor the smartest code, but for now, it'll do. The operation of it is quite simple: First, we draw the borders of the triangle with a marking color. (255 is as good as any number bigger than 15, since our EGA palette supports only 16 colors.) After that we search for the highest and the lowest point of the triangle, and moving from the top to the bottom, we go trough every relevant line of the screen and fill the selected parts of it with the color of the shape. In the end, we redraw the borders - now with the desired color.

Finished with the implementation of it, the next thing I had to pay attention was the printing of the characters to the bubbles. Since the original code used Pascal's outtextxy(), I had to come up with something to replace it as accurately as I could. As a solution, I introduced Graphics::drawText():
void Graphics::drawText(::Graphics::Surface &surface, const Common::String &text, fontType font, byte fontHeight, int16 x, int16 y, byte color) {
 for (byte i = 0; i < text.size(); i++)
  for (byte j = 0; j < fontHeight; j++) {
   byte pixel = font[(byte)text[i]][j]; 
   for (byte bit = 0; bit < 8; bit++) {
    byte pixelBit = (pixel >> bit) & 1;
    if (pixelBit)
     *(byte *)surface.getBasePtr(x + i * 8 + 7 - bit, y + j) = color;
   }
  }
}
It's a very simple function, which's only purpose is to draw the given text with the given font to the given place on the given surface with the given color. (GIVENGIVENGIVEN!!!) It works like that: in font (which has the type of fontType), we store a mask for every character. The function simply search for every character's mask in this array, and then using that, the coordinates and the color, draws the picture of the character to the surface. Passing the height of the font is needed, because Avalanche uses 3 types of font and 2 of them has the height of 12 (used on the scrolls), but the third one (used on speech bubbles, the drop-down menu and the text input field) is only 8 pixel high.
Using these two functions it was super easy to implement the speech bubbles, I only had to center the texts a little bit in Scrolls::bubble().

Besides these improvements, I managed to implement a lot of the game logics, so now the first 4 rooms of the game are complete and playable, all the NPC-s on these screens are fully functioning, and everything is basically very fancy. I could even make Spludwick (the mage on the screenshot above) follow Avvy around the room as in the original game.

That's all for now! I hope next time I will be able to tell you about how I managed to implement the handling of the mouse in the game and I am planning to get done with the drop-down menu right after that. See you soon!

Thursday, August 8, 2013

Arces

They are everywhere! Just like in this picture:
As you can see, there are two significant alterations since my last post: an error message on the screen in the embrace of a scroll, and the hands of the clock. Let me start with the former!

The complete "scrolldrivers" are not implemented yet, and at the moment my engine only can display these gray scrolls with black (mostly error) messages in them. Later, with the handling of multiple sprites on the screen, there'll come the speech bubbles, since they have a very similar algorithm.
My idea to implement the scrolls was quite simple. I introduced a new surface object (Graphics::_scrolls) which I use like this: When a scroll is needed to be drawn, we copy the whole screen to _scrolls (which obviously has the very same size as the screen, 640x200), then draw the scroll to this copy (it's method depends on the type of the scroll - currently the engine only supports this one) and do the followings:
::Graphics::Surface temp;
 temp.copyFrom(_vm->_graphics->_surface);
 _vm->_graphics->_surface.copyFrom(_vm->_graphics->_scrolls); // TODO: Rework it using getSubArea !!!!!!!
 _vm->_graphics->refreshScreen();

 Common::Event event;
 while (!_vm->shouldQuit()) {
  _vm->getEvent(event);
  if ((event.type == Common::EVENT_KEYDOWN) && ((event.kbd.keycode == Common::KEYCODE_ESCAPE) || (event.kbd.keycode == Common::KEYCODE_RETURN) || (event.kbd.keycode == Common::KEYCODE_HASH) || (event.kbd.keycode == Common::KEYCODE_PLUS)))
   break;
 }

 _vm->_graphics->_surface.copyFrom(temp);
I hope the code speaks for itself clearly enough, but if it does not, here's a brief explanation: We make a backup for the actual screen, then draw the content of _scolls to _surface, and put _surface's new content to the screen using Grahpics::refreshScreen(). After that we enter an (almost) endless loop, which checks for keyboard input, and if the user hits the proper key, we stop presenting the scroll: we copy the original content of _surface back. I don't call refreshScreen() again here, since the main loop of the game will does it anyway.
After I talked about the methodology of the scroll system, let me say a word or two about the drawing of this particular type of scrolls. It all happen in Scrolls::drawscroll(). The gray body and the red borders of the scroll were easy enough, they are just simple ::Graphics::Surface::fillRect() calls with the proper parameters. Putting the text on the scrolls was a very easy task as well, since it's almost completely the same as I used previously in Dropdown::chalk(). The real pain came when it was time to draw the corners of the scrolls. For that, I had to reimplement Pascal's procedure arc(), since ScummVM doesn't have anything like that. For that, I used Free Pascal's InternalEllipse() with some minor modifications. Basically, it does the very same under the name of Graphics::drawArc(). After implementing that, I could also recreate the behavior of Pascal's pieslice() in Graphics::drawPieSlice() calling drawArc() multiple times with smaller radius every time than before. (As always, you can check out both of them here.) With the use of these two I was able to implement the drawing of this type of scroll fully.

Right after that came the idea: Why not hit two birds with one stone and implement the clock as well? I tried to work around the use of Pascal's arc() in this case before, but the result was catastrophic. Now I have Pascal's arc() in C++! Why not try again? So, the trying went very well as you may see. But because the drawing of the clock used the full functionality of arc() (which in Pascal stored the coordinates of the end point of the arc in a variable, which was accessible with GetArcCoords()), I had to add a return value to Graphics::drawArc() which presented the very same value as GetArcCoords() did in Pascal. After that it was very easy to implement the hands of the clock. You can see the final functions for yourself  in Graphics.

Wednesday, July 31, 2013

Mostly parsing and magics

Let me start this post with our usual screenshot!
As you may see, there are a lot of changes and improvements since my last post. I'll tell you the story of the last week in the followings, so prepare for a smaller wall of text, a lot had happened! ;)

The first and most obvious thing is that I took many ScummVM members' advices and doubled the screen height again. We all agreed that it will be it's final size. The algorithm was pretty easy, I only had to update Graphics::refreshScreen() a bit. (Oh, and I renamed the class Graph to Graphics. It was sev's idea and I agree with him. Now it reflects much more the purpose of the class, and I added so much things to it during the past days that it lost all of its connections to the Graph unit in Pascal, so there's really no point in keeping the old name.) So, the new refreshScreen():
void Graphics::refreshScreen() {
 // These cycles are for doubling the screen height.
 ::Graphics::Surface picture;
 picture.create(kScreenWidth, kScreenHeight * 2, ::Graphics::PixelFormat::createFormatCLUT8());
 for (uint16 y = 0; y < picture.h / 2; y++)
  for (uint16 x = 0; x < picture.w; x++)
   for (byte j = 0; j < 2; j++) 
    *(byte *)picture.getBasePtr(x, y * 2 + j) = *(byte *)_surface.getBasePtr(x, y); 

 // Now we copy the stretched picture to the screen.
 g_system->copyRectToScreen(picture.pixels, picture.pitch, 0, 0, kScreenWidth, kScreenHeight * 2);
 g_system->updateScreen();

 picture.free();
}
I think the comments make it pretty understandable. I still work with the original 640x200 resolution when loading pictures to the screen (If you check out graphics.h, you can see it for yourself in the form of kScreenWidth and kScreenHeight.), but when I show the actual output, I draw every line twice, so it's like we have a screen height of 400.

I also want to mention that I reworked loading of pictures a little bit in the form of loadPictureGraphic() and loadPictureRow(). The names of these functions came from here, referring to their behavior. Obviously the sooner one loads graphical data that uses "graphic-planar EGA data" as input and the latter one is for loading "row-planar EGA data". In the end, both produce a Surface object with the same format as output. This revision was needed because I had to use these two methods frequently and it made the whole thing much convenient since now Graphics::drawPicture() only accepts a Surface object and two coordinates, and draws the input picture (coming from one of the loading functions or simply by copying parts of the already drawn screen) to the given place. You can check out the current source code of these algorithms in graphics.cpp. I wouldn't describe them further here, because I talked about their operation in my previous posts a lot.

The next thing I spent a large amount of time with during the week was parsing. Since the original code was a bit hard to understand it took me more time to look through all of it than the actual coding, but finally it's done and working! :)
I introduced a new class, Parser (you can check this out here and here), which is practically a rework of Basher. One of my further plans is to completely get rid of Basher and move everything from it to Parser after renaming them. The "funny" thing is that the actual parsing is not done here (yet), but in Acci::parse(), and Acci::do_that() takes actions based on the result of the parsing (run animations, move characters, etc.). Parser now is only for processing the keyboard input and the handling of the visualization of it in a little command line under the main picture and over the toolbar. (You can see it in the screenshot at the top of the post, I wrote "get up" into it.) It's also my plan to move at least these two functions from Acci to Parser, and even more data, if I find out that they are only connected to parsing.
I wouldn't insert any code samples connected to parsing here now, since parse.h and parse.cpp contains quite readable code in my opinion, and Acci::parse() and Acci::do_that() is in such a bad condition that I don't want to advertise them at all. (:D) Let it be enough that they are called by Parser::handleReturn(), and they work properly. But a certain rework will be needed soon if I want to keep my code readable... Anyway, if you want to check out them in their current forms, here you go.

Also, not only the text input is working now (By using that you can wake up Avvy typing in "wake" or "wake up" and get him out of bed typing "stand", "stand up", or "get up". Other commands may don't work properly or don't work at all at the moment.), but you can move Avvy around in the first room of the game using the cursor keys or the home/end/page up/page down buttons executing diagonal movements with them. You can also control him with the numeric keyboard and stop him by hitting the numeric key '5' or hitting the direction key he is facing right now again.

We arrived to the second greater part of my last week's work: the MAGICS!
No, not turning people into toads or summoning a demon from Burning Hell using ScummVM, nothing like that. It's the name of the system in Avalanche which forbids the characters to cross the border of the screen and walk right on the toolbar for example. Let me illustrate it with the help of two screenshots!

As you may have noticed checking out Graphics, I added a new Surface object to the engine named _magics. This is the one which stores the image to the left. The white lines on it means the edges of the screen what Avvy (or any NPC) cannot cross.
They are drawn to this Surface in Lucerna::draw_also_lines(), using the data stored in Gyro::lines[] - which's content is loaded in Lucerna::load_also() amongst many other room-related data. If you'd like to read more about this matter, you can always check out the wiki pages of the original author.
So basically the algorithm in triptype::walk() is the following: we check if the next step of the character would cause him to cross a line on _magics and if it would, we simply stop the character.
Vigilant readers may have noticed the blue colored rectangle on the bottom left of the pictures, where the door is. It marks a different kind of "magic", which means that if we cross these lines, we want to leave the room.

My plans for the following weeks are making the speech bubbles (the so-called scrolls), the drop-down menu on the top and the transportation between rooms work. The drawing system will also need a certain rework, since now it can handle only one sprite per screen.

Tuesday, July 23, 2013

Avalot lives!

Yes, he does!
As you may have noticed, the menu bar on the top is also visible. So I can say that everything is shown what is needed for the first scene of the game! (Expect the clock and some status leds to the left of it. That will remain for later as I mentioned before.) Oh, and I got rid of that disgusting pink blanket as well and gave it the pleasant color of flesh! ;)

Let me speak first about Avvy, since it was a bit tricky to make him (and consistently the other characters during the game) appear, and I would have certainly gone mad if fuzzie didn't help me with a lot of explanations and suggestions.
So I added a new function to Graph: drawSprite(), which is - obviously - responsible for drawing the sprites of a character. The data of all characters are stored in an array named 'tr' located in Trip, which have the type of triptype. I made a little revision of this. The original code didn't divide data about a character in any ways, so I did. Everything connected to the display of a sprite (actually, the data what drawSprite() uses) went to a new type named SpriteInfo in grap.h and triptype got a new data member with the name of _info and the type of SpriteInfo. (You can take a look at these types and the array named 'tr' in Trip and Graph.)
The next thing was to implement Graph::drawSprite(). Here came in handy the new type I introduced, because now we only have to pass this data member of a triptype variable to the function and it can work using only these informations. Here it is:
void Graph::drawSprite(const SpriteInfo &sprite, byte picnum, int16 x, int16 y) {

 /* First we make the pixels of the spirte blank. */
 for (byte qay = 0; qay < sprite.yl; qay++) {
  byte *mask = new byte[sprite.xl];

  for (byte qax = 0; qax < sprite.xl; qax++) {
   byte count = qax / 8;
   mask[qax] = ((*sprite.sil[picnum])[qay][count] >> ((7 - qax % 8)) & 1);
   if (mask[qax] == 0)
    *getPixel(x + qax, y + qay) = 0;
  }

  delete[] mask;
 }

 /* Then we draw the picture to the blank places. */
 uint16 i = 0; // Because the original siltype starts at 5!!! See Graph.h for definition.

 for (byte qay = 0; qay < sprite.yl; qay++)
  for (int8 plane = 3; plane >= 0; plane--) // The planes are in the opposite way.
   for (uint16 qax = 0; qax  < sprite.xl; qax += 8) {
    byte pixel = (*sprite.mani[picnum])[i++];
    for (byte bit = 0; bit < 8; bit++) {
     byte pixelBit = (pixel >> bit) & 1;
     *getPixel(x + qax + 7 - bit, y + qay) += (pixelBit << plane);
    } 
   }
}

Use of image masks
I think the comments and mostly the code speak for themselves, but here's a brief summary of it:
The method consists of two parts: before the drawing, we have to blank the pixels of the sprite to black (0). Here, we use the array 'sil' which contains the mask for it. After that we can go through the image itself to draw it plane-by-plane, which is identical to the method I showed you before in my previous posts. You can read about the topic of image masks here in a bit more depth. Note that x and y here are the coordinates of the upper left corner of the rectangle which is an invisible frame around the sprite. (That was what you saw in my previous post in the color of magenta.)

The next thing I implemented was the changing of the disturbing pink color to a smoother 'flesh color'. It wasn't a big deal, I only had to set two palette entries what I did in Graph::flesh_colours(). (Keeping the name of the original function, but moving it from Trip to Graph.)

The third thing was the menu on the top of the screen. I have to tell you, it doesn't operate at all yet, it's only drawn to the screen so we don't have a blank line there. But of course it wasn't as easy as a bunch of writelns or couts. I had to draw the subtitles as pictures to the screen and they had a very nasty way of working. It's all done in Dropdown::chalk():
void Dropdown::chalk(int16 x, int16 y, char t, Common::String z, bool valid) {
 byte ander;
 if (valid)
  ander = 255;
 else
  ander = 170;

 for (byte fv = 0; fv < z.size(); fv++)
  for (byte ff = 0; ff < 8; ff++) {
   byte pixel = ~(_vm->_gyro.little[z[fv]][ff] & ander); // Note that it's the bitwise NOT operator!
   for (byte bit = 0; bit < 8; bit++) {
    byte pixelBit = (pixel >> bit) & 1;
    *_vm->_graph.getPixel(x * 8 + fv * 8 + 7 - bit, y + ff) = pixelBit + (pixelBit << 1) + (pixelBit << 2);
    // We don't have to bother with the planes, since they all have the same value. See the original.
    // Note that it's the bitwise OR operator!
   }
  }

 if (! z.contains(t))
  return;
 else {
  byte fv;
  for (fv = 0; z[fv] != t; fv++); // Search for the character in the string.
 
  // Similar to the cycle before.
  byte pixel = ~ ander;
  for (byte bit = 0; bit < 8; bit++) {
   byte pixelBit = (pixel >> bit) & 1;
   *_vm->_graph.getPixel(x * 8 + fv * 8 + 7 - bit, y + 8) = pixelBit | (pixelBit << 1) | (pixelBit << 2);
  }
 }

 _vm->_lucerna.blitfix();
}
At least here I didn't have to blank out the pixels or bother with planes and these made the whole thing a little bit easier. (In truth understanding the original Pacal code was much harder then implementing it in C++ again.) There is two stances of a menu item: valid (black) and invalid (grayed out). In truth, there's a third one: highlighted, but since the menu doesn't operate yet, I didn't have to bother with the implementation of it. Depending on the current state of the menu item, we get the pixels of the characters with bitwise operations. According to the original code, the planes all have the same value (since in dropdown.pas chalk() does the same for every plane), and since we have 1 byte for every row of a character in 'little', all the characters are 8 pixels wide as well. After that comes the underlining of a character of every text with a very similar algorithm and that's it: we are done. We call chalk() for every menu item after drawing a gray bar on the top of the screen and finally everything looks fine.

Implementing the drop-down menu system will remain for after midterm. My main concerns now are to make Avvy move around in the room with the help of the arrow keys, and if possible, put him into the bed at the beginning of the game, and make the speech bubble system work along with text input, so I'll be able to display the first few animations of the game (when Avalot wakes up to the screaming of her wife). I hope I'll be able to do all of this before midterm. I am giving it all I've got, and we'll soon see the result of it.

Friday, July 19, 2013

Loading pictures


Yes, loads of them! Let me show you the events of the past few days in the form of a screenshot first, and then I'll wrote about them in detail. Here you go:
The first thing you may have noticed looking the picture is that I changed back the resolution to 640x200. I decided to do so because I got the information that DOSBox only emulates the bigger screen height, and as Thomas said in a comment under my previous post, Avalanche really uses 200 pixel height, so I don't see the point in mimicking DOSBox's output instead of recreating the original experience. Also, if we decide that a bigger resolution would be nicer, it wouldn't take much more than adding a few lines of code to Graph::refreshScreen().

The second one is that there are much more things in the picture. Yes, I can say that the toolbar on the bottom is almost fully done and only the clock is missing from it. (Which - I assume - will miss for a couple of days/weeks because it's not so important regrading the actual gameplay, but tricky enough to recreate. And now I have much more urgent tasks to deal with before midterm - the characters, the dropdown menu on the top and the keyboard/mouse input -, and the days are just getting shorter and shorter.)
To be honest, after understanding how EGA graphics work and implementing the loading of the background image, the toolbar itself wasn't such a big problem, since it uses an almost identical method to load the parts of it as pictures. I can divide the bottom of the screen to 5 bigger parts: the background of the toolbar (the big blue thing), the "Thinks:" field of it, the score display, the clock, and that little picture (in the above screenshot a brown STOP sign) at the top left of it which tells the player if Avalot is standing in one place or moving in a given direction.
I implemented these parts in the exact order as I enumerated them in my previous sentence. To do this, I had to find out (obviously, with the help of fuzzie) that these pictures' encoding differ a bit from the background's. They are using row-planar EGA data, instead of graphic-planar EGA data which I used in the algorithm published in my previous post. Luckily, the methods for these two styles don't differ much, so the implementation of a function which will handle all of the pictures what are not the background was quite easy. To do so, I reworked Graph a little bit, and finally Graph::drawPicture() was born (to replace Graph::copySurface()):

void Graph::drawPicture(const byte *source, uint16 destX, uint16 destY) {
 // The height and the width are stored in 2-2 bytes. We have to add 1 to each because Pascal stores the value of them -1.
 uint16 pictureWidth = READ_LE_UINT16(source) + 1;
 uint16 pictureHeight = READ_LE_UINT16(source + 2) + 1;

 uint32 i = 4;

 Graphics::Surface picture; // We make a Surface object for the picture itself.

 picture.create(pictureWidth, pictureHeight, Graphics::PixelFormat::createFormatCLUT8());

 // Produce the picture.
 for (byte y = 0; y < pictureHeight; y++)
  for (int8 plane = 3; plane >= 0; plane--) // The planes are in the opposite way.
   for (uint16 x = 0; x < pictureWidth; x += 8) {
    byte pixel = source[i++];
    for (byte i = 0; i < 8; i++) {
     byte pixelBit = (pixel >> i) & 1;
     *(byte *)picture.getBasePtr(x + 7 - i, y) += (pixelBit << plane);
    } 
   }

 // Copy the picture to a given place on the screen.
 for (uint16 y = 0; y < picture.h; y++)
  for (uint16 x = 0; x < picture.w; x++)
   *(byte *)_surface.getBasePtr(x + destX, y + destY) = *(byte *)picture.getBasePtr(x, y);  
}

During the implementation of it, I found this little help during a simple search with Google. You can see that my code dips a lot from it: I read in the width and the height of the picture first, then create a Graphics::Surface object to store the picture in it, and then a very familiar algorithm comes with a little modification regarding the order of the planes. At last, I copy the image to a given point of the screen. So Tom Swigle, if you are reading this post somewhere, sometime: thank you, you are awesome!
After I finished with drawPicture, my only task was to replace the original PutImage() calls of the Pascal code with it, since I've done the loading of the pictures into byte arrays (what drawPicture gets as a parameter to work with) a few weeks earlier. And that's all, you can see yourself the result of it in the image above.

The last thing you might have noticed in the screenshot is a little pink rectangle in the middle of the screen. Don't worry, it's not a glitch! It's the very place where the hero of the game, Avalot d' Argent himself will manifest - I hope - within a couple of days. (I just put it there to see if I get the coordinates of the character accurately.)
Maybe next time we can see him in the screen as well? ;)

Sunday, July 14, 2013

First screenshot

Yes, you are not dreaming! It's true, it's fresh, it's happening RIGHT NOW! Ladies and gentlemen, I proudly present you the very first screenshot of Avalot d' Argent in the holy embrace of SvummVM!
Okay, the colors really need some adjustments, but apart from that you can see that the background image is successfully loaded and shown accurately. (Of course here will come the GUI in the top and the bottom, but that's not my first priority at the moment.)

Lucerna
Let me tell you a little story about my fight with the bits! Everything started after my latest post: I began to mess around with graphics, and I had some mailing with dreammaster, who helped me a lot and gave me an awesome "Graphics in ScummVM for dummies" guide. By following that, I successfully set up the basics of the screen handling in my engine, what you can find here and here. Graph's initial purpose was to replace the Graph unit from Pascal with a C++ class, so it can work in synergy with Lucerna (the class/unit which is responsible for the screen, keyboard and mouse handling) but as time passes I am slowly getting convinced that it will eventually become a replacement for Lucerna. I don't see it clear yet, time will tell...
At the moment Graph is not much more than a wrapper around a Graphics::Surface object.
I got the resolution of the game (what you can find in the header file of Graph) from this function call in the original code: 
 gd:=3; gm:=0; initgraph(gd,gm,'');
Where 3 stands for EGA graphic driver and 0 means EGALo mode, which is equal to 640x200 screen resolution, 16 colors and 4 screen pages. (I'll bother with these "pages" later.)
I also had some difficulties setting up the color palette to mimic the EGA display, but dreammaster told me a lot about it, and by "borrowing" a little bit of code from Strangerke's Mortvielle engine, I get over with it quite fast too. As you may see it in the screenshot at the beginning of the post, there is still a couple of things to do with it, since the colors in the original game are much more livid, but I'll leave it's fix for later.

The next big deal came right after that. I had a long conversation with fuzzie (who is "substituting" Strangerke, my mentor, while he is on holiday) about the topic and she told me a great deal about EGA displays and how did they handle data.
The function which is responsible for loading the data of each screen is Lucerna::load(). The tricky part was here to notice the loop in the original code (which is fuzzie's merit), and recognize that we have to face the "four plane style". After that, recreating it in C++ was quite easy, and fuzzie helped me a lot with that as well.
Here's the result of it:

f.seek(177);

/*for (bit = 0; bit <= 3; bit++) {
 port[0x3c4] = 2;
 port[0x3ce] = 4;
 port[0x3c5] = 1 << bit;
 port[0x3cf] = bit;
 blockread(f, a0, 12080);
 move(a0, a1, 12080);
}*/

Graphics::Surface background;
background.create(_vm->_graph._screenWidth, _vm->_graph._screenHeight, Graphics::PixelFormat::createFormatCLUT8());

byte backgroundHeight = 8 * 12080 / _vm->_graph._screenWidth; // With 640 width it's 151
// The 8 = number of bits in a byte, and 12080 comes from the original code (see above)

for (byte plane = 0; plane < 4; plane++)
 for (uint16 y = 0; y < backgroundHeight; y++)
  for (uint16 x = 0; x < _vm->_graph._screenWidth; x += 8) {
   byte pixel = f.readByte();
   for (byte i = 0; i < 8; i++) {
    byte pixelBit = (pixel >> i) & 1;
    *(byte *)background.getBasePtr(x + 7 - i, y) += (pixelBit << plane);
   } 
  }

_vm->_graph.copySurface(background);

background.free();

As you can see I left the automatically converted loop in a comment. Under that, there's my C++ interpretation of it. You can find the idea behind that loop's core on this page. We guessed it's using four planes because the original loop goes from 0 to 3. So my code does the very same. It first reads the blue component of every pixel: since every bit represent a pixel, we jump in the x loop 8 times every time, and read a byte only after every 8th processed pixel. After that, we loop through the given byte, get the blue component of every pixel, and put them in their place. We do that four times, so every plane (blue, green, red, intensity) is read by the end of the big, plane loop, and finally we got the background image!
The interesting part with this is the following: we read an image with the size of 640x151. That's ok, but after playing the game a couple of times using DOSBox, I clearly saw that it shows the background image (and obviously the whole game too) in a much bigger resolution. I found that the window's size the emulator uses is 640x400. It's very strange since the original Pascal code (as I mentioned above) uses half of that height. To mimic DOSBox's output, I put a little supplement into Graph::copySurface() which copies every line of the background 2 times. After that, my graphical output became almost the same with the one DOSBox produced, but I am still not sure if it's the right way of operation and I am still searching for traces of this "stretching" in the original code.

(P.s.: Thomas: if you read this post and have any clue or suggestion about this resolution-problem, I'd be very glad if you could share it with me in a comment or by mail! :) Is the original output of the game really in 640x400, and if it is, where the "trick" is located in the original code which makes it possible?)