It is currently Fri Nov 24, 2017 3:51 pm

All times are UTC + 1 hour




Post new topic Reply to topic  [ 15 posts ] 
Author Message
 Post subject: Gif animated backgrounds
PostPosted: Mon Sep 11, 2017 8:12 pm 
Offline
New User
New User

Joined: Mon Sep 11, 2017 7:43 pm
Posts: 8
Hi everybody.
Since posting exes as new user isn't very popular here i'm gonna do what expected to do, sharin some codes, ideas and stuff. I really love purebasic and i'm not going to stop using it because of my opinion on some people...

Not so far ago, just starting learning purebasic, i've managed to create a sokoban game and soon needed to enhance graphics.
I was looking in this forum to get some ideas for an animated background based on GIF images.
Probably most of you had this idea but i've only readed people talking about GIF LIBRARIE or such...
I've tried it but source code was too long and yes i'm still using demo version so i was unable to run it... then come
to the conclusion that an animation is so easy to do with purebasic sprites that it wont take more than a few code lines.

This little demo shows easy way to do it wich probably will be useful for newbis (as i am)
The code won't work unless it loads the .jpg at the data folder. I'm showing here but need to download at
https://mega.nz/#!hC4xBRgK!KJB-haHw98mm ... pONK03t08Q
then unzip to it's own folder.
More info at the source.

Code:
; ANIMATED GIF BACKGROUNDS By SERGIO 'ManOwaR' SOEIRO 2017
;
;
; * Since i was searching some way to have animated backgrounds in my games, i looked at purebasic forums and people agree to use some
;  "gif library" or such.... i've tried it but it has thousands lines so i made this to get a simple and effective way to animate backgrounds.
;
; * This little code is inteded to extract frames from a picture then 'mount' an animated gif using purebasic commands easyly.
; * You should have your animation in a 'comic strip' format. There are tools online to convert gifs to strip etc.
; * You must know data like resolution, frames total and animation frame speed.
; * There are limitation because mounting a picture in a strip format will result in a very long width picture, that probably will crash on certain
;     cpus or be loaded with color errors. In this demo i'm using a 3000 pixels width picture in 10 frames (300px each frame)
;     Of course image can also be mounted in a "tileset" form but that should be done manually because i haven't found tools at the moment to do it
;     and also if you get a tileset (squared) you need to change the algorithm to extract tiles (frames). I've alreday done it for another purposes
;     like having a personaliced sprite-based font and that algorithm could be used here if needed.
;
; * This demo works with prewrited data of the animation showed, the way to use several "gifs" must be very easy if you know a little coding
;    Here are my suggestions:
;     1: You can have a stored data lines containing your gifs data like ID, NAME, FRAMES TOTAL, WIDTH, HEIGHT
;     2:  You can create your own rutine to read 'on the fly' gif data. Pictures must have the data contained in the name, then use string commands
;         to extract Data anytime a picture is loaded. an example of this will be a pictured named "#1#WATER BACKCROUND#11#320#240#.JPG" Then you extract
;         data splited with "#" and can manage as many of your gifs you put in a folder.
;
;  HOPE THIS IS USEFUL TO SOMEBODY
;
;
; EMAIL:sergiomanowarsoeiro@gmail.com
; Greetings for people at dbfinteractive.com

InitSprite()
InitMouse()
InitKeyboard()

UseJPEGImageDecoder()

OpenScreen(640,480,32,"ANIMATED GIF BACKGROUNDS",#PB_Screen_SmartSynchronization,60)
LoadSprite(1,"DATA/BACKGROUNDS/BG 1.jpg")


; VARS
gif_frames=10:;WARNING ! As count starts by zero, frame 1 will be 0 and last frame wil be gif_frames-1
gif_width=300
gif_height=199
gif_frame.f=0
gif_speed.f=0.5


LOOP:
; EXTRACT FRAME
ClipSprite(1,Int(gif_frame)*gif_width,0,gif_width,gif_height)
; DRAW
FlipBuffers()
ZoomSprite(1,640,480)
DisplaySprite(1,0,0)
StartDrawing(ScreenOutput())
DrawText(0,0,"Press [ESC] to exit...")
DrawText(300,30,"FRAME "+Str(Int(gif_frame))+"/"+Str(gif_frames-1))
DrawText(300,45,"SPEED "+Str(gif_speed*100)+"%")
DrawText(0,450,"[-]: Decrease SPEED")
DrawText(0,465,"[+]: Increase SPEED")
StopDrawing()
; UPDATES
gif_frame+gif_speed
If gif_frame>gif_frames-gif_speed:gif_frame=0:EndIf
; INPUTS
ExamineKeyboard()
If KeyboardPushed(#PB_Key_Escape):End:EndIf
If KeyboardPushed(#PB_Key_Add):gif_speed+0.01:If gif_speed>1:gif_speed=1:EndIf:EndIf
If KeyboardPushed(#PB_Key_Subtract):gif_speed-0.01:If gif_speed<0.1:gif_speed=0.1:EndIf:EndIf
Goto LOOP


Of course this ain't gifs but you got the point.

I had put several animated backgrounds in my sokoban game wich i'm not sharing here cos it's a diabolic exe but maybe some day restarted to write and share some of the source or the .pbi file at least.
c ya


Top
 Profile  
Reply with quote  
 Post subject: Re: GIF ANIMATED BACKGROUNDS
PostPosted: Mon Sep 11, 2017 11:23 pm 
Offline
User
User

Joined: Sat Mar 19, 2011 3:49 pm
Posts: 45
Hey, very ugly style bro. forget goto loop and use while/repeat loop , and use tab for indent your code, the principal risk when i read this, i'm afraid of becoming blind
and dont forget to close the screen at the end, when i back to my desktop , 640x480 go back me in 1995.


Top
 Profile  
Reply with quote  
 Post subject: Re: GIF ANIMATED BACKGROUNDS
PostPosted: Tue Sep 12, 2017 1:21 am 
Offline
New User
New User

Joined: Mon Sep 11, 2017 7:43 pm
Posts: 8
G-Rom wrote:
Hey, very ugly style bro. forget goto loop and use while/repeat loop , and use tab for indent your code, the principal risk when i read this, i'm afraid of becoming blind
and dont forget to close the screen at the end, when i back to my desktop , 640x480 go back me in 1995.


ok thanks for suggestions but not very useful for me since you didn't mention a word about the utility. I didn't know people were so exquisite... using goto for a quick code.. "excusez moi monsier"... about 640x480 you should know that it's the most standard screen resolution that guarantees it will run on every screens an tvs... excusez moi again if you traveled to 1995... hope you can find the manners you lost there and bring it back. About becoming blind... if ya haven't become already jerk**g off you should not be worried about it mate. C'mom whats the matter with this forum? is it so difficult comment about results and not about any other stupid question? it's unbeliveable. I know it's ugly but it works, it was quick coded and by the way, purebasic IDE has it's own indentation. Just CTRL+A to select all then CONTROL+I for format indentation et voilà indented!!
What? No changes? Surprise! If purebasic developers considere that there is nothing to indent here why should i start using TABS? for your delicated eyes? wow


Top
 Profile  
Reply with quote  
 Post subject: Re: GIF ANIMATED BACKGROUNDS
PostPosted: Tue Sep 12, 2017 2:06 am 
Offline
New User
New User

Joined: Mon Sep 11, 2017 7:43 pm
Posts: 8
ASCII TILESET EXTRACTOR ALGORITHM

Probably this already exists so i'm not posting new topic for this, just post here because previously i mentioned that extracting "frames" to mount an animated background using clipsprite can be used aswell to extract tiles from a tileset so i've edited previous code and here it is.

You need the tileset image wich is here together the source code:
https://mega.nz/#!kH5ySIxB!3MRdcBghJouv ... 3ACqmJGIeE

Any other tileset should work ok but just replacing the individual tile resolution.

Code:
; ASCII TILESET EXTRACTOR ALGORITHM By SERGIO 'ManOwaR' SOEIRO 2017
;
; * OK! So you have a nice ASCII TILESET! 16x16 tiles...and now what?
;   This simple algorithm extracts a tile from the tileset.
;   The tile to extract must be a number between 0-255
;   Since characters also have a ascii code number, it's easy to understand that
;    an "A" corresponds to tile 65, "B" to tile 66 etc... so you can use strings and extract
;    characters from the tileset representing the same ascii char.
;  * Here i'm using pre-defined values for font size (wich will be displayed with a
;     resolution of 24x24 so it could be changed for any other value or a var
;  FONT is JOLLY and has been taken from http://dwarffortresswiki.org/images/4/4d/Jolly12x12.png
;  AUTHOR: Alexander osias
;
;  HOPE THIS IS USEFUL TO SOMEBODY
;
;
; EMAIL:sergiomanowarsoeiro@gmail.com
; Greetings for people at dbfinteractive.com

InitSprite()
InitMouse()
InitKeyboard()

UsePNGImageDecoder()
OpenScreen(640,480,32,"TILESET EXTRACTOR",#PB_Screen_SmartSynchronization,60)
LoadSprite(1,"DATA/TILESETS/Jolly12x12.png")


; TILESET
Global tileset_rows=16:;It's an ascii tileset so it is a squared 16x16 tileset. Any other type of tileset will require changes.
Global tile_width=12,tile_height=12,tile_x1,tile_y1,tile




LOOP:
; DRAW
FlipBuffers()
ClearScreen(0)
ClipSprite(1,-1,-1,-1,-1)
DisplaySprite(1,0,20)
; EXTRACT TILE
For byte=1 To Len(FullText$)
  tile=Asc(Mid(fulltext$,byte,1))
  tile_y1=Int(tile/tileset_rows)*tile_height
  tile_x1=Mod(tile,tileset_rows)*tile_width
  ClipSprite(1,-1,-1,-1,-1)
  ClipSprite(1,tile_x1,tile_y1,tile_width,tile_height)
  ZoomSprite(1,24,24)
  DisplaySprite(1,byte*24-24,300)
  DisplaySprite(1,320-Len(fulltext$)*24/2+byte*24-24,350)
  DisplaySprite(1,640-Len(fulltext$)*24+byte*24-24,400)
Next
StartDrawing(ScreenOutput())
If FullText$<>""
  DrawText(300,280,"LEFT ALIGNEMENT")
  DrawText(300,330,"CENTERED ALIGNEMENT")
  DrawText(300,380,"RIGHT ALIGNEMENT")
EndIf
DrawText(0,0,"Press [ESC] to exit...")
DrawText(0,460,"/¡\ TYPE SOME WORDS...")
StopDrawing()
; INPUTS
ExamineKeyboard()
; >>> THIS PART TAKEN FROM THE PUREBASIC HELP FILES
If KeyboardReleased(#PB_Key_Back)
  FullText$ = Left(FullText$, Len(FullText$)-1)
Else
  result$=KeyboardInkey()
  If FindString("1234567890 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", result$) ; Or your chosen valid characters
    If Len(fulltext$)<25:FullText$ + result$:EndIf
  EndIf ; Add the new text to the current one (if any)
EndIf
; <<< THIS PART TAKEN FROM THE PUREBASIC HELP FILES
If KeyboardPushed(#PB_Key_Escape):End:EndIf
Goto LOOP



Includes text alignement wich is easy when you know character resolution. It works in monospaced fonts, e.g. for a centered text you place the text at the point you want and substract length_of_string*resolution/2 ... maybe will talk more about text alignement someday, years ago i've published several built-in text routines for text align, border shadows and more in some of my games (in yabasic) and will be nice to translate it to purebasic.
Hope this is usefull for somebody and do not hurt your eyes...


Top
 Profile  
Reply with quote  
 Post subject: Re: GIF ANIMATED BACKGROUNDS
PostPosted: Tue Sep 12, 2017 7:43 am 
Offline
Enthusiast
Enthusiast

Joined: Sat Mar 02, 2013 9:17 am
Posts: 677
Removed, i think, its senseless

_________________
http://www.nachtoptik.de - The home of Bucketfill_advanced (BF) and QUICK_AES_256


Last edited by walbus on Wed Sep 13, 2017 1:29 pm, edited 9 times in total.

Top
 Profile  
Reply with quote  
 Post subject: Re: GIF ANIMATED BACKGROUNDS
PostPosted: Tue Sep 12, 2017 3:09 pm 
Offline
New User
New User

Joined: Mon Sep 11, 2017 7:43 pm
Posts: 8
Dear dumbledore i don't see the point to "should use" or "must use" repeat until etc because it's nicer... i just do things that work and it's true not really worried for a nice code but again no comments about the results... it's very annoying.
Taking a quick look at the first code i saw you made, wich is the drawtext alignements rutines, you should at least be interested in the last piece of my code wich is intended to do precisely that:alignement. In this case, sprite text mounted from a tileset, but that simple operations also work with monospaced fonts. Myself i've created several text routines years ago (wich are published at the yabasic forum) to handle this and also i maded a poin't and click game (not released yet because of transalations) wich has text rutines to handle a string text containing personaliced escape secuences (very similar as you used) to make several things like #L new line, #RGB to change on the fly character colors, #ICON to include (preloaded tileset icons), alignements and other stuff resulting in a game with very nice text routines. However surce code is ugly but running it nobody will care because of nice performance.... surely i will like to made a clean-up and make sources nicer someday but in first instance i code something that works... the nicer of the source is irrelevant, its the nice of the result what matters. So please stop criticism of appareances and start commenting about how it works and what it does.. and what it could do. thanks. This sample codes can be very much enhanced for purposes... i usually find solutions for problems... i've managed to create bitmaps for yabasic (wich it doesn't have anything) and if somebody see a bitmap in yabasic and only can say "what an ugly code bro" only thing deserves is a big LOL.
Now as a newbie with purebasic i'm sure will handle to make great stuff and the ugly code is the last of my worries. If you read this, expect some feedback about alignements, wich is a matter interesting for me and also started to work with it in purebasic using windows fonts and trying to understand more about it. Probably will adapt my text routines in yabasic to purebasic and share someday but this need lots of vars because of screen resolution and format may be different and the perfect routines should adapt to different parameters.


Top
 Profile  
Reply with quote  
 Post subject: Re: GIF ANIMATED BACKGROUNDS
PostPosted: Tue Sep 12, 2017 3:17 pm 
Offline
New User
New User

Joined: Mon Sep 11, 2017 7:43 pm
Posts: 8
Forgot to mention about what you said about using windows... yes it's better i suppose for quick tests but at the moment i found disfficult handle windows and if i get the way to have a window then enter fullscreen mode by pressing e.g ALT*ENTER or clicking an option i will start in windows mode. At the moment using fullscreen as default because it's easy and simple.


Top
 Profile  
Reply with quote  
 Post subject: Re: GIF ANIMATED BACKGROUNDS
PostPosted: Tue Sep 12, 2017 3:33 pm 
Offline
Enthusiast
Enthusiast
User avatar

Joined: Wed Sep 21, 2011 9:11 am
Posts: 577
Location: France
Hello.

I tested your code and I like the result.

But you must forget the Yabasic style and code Purebasic.
Code:
EnableExplicit

; VARS
Define gif_frames=10:;WARNING ! As count starts by zero, frame 1 will be 0 and last frame wil be gif_frames-1
Define gif_width=300
Define gif_height=199
Define gif_frame.f=0
Define gif_speed.f=0.5

If InitSprite() = 0 Or InitKeyboard() = 0 Or InitMouse() = 0
  MessageRequester("Error", "Sprite system can't be initialized", 0)
  End 
EndIf

UseJPEGImageDecoder()
UsePNGImageDecoder()

If OpenScreen(800, 600, 32, "ANIMATED GIF BACKGROUNDS",#PB_Screen_SmartSynchronization,60)
  LoadSprite(1,"DATA/BACKGROUNDS/BG 1.jpg")
 
  ; EVENTS LOOP
  Repeat
    FlipBuffers()
   
    ; EXTRACT FRAME
    ClipSprite(1, Int(gif_frame)*gif_width, 0, gif_width, gif_height)
   
    ; DRAW
    ZoomSprite(1, 800, 600)
    DisplaySprite(1, 0, 0)
   
    StartDrawing(ScreenOutput())
    DrawText(0,0,"Press [ESC] to exit...")
    DrawText(300,30,"FRAME "+Str(Int(gif_frame))+"/"+Str(gif_frames-1))
    DrawText(300,45,"SPEED "+Str(gif_speed*100)+"%")
    DrawText(0,450,"[-]: Decrease SPEED")
    DrawText(0,465,"[+]: Increase SPEED")
    StopDrawing()
   
    ; UPDATES
    gif_frame+gif_speed
    If gif_frame>gif_frames-gif_speed:gif_frame=0:EndIf
   
    ; INPUTS
    ExamineKeyboard()
    If KeyboardPushed(#PB_Key_Add):gif_speed+0.01:If gif_speed>1:gif_speed=1:EndIf:EndIf
    If KeyboardPushed(#PB_Key_Subtract):gif_speed-0.01:If gif_speed<0.1:gif_speed=0.1:EndIf:EndIf
  Until KeyboardPushed(#PB_Key_Escape)
Else
  MessageRequester("Error", "Can't open a 640*480 - 32 bit screen !", 0)
EndIf


edited by fred: let's forget the previous posts and please focus on coding :)

_________________

➽ Windows 10 - PB 5.45 LTS & PB 5.60

http://falsam.com & EasySprite.js
http://purebasic.chat - Code PureBasic
Image Pure Basic Francophone Community

Sorry for my bad english and the Dunning–Kruger effect.


Top
 Profile  
Reply with quote  
 Post subject: Re: GIF ANIMATED BACKGROUNDS
PostPosted: Tue Sep 12, 2017 3:52 pm 
Offline
Addict
Addict
User avatar

Joined: Sat Feb 19, 2005 2:46 pm
Posts: 1683
Location: Pas-de-Calais, France
Welcome on this forum, you'll see, we have great experimented coders/hackers there. Everybody could learn something ! It's nice to start by sharing, even if the exe was a mistake by now. I'm sure we'll appreciate your work when we'll know you a little more. In fact, I think that most of us do prefer WIP/algorithmic/maths/problems instead of final exe. And a lot of us do love answering questions ! Your code shows that you like oldschool stuff, isn't it ?

_________________
Prehistoric games - Bobble Puzzle, Purebreaker 3 ~> http://djes.free.fr


Top
 Profile  
Reply with quote  
 Post subject: Re: Gif animated backgrounds
PostPosted: Tue Sep 12, 2017 8:43 pm 
Offline
Addict
Addict
User avatar

Joined: Sat Oct 09, 2010 3:47 am
Posts: 1366
Hi SERGIO_Man0waR_,

Prior to the latest versions of PureBasic, GIF animation was accomplished using a couple of methods...

Coded from scratch: GIF Toolkit, GIF Workshop.

Using the WebGadget:
Code:
Enumeration
  #MainWindow
  #WebGadget
EndEnumeration

HTML.s = "<html>" + #LF$ +
         #TAB$ + "<body style='overflow:hidden'>" + #LF$ +
         #TAB$ + #TAB$ + "<img src='https://media.giphy.com/media/PTCEEV9GWZQFa/giphy.gif' alt='GIF by ORBO' style='width:636;height:356;'>" + #LF$ +
         #TAB$ + "</body>" + #LF$ +
         "</html>"

If OpenWindow(#MainWindow, 0, 0, 646, 366, "WebGadget: Animated GIF", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
  WebGadget(#WebGadget, 0, 0, 636, 356, #Null$) : SetWindowColor(#MainWindow, #White)
  SetGadgetItemText(#WebGadget, #PB_Web_HtmlCode, HTML)
  Repeat : Until WaitWindowEvent() = #PB_Event_CloseWindow
EndIf

In the latest versions of PureBasic, Fred and Team added GIF Animation to the IDE:
Code:
Enumeration
  #MainWindow
  #ImageGadget
EndEnumeration

Procedure PlayAnimation(*hGIF)
  FrameCount = ImageFrameCount(*hGIF)

  Repeat
    For rtnCount = 0 To FrameCount - 1
      SetImageFrame(*hGIF, rtnCount)
      SetGadgetState(#ImageGadget, ImageID(*hGIF)) : Delay(40)
    Next
  ForEver
EndProcedure

AnimatedGIF.s = GetTemporaryDirectory() + "_test.gif"

If Not FileSize(AnimatedGIF) > 0
  InitNetwork()
  ReceiveHTTPFile("http://cmzone.vzbqbxhynotw9ion96xv.netdna-cdn.com/wp-content/uploads/2013/02/stripes.gif", AnimatedGIF)
EndIf

If AnimatedGIF
  UseGIFImageDecoder()
  hGIF = LoadImage(#PB_Any, AnimatedGIF)

  If IsImage(hGIF)
    nWidth = ImageWidth(hGIF) : nHeight = ImageHeight(hGIF)

    If OpenWindow(#MainWindow, 0, 0, nWidth, nHeight, "ImageGadget: Animated GIF", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
      ImageGadget(#ImageGadget, 0, 0, nWidth, nHeight, #Null)
      CreateThread(@PlayAnimation(), hGIF)
      Repeat : Until WaitWindowEvent() = #PB_Event_CloseWindow
    EndIf
    FreeImage(hGIF)
  EndIf
EndIf

_________________
ImageMy PureBasic Stuff


Top
 Profile  
Reply with quote  
 Post subject: Re: Gif animated backgrounds
PostPosted: Thu Sep 14, 2017 10:19 pm 
Offline
New User
New User

Joined: Mon Sep 11, 2017 7:43 pm
Posts: 8
Ok finally got some positive criticism so thnks all and i'm gonna reply.

falsam:thanks for nice reply. Your edited code i could'nt run because my screen doesn't support 800x600. About that i think it's probably better make some nested openscreen conditions, starting from bigger resolution to lower if not supported and finally if no one of the previous is supported, force 640x480 wich is universal supported. I have done it and surely most people also does it but in a quick code i missed.
About yabasic... i've been coding since i've discovered it at ps2 demo... maybe 15 years... and purebasic it's just a matter of a couple years ocasionally so it's very difficult to me to be focused on "purebasic style". I still use my own routines, 2d graphic engines and all the stuff i've maded at yabasic adapting to purebasic and surely i have no idea how purebasic can do it better and thats what i expect from experience purebasic users; tips about using advanced commands and structures. As an example, i'm using my own stack process rutines to have effects like bullets, burn flames, smoke, particles and such and i haven't understand a word of how using structures in purebasic. Another example is using my 2d tile engine (not showed yet here) consisting in store levels tile coordinates in matrix then place sprites into that coordinates tile by tile... and i'm sure there must be much better ways for a 2d engine and probably libraries. That's the problem with yabasic:you have nothing and you must create everything so as a newbie using purebasic i got some habits deep inside. Hope been around here will be good.

thanks djes for nice welcome. Yep call it 'old style'.. Liked to code old locomotive basic for amstrad cpc later yabasic. Nowadays is called ugly style :lol: but i'll keep an eye on people experienced here and sure it will be good.
By the way:as using 'goto' for a quick loop have been so eye-hurting... has anybody coded a performance test in purebasic for goto, repeat and while? In a large code with lots of rutines and labels could be interesting test wich of them is faster. I'm always using 'goto' in my main loops (except those including loop exit where using 'while') and performance is a good reason to change it.

Hi JHPJHP

ey! Thats lots of stuff related to animations, thanks.
Probably there was no need to open a topic like this, just wanted to start something and meet people.
A quick question; Is it possible to have a .mp4 video running fullscreen (e.g a landscape with a river) meanwhile drawing operations are drawed over the video? I'm talking about having a running looped video at background then in foreground drawing display, sprites and other game stuff. I've tried once and and could'n do it.

Well i've just started from zero a 2d engine for tiles for making game like sokoban or any other tile-based game. This simple engine includes zooming and scrolling, and 2 planes, so can be drawed a floor then some blocks in a higher plane so it has pseudo-3d effect from aerial view. If anybody interested i'll post right here. Currently working on fitting tile sprites, it has a bug because of the zooming 'floor' vars. I've tried some 'int' and other solutions and it works but probably there are better ways to do it in purebasic. Currently working on the 'transform sprite' to fit skewed sprites and it has not so many documentation so i'm testing brute force.

Very glad to see things get better, greetings to all


Top
 Profile  
Reply with quote  
 Post subject: Re: Gif animated backgrounds
PostPosted: Fri Sep 15, 2017 7:09 am 
Offline
Addict
Addict
User avatar

Joined: Sat Oct 09, 2010 3:47 am
Posts: 1366
Hi SERGIO_Man0waR_,

SERGIO_Man0waR_ wrote:
Is it possible to have a .mp4 video running fullscreen (e.g a landscape with a river) meanwhile drawing operations are drawed over the video?

The short answer is yes; similar has been done using OpenCV, but that would be overkill.

As you know, a video is basically a sequence of image frames timed with an audio stream...

*** Example updated based on information provided by [blendman] ***

To keep things simple I have used my previous example combined with a movable Sprite to illustrate the effect:
- use the Arrow keys to move the object
Code:
Enumeration
  #MainWindow
  #SpriteBackground
  #SpriteObject
EndEnumeration

AnimatedGIF.s = GetTemporaryDirectory() + "_jhpjhp.gif"
PlaneWAV.s = GetTemporaryDirectory() + "_jhpjhp.wav"

If Not FileSize(AnimatedGIF) > 0
  InitNetwork()
  ReceiveHTTPFile("https://media.giphy.com/media/hxYmtE6C4wi2Y/giphy.gif", AnimatedGIF)
  ReceiveHTTPFile("https://www.soundjay.com/transportation/propeller-plane-flying-steady-01.wav", PlaneWAV)
EndIf

If AnimatedGIF
  UseGIFImageDecoder()
  hGIF = LoadImage(#PB_Any, AnimatedGIF)

  If IsImage(hGIF)
    WindowWidth = ImageWidth(hGIF) : WindowHeight = ImageHeight(hGIF)

    If OpenWindow(#MainWindow, 0, 0, WindowWidth, WindowHeight, "Sprite Object and Animation", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
      InitSprite() : InitKeyboard() : InitSound()

      If OpenWindowedScreen(WindowID(#MainWindow), 0, 0, WindowWidth, WindowHeight)
        ObjectWidth = 50 : ObjectHeight = 50
        CreateSprite(#SpriteBackground, WindowWidth, WindowHeight)
        CreateSprite(#SpriteObject, ObjectWidth, ObjectHeight)

        If StartDrawing(SpriteOutput(#SpriteObject))
          Box(0, 0, ObjectWidth, ObjectHeight, #Red)
          Box(1, 1, ObjectWidth - 2, ObjectHeight - 2, #Blue)
          StopDrawing()
        EndIf
        FrameCount = ImageFrameCount(hGIF)
        nX = WindowWidth / 2 - ObjectWidth / 2 : nY = WindowHeight / 2 - ObjectHeight / 2

        If FileSize(PlaneWAV) > 0
          If LoadSound(0, PlaneWAV) : PlaySound(0, #PB_Sound_Loop) : EndIf
        EndIf

        Repeat
          Repeat
            Event = WaitWindowEvent(1)
 
            Select Event
              Case #PB_Event_CloseWindow : CloseScreen() : End
            EndSelect
          Until Not Event
          nDelay = (nDelay + 1) % 4

          If nDelay = 1
            SetImageFrame(hGIF, nFrame)

            If StartDrawing(SpriteOutput(#SpriteBackground))
              DrawImage(ImageID(hGIF), 0, 0)
              StopDrawing()
            EndIf
            nFrame = (nFrame + 1) % FrameCount
          EndIf
          FlipBuffers() : ExamineKeyboard()

          If KeyboardPushed(#PB_Key_Left) And nX > 0 : nX - 5 : EndIf
          If KeyboardPushed(#PB_Key_Right) And nX < WindowWidth - ObjectWidth : nX + 5 : EndIf
          If KeyboardPushed(#PB_Key_Up) And nY > 0 : nY - 5 : EndIf
          If KeyboardPushed(#PB_Key_Down) And nY < WindowHeight - ObjectHeight : nY + 5 : EndIf

          DisplaySprite(#SpriteBackground, 0, 0)
          DisplayTransparentSprite(#SpriteObject, nX, nY, 150)
        Until KeyboardPushed(#PB_Key_Escape)

        If IsSound(0) : FreeSound(0) : EndIf

        FreeSprite(#SpriteObject)
        FreeSprite(#SpriteBackground)
      EndIf
    EndIf
    FreeImage(hGIF)
  EndIf
EndIf

_________________
ImageMy PureBasic Stuff


Last edited by JHPJHP on Tue Sep 19, 2017 6:42 pm, edited 1 time in total.

Top
 Profile  
Reply with quote  
 Post subject: Re: Gif animated backgrounds
PostPosted: Fri Sep 15, 2017 10:42 pm 
Offline
New User
New User

Joined: Mon Sep 11, 2017 7:43 pm
Posts: 8
Hi JHPJHP
Ey thanks! Your code seems very interesting to me, includes download from web and couple of 'must know' things.
At first try i thoght it doesn't work... it does but it takes so long to download from web..

This is good thanks! And the gifdecoder works fine... maybe its new i don't remember from previous versions but that's precisely what i was talking about. There is no need to play a video since you have the looped gif for the same purpose.

There are many things in PB difficult to understand. For playing background music (.mp3) in my games i've only find this solution: using "playmovie" and movie commands for music... while sound commands reserved for wavs and sfx sounds... maybe this is an aberration but when i first saw purebasic capabilities on loading images,videos and lots of stuff i thoght "ey, it must be so easy to play a .mp3 music album background..." but no, it wasn't for me.

Anyway good to see purebasic can do so many things.

Oh i have to make another question.. ok is my last one for a time! I'm making a tile engine and it works fine, (used in yabasic) but now using sprites in purebasic to fill the tiles i got 2 bugs: one is because using zoom. The sprites must me zoomed aswell according to zoom level and thats a float var so i got tiles separated for one blank line depending on zooming level. Easy solutions were using 'int' or added a +1 to the zoomsprite values... this way the ugly blank line dissapears but transformed in a tile sprite that ocasionally overlaps next tile.
The other problem is using spritequality(1). This creates a"smoothed sprite". You probably know how it works... algorithm cheks pixels sourrounding colors then creates new colors based on average values. Sorry my bad english i don't know how to explain but the question is that sprite boundary is bugged because it tests the offscreen wich is value zero so the sprite limits will show some sort of "black border". That is ok but when you put together all this tiles with the black borders the effect is so bad....and the continuity of a tiled-based graphics is lost. So first i thought the best solution to this is NOT having a nested 'tile by tile' drawing sprites loop. Instead it will be great, if you know what tiles must be showed, mount all together in a new sprite or image, then this alone image can be safely zoomed, smoothed, rotated or whatever. Is it possible to MOUNT a new sprite from sprite tiles? Short answer will be ok if you or anybody knows, thanks!
Ok thanks anyway, from now i'll be cheking forum and if i can help or share some idea i'll be glad to do it.


Top
 Profile  
Reply with quote  
 Post subject: Re: Gif animated backgrounds
PostPosted: Sat Sep 16, 2017 9:13 am 
Offline
Enthusiast
Enthusiast
User avatar

Joined: Thu Apr 07, 2011 1:14 pm
Posts: 243
Location: 3 arks
Hi

Thanks, it's interesting.
it's not really a gif, because your image is a jpg ;).
But the effect is great.

In your loop, if you use openwindow() and openwindowedscreen(), you can use :

Code:
Repeat
   
    Repeat
     
      event = WaitWindowEvent(1)
     
      If event = #PB_Event_CloseWindow
        CloseScreen()
        End
      EndIf
           
    Until event = 0
   
   
    FlipBuffers()
; here your sprite, display, clearscreen...

Until KeyboardPushed(#PB_Key_Escape)


it's better, when you use a windowed screen to have a double repeat / until loop.

The complete code :
Code:
EnableExplicit

; VARS
Define gif_frames=10:;WARNING ! As count starts by zero, frame 1 will be 0 and last frame wil be gif_frames-1
Define gif_width=300
Define gif_height=199
Define gif_frame.f=0
Define gif_speed.f=0.5

Define event.i=0

If InitSprite() = 0 Or InitKeyboard() = 0 Or InitMouse() = 0
  MessageRequester("Error", "Sprite system can't be initialized", 0)
  End
EndIf

UseJPEGImageDecoder()
UsePNGImageDecoder()

OpenWindow(0, 0, 0, 640, 480, "ANIMATED GIF BACKGROUNDS")

If  OpenWindowedScreen(WindowID(0), 0, 0, 640, 480)
  LoadSprite(1,"bg1.jpg")
 
  ; EVENTS LOOP
  Repeat
   
    Repeat
     
      event = WaitWindowEvent(1)
     
      If event = #PB_Event_CloseWindow
        CloseScreen()
        End
      EndIf
           
    Until event = 0
   
   
    FlipBuffers()
   
    ; EXTRACT FRAME
    ClipSprite(1, Int(gif_frame)*gif_width, 0, gif_width, gif_height)
   
    ; DRAW
    ZoomSprite(1, 800, 600)
    DisplaySprite(1, 0, 0)
   
    StartDrawing(ScreenOutput())
    DrawText(0,0,"Press [ESC] to exit...")
    DrawText(300,30,"FRAME "+Str(Int(gif_frame))+"/"+Str(gif_frames-1))
    DrawText(300,45,"SPEED "+Str(gif_speed*100)+"%")
    DrawText(0,450,"[-]: Decrease SPEED")
    DrawText(0,465,"[+]: Increase SPEED")
    StopDrawing()
   
    ; UPDATES
    gif_frame+gif_speed
    If gif_frame>gif_frames-gif_speed:gif_frame=0:EndIf
   
    ; INPUTS
    ExamineKeyboard()
    If KeyboardPushed(#PB_Key_Add):gif_speed+0.01:If gif_speed>1:gif_speed=1:EndIf:EndIf
    If KeyboardPushed(#PB_Key_Subtract):gif_speed-0.01:If gif_speed<0.1:gif_speed=0.1:EndIf:EndIf
  Until KeyboardPushed(#PB_Key_Escape)

Else

  MessageRequester("Error", "Can't open a 640*480 - 32 bit screen !", 0)

EndIf


And welcome to the purebasic forum ;)


Top
 Profile  
Reply with quote  
 Post subject: Re: Gif animated backgrounds
PostPosted: Mon Sep 18, 2017 12:18 pm 
Offline
New User
New User

Joined: Mon Sep 11, 2017 7:43 pm
Posts: 8
Thanks blendman for welcome and suggestions.
Yes it is not a gif... it has similar purpose but need to create the strip by yourself or with a tool.

I have tested now usegifdecoder() and it works fine... but it decreases dramatically the frame rate.. or at least for me! so i keep using clipsprite as an option.

I see many people interested in nice code like:

If InitSprite() = 0 Or InitKeyboard() = 0 Or InitMouse() = 0
MessageRequester("Error", "Sprite system can't be initialized", 0)
End
EndIf

I have to say that i know that, just not using it for 2 reasons: first, for a quick code i don't like to type so many stuff. If the cpu can't init sprite or keyboard or mouse.... then just take the cpu and a big hammer and crush it.. :D the second reason is because using demo version, source is limited.
I understand the sense of having conditions "if" for if something can't start then have a response... or a message, but if a had a final product it will include several responses (and in several languajes) to conditions. I'm saying this because i've seen many people worried about the nice code but i will be more interested on people saying me: "ey you don't need to reset the clipsprite(-1,-1,-1,-1) all the time unless that..." or any other tip related to purebasic functions instead of appareance.
Thats the kind of things a newbie need, how the functions and commands works. Mostly i'm just trying things until it works but a experienced user can save lot ot time.

Using windows.. ok i'll try thanks for the code... i just find annoying all that windowId stuff but i'll ckek your code.
You have been very frendly and i thank you and hope we will see around forums.

I'm just having an eye from time to time here if anybody can answer please:is it possible to "mount" an image from several clipsprites then have a single image?


Top
 Profile  
Reply with quote  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 15 posts ] 

All times are UTC + 1 hour


Who is online

Users browsing this forum: No registered users and 3 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
Jump to:  

 


Powered by phpBB © 2008 phpBB Group
subSilver+ theme by Canver Software, sponsor Sanal Modifiye