Image noise: Difference between revisions

m
No edit summary
 
(48 intermediate revisions by 24 users not shown)
Line 10:
{{omit from|Batch File}}
[[Category:Raster graphics operations]]
Generate a random black and white 320x240&nbsp; '''320'''<small>x</small>'''240''' &nbsp; image continuously,
showing FPS (frames per second).
 
Sample image:
 
;A sample image: [[Image:NoiseOutput.png|600px||center|sample]]
<br><br>
=={{header|6502 Assembly}}==
{{works with|https://skilldrick.github.io/easy6502/ Easy6502}}
Easy6502's built-in RNG allows for random pixels to be displayed in an infinite loop. Unfortunately these pixels are far too large to
effectively display an FPS counter, although the unused Y register in the program below could theoretically output that.
<syntaxhighlight lang="6502asm">define sysRandom $fe
 
Snow:
lda sysRandom ;get a random number
and #$01 ;remove all but bit 0
sta $0200,x ;store in first section of VRAM
 
lda sysRandom ;get a random number
and #$01 ;remove all but bit 0
sta $0300,x ;store in second section of VRAM
 
lda sysRandom ;get a random number
and #$01 ;remove all but bit 0
sta $0400,x ;store in third section of VRAM
 
lda sysRandom ;get a random number
and #$01 ;remove all but bit 0
sta $0500,x ;store in last section of VRAM
 
inx ;next X
jmp Snow ;loop forever</syntaxhighlight>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
DEFINE TEXT_SIZE="40"
BYTE ARRAY text(TEXT_SIZE)
 
CARD FUNC GetFrame()
BYTE RTCLOK1=$13,RTCLOK2=$14
CARD res
BYTE lsb=res,msb=res+1
 
lsb=RTCLOK2
msb=RTCLOK1
RETURN (res)
 
PROC CalcFPS(CARD frames REAL POINTER fps)
BYTE PALNTSC=$D014
REAL ms,r1000
 
IF PALNTSC=15 THEN
frames==*60
ELSE
frames==*50
FI
 
IntToReal(1000,r1000)
IntToReal(frames,ms)
RealDiv(r1000,ms,fps)
RETURN
 
PROC FillNoise()
BYTE POINTER ptr
BYTE x,y,rnd=$D20A
 
ptr=PeekC(88)
FOR y=0 TO 191
DO
FOR x=0 TO 39
DO
ptr^=rnd
ptr==+1
OD
OD
RETURN
 
PROC PrepareScreen()
BYTE COLOR1=$02C5,COLOR2=$02C6
CARD SDLSTL=$0230,ptr
BYTE i,v
BYTE ARRAY dlist(205)
 
Graphics(8+16)
COLOR1=$0F
COLOR2=$00
 
;prepare text
FOR i=0 TO TEXT_SIZE-1
DO
text(i)=0
OD
text(6)='F-32
text(7)='P-32
text(8)='S-32
 
;modify display list to add one row with text on the top
dlist(0)=$70
dlist(1)=$70
dlist(2)=$42
PokeC(dlist+3,text)
ptr=SDLSTL
ptr==+3
FOR i=5 TO 202
DO
dlist(i)=Peek(ptr)
ptr==+1
OD
PokeC(dlist+203,dlist)
 
SDLSTL=dlist
RETURN
 
PROC PrintFPS(REAL POINTER fps)
CHAR ARRAY tmp(20)
BYTE i
 
StrR(fps,tmp)
FOR i=1 TO 5
DO
text(i-1)=tmp(i)-32
OD
RETURN
 
PROC Main()
BYTE CH=$02FC
CARD beg,end
REAL fps
 
PrepareScreen()
beg=GetFrame()
DO
FillNoise()
end=GetFrame()
CalcFPS(end-beg,fps)
PrintFPS(fps)
beg=end
UNTIL CH#$FF
OD
CH=$FF
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Image_noise.png Screenshot from Atari 8-bit computer]
 
=={{header|Ada}}==
{{libheader|Lumen}}
noise.ads:
<langsyntaxhighlight Adalang="ada">with Lumen.Image;
 
package Noise is
Line 26 ⟶ 165:
function Create_Image (Width, Height : Natural) return Lumen.Image.Descriptor;
 
end Noise;</langsyntaxhighlight>
 
noise.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Discrete_Random;
 
package body Noise is
Line 56 ⟶ 195:
end Create_Image;
 
end Noise;</langsyntaxhighlight>
 
test_noise.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Calendar;
with Ada.Text_IO;
with System.Address_To_Access_Conversions;
Line 237 ⟶ 376:
when Program_End =>
null;
end Test_Noise;</langsyntaxhighlight>
 
=={{header|Axe}}==
Line 248 ⟶ 387:
This example gets steady 48 FPS on a TI-84 Plus Silver Edition running at 15 MHz. It gets 26 FPS when running at 6 MHz. Some pixels appear gray because the duration of each frame is shorter than the screen's notoriously slow response time. If a pixel is toggled very quickly, it never has time to fully transition to white or black.
 
<langsyntaxhighlight lang="axe">.Enable 15 MHz full speed mode
Full
.Disable memory access delays (adds 1 FPS)
Line 290 ⟶ 429:
Lbl FPS
N++
Return</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> dx% = 320
dy% = 240
images% = 100000
Line 329 ⟶ 468:
SYS "SetWindowText", @hwnd%, "BBC BASIC: " + STR$(frame%*100 DIV TIME) + " fps"
ENDIF
UNTIL FALSE</langsyntaxhighlight>
[[File:image_noise_bbc.jpg]]
 
Line 336 ⟶ 475:
{{libheader|SDL}}
 
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <time.h>
Line 385 ⟶ 524:
surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);
blit_noise(surf);
}</langsyntaxhighlight>
===Fast OpenGL method===
{{libheader|GLUT}}
Depending on your hardware, you might be able to get thousands of frames per second. Compiled with <code>gcc -lglut -lGL -g -Wall -O2</code>.
<langsyntaxhighlight lang="c">#include <GL/glut.h>
#include <GL/gl.h>
#include <stdio.h>
Line 435 ⟶ 574:
glutMainLoop();
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
Max 185 FPS on .NET 4.0/Windows 7 64-bit on Athlon II X4 620 - ATI Radeon X1200.
 
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
 
class Program
{
static Size size = new Size(320, 240);
static Rectangle rectsize = new Rectangle(new Point(0, 0), size);
static int numpixels = size.Width * size.Height;
static int numbytes = numpixels * 3;
 
static PictureBox pb;
static BackgroundWorker worker;
 
static double time = 0;
static double frames = 0;
static Random rand = new Random();
 
static byte tmp;
static byte white = 255;
static byte black = 0;
static int halfmax = int.MaxValue / 2; // more voodoo! calling Next() is faster than Next(2)!
 
static IEnumerable<byte> YieldVodoo()
{
// Yield 3 times same number (i.e 255 255 255) for numpixels times.
 
for (int i = 0; i < numpixels; i++)
{
tmp = rand.Next() < halfmax ? black : white; // no more lists!
 
// no more loops! yield! yield! yield!
yield return tmp;
yield return tmp;
yield return tmp;
}
}
 
static Image Randimg()
{
// Low-level bitmaps
var bitmap = new Bitmap(size.Width, size.Height);
var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
 
Marshal.Copy(
YieldVodoo().ToArray<byte>(),// source
0, // start
data.Scan0, // scan0 is a pointer to low-level bitmap data
numbytes); // number of bytes in source
 
bitmap.UnlockBits(data);
return bitmap;
}
 
[STAThread]
static void Main()
{
var form = new Form();
 
form.AutoSize = true;
form.Size = new Size(0, 0);
form.Text = "Test";
 
form.FormClosed += delegate
{
Application.Exit();
};
 
worker = new BackgroundWorker();
 
worker.DoWork += delegate
{
System.Threading.Thread.Sleep(500); // remove try/catch, just wait a bit before looping
 
while (true)
{
var a = DateTime.Now;
pb.Image = Randimg();
var b = DateTime.Now;
 
time += (b - a).TotalSeconds;
frames += 1;
 
if (frames == 30)
{
Console.WriteLine("{0} frames in {1:0.000} seconds. ({2:0} FPS)", frames, time, frames / time);
 
time = 0;
frames = 0;
}
}
};
 
worker.RunWorkerAsync();
 
FlowLayoutPanel flp = new FlowLayoutPanel();
form.Controls.Add(flp);
 
pb = new PictureBox();
pb.Size = size;
 
flp.AutoSize = true;
flp.Controls.Add(pb);
 
form.Show();
Application.Run();
}
}</syntaxhighlight>
 
=={{header|C++}}==
===Version 1 (windows.h)===
[[File:noise_cpp.png]]
<langsyntaxhighlight lang="cpp">
#include <windows.h>
#include <sstream>
#include <tchar.h>
//--------------------------------------------------------------------------------------------------
using namespace std;
Line 670 ⟶ 928:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
 
===Version 2 (SDL2)===
=={{header|C sharp|C#}}==
{{libheader|SDL2}}
Max 185 FPS on .NET 4.0/Windows 7 64-bit on Athlon II X4 620 - ATI Radeon X1200.
'''Source:''' https://gist.github.com/KatsumiKougen/58c53e77dc45e4e3a13661ff7b38c1ea
<syntaxhighlight lang="cpp">
// Standard C++ stuff
#include <iostream>
#include <string>
#include <random>
 
// SDL2 stuff
<lang csharp>using System;
#include "SDL2/SDL.h"
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
 
// Other crazy stuffs
class Program
#define SCREEN_WIDTH 320
{
#define SCREEN_HEIGHT 240
static Size size = new Size(320, 240);
#define COLOUR_BLACK 0, 0, 0, 0xff
static Rectangle rectsize = new Rectangle(new Point(0, 0), size);
#define COLOUR_WHITE 0xff, 0xff, 0xff, 0xff
static int numpixels = size.Width * size.Height;
static int numbytes = numpixels * 3;
 
// Compile: g++ -std=c++20 -Wall -Wextra -pedantic ImageNoise.cpp -o ImageNoise -lSDL2
static PictureBox pb;
static BackgroundWorker worker;
 
template <class RandomGenerator>
static double time = 0;
void BlitNoise(SDL_Renderer *r, int width, int height, auto &dist, RandomGenerator &generator) {
static double frames = 0;
staticfor Random(int randy = new0; Random()y < height; ++y) {
for (int x = 0; x < width; ++x) {
 
// Use the random number generator in C++ Standard Library to determine draw colour
static byte tmp;
if (dist(generator) == 0)
static byte white = 255;
// Set colour to black
static byte black = 0;
SDL_SetRenderDrawColor(r, COLOUR_BLACK);
static int halfmax = int.MaxValue / 2; // more voodoo! calling Next() is faster than Next(2)!
else if (dist(generator) == 1)
 
// Set colour to white
static IEnumerable<byte> YieldVodoo()
SDL_SetRenderDrawColor(r, COLOUR_WHITE);
{
// Yield 3 times same number (i.e// 255Go 255through 255)every forscanline, numpixelsand times.put pixels
SDL_RenderDrawPoint(r, x, y);
 
for (int i = 0; i < numpixels; i++)
{
tmp = rand.Next() < halfmax ? black : white; // no more lists!
 
// no more loops! yield! yield! yield!
yield return tmp;
yield return tmp;
yield return tmp;
}
}
}
 
void UpdateFPS(unsigned &frame_count, unsigned &timer, SDL_Window *window) {
static Image Randimg()
static Uint64 LastTime = 0;
{
std::string NewWindowTitle;
// Low-level bitmaps
Uint64 Time = SDL_GetTicks(),
var bitmap = new Bitmap(size.Width, size.Height);
Delta = Time - LastTime;
var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
timer += Delta;
 
if (timer > 1000) Marshal.Copy({
unsigned ElapsedTime = timer / 1000;
YieldVodoo().ToArray<byte>(),// source
NewWindowTitle = "Image noise - " + std::to_string((int)((float)frame_count/(float)ElapsedTime)) + " FPS"; // Dirty string trick
0, // start
SDL_SetWindowTitle(window, const_cast<char*>(NewWindowTitle.c_str()));
data.Scan0, // scan0 is a pointer to low-level bitmap data
timer = 0;
numbytes); // number of bytes in source
frame_count = 0;
 
bitmapNewWindowTitle.UnlockBitsclear(data);
return bitmap;
}
LastTime = Time;
}
 
int main() {
[STAThread]
std::random_device Device; // Random number device
static void Main()
std::mt19937_64 Generator(Device()); // Random number generator
{
std::uniform_int_distribution ColourState(0, 1); // Colour state
var form = new Form();
unsigned Frames = 0,
 
form.AutoSize Timer = true0;
form.Size = new Size(0, 0);
SDL_Window *Window = NULL; // Define window
form.Text = "Test";
SDL_Renderer *Renderer = NULL; // Define renderer
 
form.FormClosed += delegate
// Init everything just {for sure
SDL_Init(SDL_INIT_EVERYTHING);
Application.Exit();
};
// Set window size to 320x240, always shown
 
Window = SDL_CreateWindow("Image noise - ?? FPS", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
worker = new BackgroundWorker();
Renderer = SDL_CreateRenderer(Window, -1, SDL_RENDERER_ACCELERATED);
 
worker.DoWork += delegate
// Set background colour {to white
SDL_SetRenderDrawColor(Renderer, COLOUR_WHITE);
System.Threading.Thread.Sleep(500); // remove try/catch, just wait a bit before looping
SDL_RenderClear(Renderer);
 
while (true)
// Create an event handler and a "quit" {flag
SDL_Event e;
var a = DateTime.Now;
bool pb.ImageKillWindow = Randimg()false;
var b = DateTime.Now;
// The window runs until the "quit" flag is set to true
 
while (!KillWindow) {
time += (b - a).TotalSeconds;
while (SDL_PollEvent(&e) != 0) frames += 1;{
// Go through the events in the queue
 
ifswitch (framese.type) == 30){
{// Event: user hits a key
case SDL_QUIT: case SDL_KEYDOWN:
Console.WriteLine("{0} frames in {1:0.000} seconds. ({2:0} FPS)", frames, time, frames / time);
// Destroy window
 
timeKillWindow = 0true;
frames = 0break;
}
}
};
// Render the noise
BlitNoise(Renderer, SCREEN_WIDTH, SCREEN_HEIGHT, ColourState, Generator);
SDL_RenderPresent(Renderer);
// Increment the "Frames" variable.
// Then show the FPS count in the window title.
++Frames;
UpdateFPS(Frames, Timer, Window);
}
// Destroy renderer and window
SDL_DestroyRenderer(Renderer);
SDL_DestroyWindow(Window);
SDL_Quit();
return 0;
}
</syntaxhighlight>
 
{{output}}
worker.RunWorkerAsync();
<center>[[File:C++ image noise SDL2.gif|280px]]</center>
 
FlowLayoutPanel flp = new FlowLayoutPanel();
form.Controls.Add(flp);
 
pb = new PictureBox();
pb.Size = size;
 
flp.AutoSize = true;
flp.Controls.Add(pb);
 
form.Show();
Application.Run();
}
}</lang>
 
=={{header|Common Lisp}}==
{{libheader|lispbuilder-sdl}}
noise_sdl.lisp:
<langsyntaxhighlight lang="lisp">;; (require :lispbuilder-sdl)
 
(defun draw-noise (surface)
Line 831 ⟶ 1,084:
 
(main)
</syntaxhighlight>
</lang>
 
 
=={{header|D}}==
{{trans|C}}
<langsyntaxhighlight Dlang="d">import std.stdio, std.random, sdl.SDL;
 
void main() {
Line 859 ⟶ 1,111:
lastTime = time;
}
}</langsyntaxhighlight>
This D version shows about 155 FPS, while on the same PC the C version shows about 180 FPS.
 
Generating random bits with the C core.stdc.stdlib.rand the performance becomes about the same of the C version.
=={{header|Delphi}}==
{{libheader| Winapi.Windows}}
{{libheader| System.SysUtils}}
{{libheader| Vcl.Forms}}
{{libheader| Vcl.Graphics}}
{{libheader| Vcl.Controls}}
{{libheader| System.Classes}}
{{libheader| Vcl.ExtCtrls}}
<syntaxhighlight lang="delphi">
unit Main;
 
interface
 
uses
Winapi.Windows, System.SysUtils, Vcl.Forms, Vcl.Graphics, Vcl.Controls,
System.Classes, Vcl.ExtCtrls;
 
type
TfmNoise = class(TForm)
tmr1sec: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure tmr1secTimer(Sender: TObject);
end;
 
var
fmNoise: TfmNoise;
Surface: TBitmap;
FrameCount: Cardinal = 0;
 
implementation
 
{$R *.dfm}
 
procedure TfmNoise.FormCreate(Sender: TObject);
begin
Surface := TBitmap.Create;
Surface.SetSize(320, 240);
Surface.PixelFormat := pf1bit;
Randomize;
end;
 
procedure TfmNoise.FormDestroy(Sender: TObject);
begin
Surface.Free;
end;
 
type
PDWordArray = ^TDWordArray;
 
TDWordArray = array[0..16383] of DWord;
 
procedure TfmNoise.FormPaint(Sender: TObject);
var
x, y: Integer;
line: PWordArray;
begin
with Surface do
for y := 0 to Height - 1 do
begin
line := Surface.ScanLine[y];
for x := 0 to (Width div 16) - 1 do
line[x] := Random($FFFF);
// Fill 16 pixels at same time
end;
 
Canvas.Draw(0, 0, Surface);
Inc(FrameCount);
Application.ProcessMessages;
Invalidate;
end;
 
procedure TfmNoise.tmr1secTimer(Sender: TObject);
begin
Caption := 'FPS: ' + FrameCount.ToString;
FrameCount := 0;
end;
 
end.</syntaxhighlight>
Resources form:
<syntaxhighlight lang="delphi">
object fmNoise: TfmNoise
Left = 0
Top = 0
BorderIcons = [biSystemMenu]
BorderStyle = bsSingle
Caption = 'fmNoise'
ClientHeight = 240
ClientWidth = 320
OnCreate = FormCreate
OnDestroy = FormDestroy
OnPaint = FormPaint
object tmr1sec: TTimer
Interval = 2000
OnTimer = tmr1secTimer
end
end
</syntaxhighlight>
{{out}}
<pre>
1400 to 1600 FPS
</pre>
=={{header|EasyLang}}==
[https://easylang.dev/show/#cod=XZDBqoMwEEX3fsWhi0dLaRp1UbPw/Yi4kDSCUI3EUPTvH9EE+roImTl3Zm4ys7OaeTGelQ2NQGSAti/r0CEc7duwcqcUBdtxB+6M9khRhpOJzE500zB23gSxd1xr8hAOPcu2+GE03PCS38jT6FzyqCI4bG9FTHeLSlLI//p3f5V0b1YfvO+cPz0v/HCin5dTqpPU6VUR9Y6afU5aQNNS0yClRClFu//LOtZQiLeUuUrN1rElnKuE4WO19tW4bnoOk6doY4E4/ET2Bw== Run it]
 
<syntaxhighlight>
proc pset x y c . .
color c
move x / 3.2 y / 3.2
rect 0.3 0.3
.
on animate
fr += 1
if systime - t0 >= 1
move 10 78
color -2
rect 80 20
color -1
move 10 80
text fr / (systime - t0) & " fps"
t0 = systime
fr = 0
.
col[] = [ 000 999 ]
for x = 0 to 319
for y = 0 to 199
pset x y col[randint 2]
.
.
.
</syntaxhighlight>
 
=={{header|Euler Math Toolbox}}==
Line 868 ⟶ 1,252:
Currently, Euler Math Toolbox does not have optimized routines to plot matrices with color information. The frames per second are consequently not really good.
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function noiseimg () ...
$aspect(320,240); clg;
Line 882 ⟶ 1,266:
>noiseimg
2.73544353263
</syntaxhighlight>
</lang>
 
=={{header|F Sharp|F#}}==
This implementation includes two methods to update the pixels values. One uses unsafe methods and can do 350 fps on my machine, the second uses safe code to marshal the new values onto the bitmap data and can do 240 fps on the same machine.
<langsyntaxhighlight lang="fsharp">open System.Windows.Forms
open System.Drawing
open System.Drawing.Imaging
Line 959 ⟶ 1,343:
Application.Run()
0
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
Line 965 ⟶ 1,349:
~150 FPS
 
<langsyntaxhighlight lang="factor">USING: accessors calendar images images.viewer kernel math
math.parser models models.arrow random sequences threads timers
ui ui.gadgets ui.gadgets.labels ui.gadgets.packs ;
Line 1,034 ⟶ 1,418:
MAIN-WINDOW: open-noise-window
{ { title "Black and White noise" } }
<bw-noise-gadget> with-fps >>gadgets ;</langsyntaxhighlight>
 
 
=={{header|Forth}}==
{{works with|gforth|0.7.3}}
{{libheader|SDL2}}
 
<syntaxhighlight lang="Forth">\ Bindings to SDL2 functions
s" SDL2" add-lib
\c #include <SDL2/SDL.h>
c-function sdl-init SDL_Init n -- n
c-function sdl-quit SDL_Quit -- void
c-function sdl-createwindow SDL_CreateWindow a n n n n n -- a
c-function sdl-createrenderer SDL_CreateRenderer a n n -- a
c-function sdl-setdrawcolor SDL_SetRenderDrawColor a n n n n -- n
c-function sdl-drawpoint SDL_RenderDrawPoint a n n -- n
c-function sdl-renderpresent SDL_RenderPresent a -- void
c-function sdl-delay SDL_Delay n -- void
c-function sdl-ticks SDL_GetTicks -- n
 
require random.fs
 
0 value window
0 value renderer
240 constant height
320 constant width
 
: black 0 0 0 255 ;
: white 255 255 255 255 ;
: black-or-white 2 random if black else white then ;
 
: init-image ( -- )
$20 sdl-init drop
s\" Rosetta Task : Image Noise\x0" drop 0 0 width height $0 sdl-createwindow to window
window -1 $2 sdl-createrenderer to renderer
page
;
 
: image-noise-generate
height 0 do
width 0 do
renderer black-or-white sdl-setdrawcolor drop
renderer i j sdl-drawpoint drop
loop
loop
;
 
: .FPS swap - 1000 swap / 0 0 at-xy . ." FPS" ;
 
: image-noise
init-image
100 0 do
sdl-ticks
image-noise-generate renderer sdl-renderpresent
sdl-ticks .FPS
loop
sdl-quit
;
 
image-noise</syntaxhighlight>
 
 
 
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' version 13-07-2018
' compile with: fbc -s console
' or: fbc -s gui
 
' hit any to key to stop program
 
Randomize Timer
Screen 13
 
If ScreenPtr = 0 Then
Print "Error setting video mode!"
End
End If
 
Palette 0, 0 ' black
Palette 1, RGB(255, 255, 255) ' white
 
Dim As UInteger c, x, y, Col
Dim As Double fps, t = Timer
 
' empty keyboard buffer
While InKey <> "" : Wend
 
While InKey = ""
 
For x = 0 To 319
For y = 0 To 199
' color is as integer, a float gets rounded off by FreeBASIC
PSet(x, y), Rnd
Next
Next
c += 1
fps = c / (Timer - t)
WindowTitle "fps = " + Str(fps)
 
Wend</syntaxhighlight>
 
 
=={{header|FutureBasic}}==
FB has native image noise filters.
<syntaxhighlight lang="futurebasic">
 
_window = 1
begin enum output 1
_noiseView
_fpsLabel
end enum
 
void local fn BuildWindow
CGRect r = fn CGRectMake( 0, 0, 340, 300 )
window _window, @"Rosetta Code Image Noise", r, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable
r = fn CGRectMake( 10, 50, 320, 240 )
imageview _noiseView, YES, , r, NSImageScaleAxesIndependently, NSImageAlignCenter, NSImageFrameNone, _window
r = fn CGRectMake( 20, 10, 280, 24 )
textlabel _fpsLabel, @"Estimated FPS: 60", r, _window
ControlSetAlignment( _fpsLabel, NSTextAlignmentCenter )
end fn
 
local fn CIImageToImageRef( ciImage as CIImageRef ) as ImageRef
CIImageRepRef rep = fn CIImageRepWithCIImage( ciImage )
CGSize size = fn ImageRepSize( rep )
ImageRef image = fn ImageWithSize( size )
ImageAddRepresentation( image, rep )
end fn = image
 
local fn NoiseCIImage as CIImageRef
CIFilterRef filter = fn CIFilterWithName( @"CIPhotoEffectNoir" )
ObjectSetValueForKey( filter, fn ObjectValueForKey( fn CIFilterWithName(@"CIRandomGenerator"), @"outputImage" ), @"inputImage" )
CIFilterSetDefaults( filter )
CIImageRef outputCIImage = fn CIImageByCroppingToRect( fn CIFilterOutputImage( filter ), fn CGRectMake( rnd(1000), rnd(1000), 500, 500 ) )
end fn = outputCIImage
 
local fn BuildNoiseView
block NSInteger renderedFrames
renderedFrames = 0
timerbegin, 1.0/60, YES
CIImageRef noiseCIImage = fn NoiseCIImage
ImageRef noiseImage = fn CIImageToImageRef( noiseCIImage )
ImageViewSetImage( _noiseView, noiseImage )
renderedFrames++
if( renderedFrames == 60 )
ControlSetStringValue( _fpsLabel, fn StringWithFormat( @"Estimated FPS: %ld", renderedFrames ) )
renderedFrames = 0
end if
timerend
end fn
 
void local fn DoDialog( ev as long, tag as long, wnd as long )
select ( ev )
case _windowWillClose : end
end select
end fn
 
 
randomize
 
on dialog fn DoDialog
 
fn BuildWindow
fn BuildNoiseView
 
HandleEvents
</syntaxhighlight>
{{output}}
[[File:Image Noise.png]]
 
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,124 ⟶ 1,682:
}
}
</syntaxhighlight>
</lang>
===Optimized example===
A second example that is somewhat more optimized but maybe more complicated.
(~3000fps on a Thinkpad x220 laptop)
<langsyntaxhighlight lang="go">package main
 
/* Note, the x-go-binding/ui/x11 lib is under development and has as a temp solution
set the x window to a static hightheight and with, you have to manualy set these
to 240 x 320 in code.google.com/p/x-go-binding/ui/x11/conn.go */
 
Line 1,226 ⟶ 1,784:
}
}
</syntaxhighlight>
</lang>
[[File:GoNoise.png]]
 
Line 1,232 ⟶ 1,790:
This uses the GLFW-b bindings for GLFW 3 support:
<pre>cabal install glfw-b</pre>
<langsyntaxhighlight Haskelllang="haskell">import qualified Graphics.Rendering.OpenGL as GL
import qualified Graphics.UI.GLFW as GLFW
import qualified Foreign as F
Line 1,299 ⟶ 1,857:
case key of
GLFW.Key'Q -> GLFW.setWindowShouldClose win True
_ -> return ()</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,309 ⟶ 1,867:
* Using DrawImage to draw a randomly constructed bi-level images(see pg 157 of the graphics book, speed ~= 10x)
 
<langsyntaxhighlight Iconlang="icon">link printf
 
procedure main()
Line 1,327 ⟶ 1,885:
Event() # wait for any window event
close(&window)
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/src/procs/printf.icn printf.icn provides a family of print formatting routines]
 
=={{header|J}}==
<langsyntaxhighlight lang="j">coclass'example'
(coinsert[require)'jzopengl'
Line 1,380 ⟶ 1,938:
)
p_run''</langsyntaxhighlight>
 
The script auto-starts when run (that last line <code><nowiki>p_run''</nowiki></code> is responsible for the auto-start.
Line 1,400 ⟶ 1,958:
 
- Very fast: 1000+ FPS on a 2.8 GHz Core Duo (with 64-bit JRE). This is capped because the maximum resolution of the timers available is 1 ms
<langsyntaxhighlight lang="java">import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
Line 1,519 ⟶ 2,077:
});
}
}</langsyntaxhighlight>[[File:javanoise2.png]]
 
=={{header|JavaScript}}==
[http://jsfiddle.net/bZJvr/ jsFiddle Demo]
 
<langsyntaxhighlight lang="javascript"><body>
<canvas id='c'></canvas>
 
Line 1,572 ⟶ 2,130:
animate();
</script>
</body></langsyntaxhighlight>
About 59 frames/second on Firefox 4.
 
=={{header|Julia}}==
With Gtk, gets about 80 frames per second on a older, dual core 3 Ghz processor.
<syntaxhighlight lang="julia">using Gtk, GtkUtilities
 
function randbw(ctx, w, h)
pic = zeros(Int64, w, h)
for i in 1:length(pic)
pic[i] = rand([1, 0])
end
copy!(ctx, pic)
end
 
const can = @GtkCanvas()
const win = GtkWindow(can, "Image Noise", 320, 240)
 
@guarded draw(can) do widget
ctx = getgc(can)
h = height(can)
w = width(can)
randbw(ctx, w, h)
end
 
show(can)
const cond = Condition()
endit(w) = notify(cond)
signal_connect(endit, win, :destroy)
 
while true
frames = 0
t = time()
for _ in 1:100
draw(can)
show(can)
sleep(0.0001)
frames += 1
end
fps = round(frames / (time() - t), digits=1)
set_gtk_property!(win, :title, "Image Noise: $fps fps")
end
 
wait(cond)
</syntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|Java}}
<syntaxhighlight lang="scala">// version 1.2.10
 
import java.awt.*
import java.awt.event.*
import java.awt.image.*
import java.util.Random
import javax.swing.*
 
class ImageNoise {
var framecount = 0
var fps = 0
lateinit var image: BufferedImage
val kernel: Kernel
lateinit var cop: ConvolveOp
val frame = JFrame("Java Image Noise")
 
val panel = object : JPanel() {
private var showFps = 0 // 0 = blur + FPS; 1 = FPS only; 2 = neither
private val ma = object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
showFps = (showFps + 1) % 3
}
}
 
init {
addMouseListener(ma)
preferredSize = Dimension(320, 240)
}
 
override fun paintComponent(g1: Graphics) {
val g = g1 as Graphics2D
drawNoise()
g.drawImage(image, 0, 0, null)
if (showFps == 0) {
// add blur behind FPS
val xblur = width - 130
val yblur = height - 32
val bc = image.getSubimage(xblur, yblur, 115, 32)
val bs = BufferedImage(
bc.width, bc.height, BufferedImage.TYPE_BYTE_GRAY
)
cop.filter(bc, bs)
g.drawImage(bs, xblur, yblur, null)
}
if (showFps <= 1) {
// add FPS text
g.color = Color.RED
g.font = Font("Monospaced", Font.BOLD, 20)
g.drawString("FPS: $fps", width - 120, height - 10)
}
framecount++
}
}
 
// Timer to trigger update display, with 1 ms delay
val repainter = Timer(1, object: ActionListener {
override fun actionPerformed(e: ActionEvent) = panel.repaint()
})
 
// Timer to check FPS, once per second
val framerateChecker = Timer(1000, object : ActionListener {
override fun actionPerformed(e: ActionEvent) {
fps = framecount
framecount = 0
}
})
 
init {
// Intitalize kernel describing blur, and convolve operation based on this
val vals = FloatArray(121) { 1.0f / 121.0f }
kernel = Kernel(11, 11, vals)
cop = ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null)
 
// Initialize frame and timers
with (frame) {
add(panel)
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
pack()
isVisible = true
}
repainter.start()
framerateChecker.start()
}
 
fun drawNoise() {
val w = panel.width
val h = panel.height
 
// Check if our image is initialized or window has been resized,
// requiring new image
if (!this::image.isInitialized || image.width != w || image.height != h) {
image = BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY)
}
val rand = Random()
val data = IntArray(w * h)
// Each int has 32 bits so we can use each bit for a different pixel
// - much faster
for (x in 0 until w * h / 32) {
var r = rand.nextInt()
for (i in 0..31) {
data[x * 32 + i] = (r and 1) * Int.MAX_VALUE
r = r ushr 1
}
}
// Copy raw data to the image's raster
image.raster.setPixels(0, 0, w, h, data)
}
}
 
fun main(args: Array<String>) {
// Invoke GUI on the Event Dispatching Thread
SwingUtilities.invokeLater(object: Runnable {
override fun run() {
ImageNoise()
}
})
}</syntaxhighlight>
 
{{out}}
<pre>
Similar to Java entry
</pre>
 
=={{header|Liberty BASIC}}==
Generates the random bitmap programmatically, then chops it each time in a different way.
<syntaxhighlight lang="lb">
<lang lb>
WindowWidth =411
w =320
Line 1,650 ⟶ 2,376:
close #w
end
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
*Note, you will need to insert a plot component to get this to work.
<syntaxhighlight lang="maple">
<lang Maple>
a:=0;
t:=time[real]();
Line 1,665 ⟶ 2,391:
 
end do:
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">
<lang Mathematica>
time = AbsoluteTime[]; Animate[
Column[{Row[{"FPS: ", Round[n/(AbsoluteTime[] - time)]}],
RandomImage[1, {320, 240}]}], {n, 1, Infinity, 1}]
</syntaxhighlight>
</lang>
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
<lang MAXScript>
try destroydialog testRollout catch ()
Line 1,709 ⟶ 2,435:
createdialog testrollout
</syntaxhighlight>
</lang>
 
=={{header|MiniScript}}==
This implementation is for use with [http://miniscript.org/MiniMicro Mini Micro].
<syntaxhighlight lang="miniscript">
clear
tileSetLength = 32
width = 320
height = 240
cellSize = [960/width, 600/height]
colors = [color.black, color.white]
 
newImg = function
img = Image.create(tileSetLength, 1)
for i in range(0, tileSetLength - 1)
img.setPixel i, 0, colors[rnd * 2]
end for
return img
end function
 
display(5).mode = displayMode.tile
td = display(5)
td.cellSize = cellSize
td.extent = [width, height]
td.tileSetTileSize = 1
for x in range(0, width - 1)
for y in range(0, height - 1)
td.setCell x, y, rnd * tileSetLength
end for
end for
frames = 0
startTime = time
while true
td.tileSet = newImg
frames += 1
dt = time - startTime
if dt >= 1 then
text.row = 25; print "FPS: " + round(frames / dt, 2)
frames = 0
startTime = time
end if
end while
</syntaxhighlight>
[[File:Minimicro-noise-32.gif]]
 
=={{header|Nim}}==
 
===Using OpenGL===
 
{{trans|C}}
{{libheader|OpenGL}}
 
On a small laptop running Manjaro and without a dedicated graphic card, we get 550-600 FPS.
 
<syntaxhighlight lang="nim">import times
 
import opengl
import opengl/glut
 
const
W = 320
H = 240
SLen = W * H div sizeof(int)
 
var
frame = 0
bits: array[SLen, uint]
last, start: Time
 
#---------------------------------------------------------------------------------------------------
 
proc render() {.cdecl.} =
## Render the window.
 
var r = bits[0] + 1
for i in countdown(bits.high, 0):
r *= 1103515245
bits[i] = r xor bits[i] shr 16
 
glClear(GL_COLOR_BUFFER_BIT)
glBitmap(W, H, 0, 0, 0, 0, cast[ptr GLubyte](bits.addr))
glFlush()
 
inc frame
if (frame and 15) == 0:
let t = getTime()
if t > last:
last = t
echo "fps: ", frame.float / (t - start).inSeconds.float
 
#---------------------------------------------------------------------------------------------------
 
proc initGfx(argc: ptr cint; argv: pointer) =
## Initialize OpenGL rendering.
 
glutInit(argc, argv)
glutInitDisplayMode(GLUT_RGB)
glutInitWindowSize(W, H)
glutIdleFunc(render)
discard glutCreateWindow("Noise")
glutDisplayFunc(render)
loadExtensions()
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
var argc: cint = 0
initGfx(addr(argc), nil)
start = getTime()
last = start
glutMainLoop()</syntaxhighlight>
 
===Using library "Rapid"===
{{libheader|rapid}}
 
Unfortunately, these examples no longer work for some reason.
 
Naive implementation:
 
<syntaxhighlight lang="nim">import random
 
import rapid/gfx
 
var
window = initRWindow()
.size(320, 240)
.title("Rosetta Code - image noise")
.open()
surface = window.openGfx()
 
surface.loop:
draw ctx, step:
ctx.clear(gray(0))
ctx.begin()
for y in 0..window.height:
for x in 0..window.width:
if rand(0..1) == 0:
ctx.point((x.float, y.float))
ctx.draw(prPoints)
echo 1 / (step / 60)
update step:
discard step</syntaxhighlight>
 
Optimized implementation using shaders:
 
<syntaxhighlight lang="nim">import random
 
import rapid/gfx
 
var
window = initRWindow()
.size(320, 240)
.title("Rosetta Code - image noise")
.open()
surface = window.openGfx()
 
let
noiseShader = surface.newRProgram(RDefaultVshSrc, """
uniform float time;
 
float rand(vec2 pos) {
return fract(sin(dot(pos.xy + time, vec2(12.9898,78.233))) * 43758.5453123);
}
 
vec4 rFragment(vec4 col, sampler2D tex, vec2 pos, vec2 uv) {
return vec4(vec3(step(0.5, rand(uv))), 1.0);
}
""")
 
surface.vsync = false
surface.loop:
draw ctx, step:
noiseShader.uniform("time", time())
ctx.program = noiseShader
ctx.begin()
ctx.rect(0, 0, surface.width, surface.height)
ctx.draw()
echo 1 / (step / 60)
update step:
discard step</syntaxhighlight>
 
On a Ryzen 5 1600 and a Vega 56 the naive implementation struggles to maintain 10 FPS. The GPU-powered version, however, reaches up to 12000-13000 FPS.
 
=={{header|OCaml}}==
{{libheader|OCamlSDL}}
with the [[OCamlSDL|ocaml-sdl]] bindings:
<langsyntaxhighlight lang="ocaml">let frames =
{ contents = 0 }
 
Line 1,762 ⟶ 2,669:
in
Sys.catch_break true;
blit_noise surf</langsyntaxhighlight>
 
compile to native-code with:
Line 1,780 ⟶ 2,687:
 
In a more idiomatic way, using the modules Graphics and Unix from the standard OCaml library:
<langsyntaxhighlight lang="ocaml">open Graphics
 
let white = (rgb 255 255 255)
Line 1,806 ⟶ 2,713:
with _ ->
flush stdout;
close_graph ()</langsyntaxhighlight>
 
run this script with:
Line 1,818 ⟶ 2,725:
 
[[Image_Noise/OCaml/OpenGL|Equivalent]] of the C-OpenGL method.
 
=={{header|Perl 6}}==
We'll use minimal mappings for SDL2. The resulting code is embarrassingly slow, but it's better than nothing.
 
<lang perl6>use NativeCall;
 
class SDL_Window is repr('CStruct') {}
class SDL_Renderer is repr('CStruct') {}
 
my ($w, $h) = 320, 240;
my SDL_Window $window;
my SDL_Renderer $renderer;
 
constant $sdl-lib = 'libSDL2';
constant SDL_INIT_VIDEO = 0x00000020;
constant SDL_WINDOWPOS_UNDEFINED_MASK = 0x1FFF0000;
constant SDL_WINDOW_SHOWN = 0x00000004;
 
sub SDL_Init(int32 $flag) returns int32 is native($sdl-lib) {*}
sub SDL_Quit() is native($sdl-lib) {*}
 
sub SDL_CreateWindow(Str $title, int $x, int $y, int $w, int $h, int32 $flag) returns SDL_Window is native($sdl-lib) {*}
sub SDL_CreateRenderer(SDL_Window $, int $, int $) returns SDL_Renderer is native($sdl-lib) {*}
sub SDL_SetRenderDrawColor(SDL_Renderer $, int $r, int $g, int $b, int $a) returns Int is native($sdl-lib) {*}
sub SDL_RenderClear(SDL_Renderer $) returns Int is native($sdl-lib) {*}
sub SDL_RenderDrawPoint( SDL_Renderer $, int $x, int $y ) returns Int is native($sdl-lib) {*}
sub SDL_RenderPresent(SDL_Renderer $) is native($sdl-lib) {*}
 
sub render {
SDL_SetRenderDrawColor($renderer, 0, 0, 0, 0);
SDL_RenderClear($renderer);
SDL_SetRenderDrawColor($renderer, 255, 255, 255, 0);
loop (my int $i; $i < $w; $i = $i + 1) {
loop (my int $j; $j < $h; $j = $j + 1) {
SDL_RenderDrawPoint( $renderer, $i, $j ) if Bool.pick
}
}
SDL_RenderPresent($renderer);
}
 
SDL_Init(SDL_INIT_VIDEO);
$window = SDL_CreateWindow(
"some white noise",
SDL_WINDOWPOS_UNDEFINED_MASK, SDL_WINDOWPOS_UNDEFINED_MASK,
$w, $h,
SDL_WINDOW_SHOWN
);
$renderer = SDL_CreateRenderer( $window, -1, 1 );
loop {
my $then = now;
render();
note "{1 / (now - $then)} fps";
}
END { SDL_Quit() }</lang>
 
=={{header|Pascal}}==
Line 1,877 ⟶ 2,730:
{{libheader|SDL}}
It is SDL-internally limited to 200 fps.
<langsyntaxhighlight lang="pascal">Program ImageNoise;
 
uses
Line 1,918 ⟶ 2,771:
lastTime := time;
end;
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">use Gtk3 '-init';
use Glib qw/TRUE FALSE/;
use Time::HiRes qw/ tv_interval gettimeofday/;
 
my $time0 = [gettimeofday];
my $frames = -8; # account for set-up steps before drawing
 
my $window = Gtk3::Window->new();
$window->set_default_size(320, 240);
$window->set_border_width(0);
$window->set_title("Image_noise");
$window->set_app_paintable(TRUE);
 
my $da = Gtk3::DrawingArea->new();
$da->signal_connect('draw' => \&draw_in_drawingarea);
$window->add($da);
$window->show_all();
Glib::Timeout->add (1, \&update);
 
Gtk3->main;
 
sub draw_in_drawingarea {
my ($widget, $cr, $data) = @_;
$cr->set_line_width(1);
for $x (1..320) {
for $y (1..240) {
int rand 2 ? $cr->set_source_rgb(0, 0, 0) : $cr->set_source_rgb(1, 1, 1);
$cr->rectangle( $x, $y, 1, 1);
$cr->stroke;
}
}
}
 
sub update {
$da->queue_draw;
my $elapsed = tv_interval( $time0, [gettimeofday] );
$frames++;
printf "fps: %.1f\n", $frames/$elapsed if $frames > 5;
return TRUE;
}</syntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/pGUI}}
Not optimised, gets about 130 fps.
<syntaxhighlight lang="phix">-- demo\rosetta\ImageNoise.exw
include pGUI.e
 
Ihandle dlg, canvas, timer
cdCanvas cddbuffer, cdcanvas
 
constant TITLE = "Image noise"
 
integer fps = 129 -- (typical value)
 
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/)
integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE")
cdCanvasActivate(cddbuffer)
sequence bw = repeat(0,w*h)
for x=0 to w-1 do
for y=0 to h-1 do
if rand(2)=2 then bw[x*h+y+1] = 255 end if
end for
end for
cdCanvasPutImageRectRGB(cddbuffer, w, h, {bw,bw,bw})
cdCanvasFlush(cddbuffer)
fps += 1
return IUP_DEFAULT
end function
 
atom t1 = time()
 
function timer_cb(Ihandle /*ih*/)
if time()>t1 then
IupSetStrAttribute(dlg, "TITLE", "%s [%g FPS])",{TITLE,fps})
fps = 0
t1 = time()+1
end if
IupUpdate(canvas)
return IUP_IGNORE
end function
 
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
return IUP_DEFAULT
end function
 
procedure main()
IupOpen()
 
canvas = IupCanvas(NULL)
IupSetAttribute(canvas, "RASTERSIZE", "320x240")
IupSetCallback(canvas, "MAP_CB", Icallback("map_cb"))
IupSetCallback(canvas, "ACTION", Icallback("redraw_cb"))
 
timer = IupTimer(Icallback("timer_cb"), 10)
 
dlg = IupDialog(canvas)
IupSetAttribute(dlg, "TITLE", TITLE)
 
IupShow(dlg)
IupSetAttribute(canvas, "RASTERSIZE", NULL)
IupMainLoop()
IupClose()
end procedure
 
main()</syntaxhighlight>
 
=={{header|PicoLisp}}==
This solution works on ErsatzLisp, the Java version of PicoLisp. It creates a 'JFrame' window, and calls inlined Java code to handle the image.
<langsyntaxhighlight PicoLisplang="picolisp">(javac "ImageNoise" "JPanel" NIL
"java.util.*"
"java.awt.*" "java.awt.image.*" "javax.swing.*" )
Line 1,972 ⟶ 2,934:
 
# Start with 25 frames per second
(imageNoise 320 240 25)</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="text">Image_Noise: procedure options (main); /* 3 November 2013 */
declare (start_time, end_time) float (18);
declare (frame, m, n) fixed binary;
Line 2,001 ⟶ 2,963:
end display;
 
end Image_Noise;</langsyntaxhighlight>
 
=={{header|Processing}}==
<syntaxhighlight lang="processing">color black = color(0);
color white = color(255);
 
void setup(){
size(320,240);
// frameRate(300); // 60 by default
}
 
void draw(){
loadPixels();
for(int i=0; i<pixels.length; i++){
if(random(1)<0.5){
pixels[i] = black;
}else{
pixels[i] = white;
}
}
updatePixels();
fill(0,128);
rect(0,0,60,20);
fill(255);
text(frameRate, 5,15);
}</syntaxhighlight>
 
==={{header|Processing Python mode}}===
<syntaxhighlight lang="python">black = color(0)
white = color(255)
 
def setup():
size(320, 240)
# frameRate(30) # 60 by default
 
 
def draw():
loadPixels()
for i in range(len(pixels)):
if random(1) < 0.5:
pixels[i] = black
else:
pixels[i] = white
 
updatePixels()
fill(0, 128)
rect(0, 0, 60, 20)
fill(255)
text(frameRate, 5, 15)</syntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">#filter=0.2 ; Filter parameter for the FPS-calculation
#UpdateFreq=100 ; How often to update the FPS-display
 
Line 2,039 ⟶ 3,049:
Until Not Event
EndIf
ForEver</langsyntaxhighlight>
[[Image:Image_Noise_in_PureBasic.png‎]]
 
Line 2,046 ⟶ 3,056:
{{libheader|PIL}}
 
<langsyntaxhighlight lang="python">import time
import random
import Tkintertkinter
from PIL import Image, ImageTk # PIL libray
from PIL import ImageTk
 
 
class App(object):
class App:
def __init__(self, size, root):
self.root = root
self.root.title("Image Noise Test")
 
self.img = Image.new("RGB1", size)
self.label = Tkintertkinter.Label(root)
self.label.pack()
 
Line 2,063 ⟶ 3,075:
self.frames = 0
self.size = size
self.n_pixels = self.size[0] * self.size[1]
 
self.loop()
 
def loop(self):
self.tastart_time = time.time()
# 13 FPS boost. half integer idea from C#.
rnd = random.random
white = (255, 255, 255)
black = (0, 0, 0)
npixels = self.size[0] * self.size[1]
data = [white if rnd() > 0.5 else black for i in xrange(npixels)]
self.img.putdata(data)
self.pimg = ImageTk.PhotoImage(self.img)
self.label["image"] = self.pimg
self.tb = time.time()
 
self.time += img.putdata(self.tb - self.ta)
[255 if b > 127 else 0 for b in random.randbytes(self.n_pixels)]
)
 
self.bitmap_image = ImageTk.BitmapImage(self.img)
self.label["image"] = self.bitmap_image
 
end_time = time.time()
self.time += end_time - start_time
self.frames += 1
 
if self.frames == 30:
try:
self.fps = self.frames / self.time
except ZeroDivisionError:
self.fps = "INSTANT"
 
print ("%d frames in %3.2f seconds (%s FPS)" %
print(f"{self.frames,} frames in {self.time,:3.2f} self.seconds ({fps} FPS)")
self.time = 0
self.frames = 0
 
self.root.after(1, self.loop)
 
 
def main():
root = Tkintertkinter.Tk()
app = App((320, 240), root)
root.mainloop()
 
 
main()</lang>
if __name__ == "__main__":
About 28 FPS max, Python 2.6.6.
main()
</syntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require 2htdp/image 2htdp/universe)
Line 2,129 ⟶ 3,144:
[on-draw draw]
[on-tick handle-tick (/ 1. 120)])
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
Variant of a script packaged with the SDL2::Raw module.
 
<syntaxhighlight lang="raku" line>use NativeCall;
use SDL2::Raw;
 
my int ($w, $h) = 320, 240;
 
SDL_Init(VIDEO);
 
my SDL_Window $window = SDL_CreateWindow(
"White Noise - Raku",
SDL_WINDOWPOS_CENTERED_MASK, SDL_WINDOWPOS_CENTERED_MASK,
$w, $h,
RESIZABLE
);
 
my SDL_Renderer $renderer = SDL_CreateRenderer( $window, -1, ACCELERATED +| TARGETTEXTURE );
 
my $noise_texture = SDL_CreateTexture($renderer, %PIXELFORMAT<RGB332>, STREAMING, $w, $h);
 
my $pixdatabuf = CArray[int64].new(0, $w, $h, $w);
 
sub render {
my int $pitch;
my int $cursor;
 
# work-around to pass the pointer-pointer.
my $pixdata = nativecast(Pointer[int64], $pixdatabuf);
SDL_LockTexture($noise_texture, SDL_Rect, $pixdata, $pitch);
 
$pixdata = nativecast(CArray[int8], Pointer.new($pixdatabuf[0]));
 
loop (my int $row; $row < $h; $row = $row + 1) {
loop (my int $col; $col < $w; $col = $col + 1) {
$pixdata[$cursor + $col] = Bool.roll ?? 0xff !! 0x0;
}
$cursor = $cursor + $pitch;
}
 
SDL_UnlockTexture($noise_texture);
 
SDL_RenderCopy($renderer, $noise_texture, SDL_Rect, SDL_Rect);
SDL_RenderPresent($renderer);
}
 
my $event = SDL_Event.new;
 
main: loop {
 
while SDL_PollEvent($event) {
my $casted_event = SDL_CastEvent($event);
 
given $casted_event {
when *.type == QUIT {
last main;
}
}
}
 
render();
print fps;
}
 
say '';
 
sub fps {
state $fps-frames = 0;
state $fps-now = now;
state $fps = '';
$fps-frames++;
if now - $fps-now >= 1 {
$fps = [~] "\b" x 40, ' ' x 20, "\b" x 20 ,
sprintf "FPS: %5.2f ", ($fps-frames / (now - $fps-now)).round(.01);
$fps-frames = 0;
$fps-now = now;
}
$fps
}</syntaxhighlight>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program times (elapsed) the generation of 100 frames of random black&white image.*/
parse arg sw sd im . /*obtain optional args from the C.L. */
if sw=='' | sw=="," then sw=320 /*SW specified? No, then use default.*/
Line 2,154 ⟶ 3,250:
$=$ || _ /*append row to $ string.*/
end /*y*/ /* [↑] build the image. */
return</langsyntaxhighlight>
 
=={{header|RPL}}==
RPL can only handle 131x64 screens. Despite such a small size, displaying graphics is very slow: FPH (frames Per Hour) would be a more appropriate unit.
====HP 28/48 version====
≪ TICKS (0,0) PMIN (130,64) PMAX
'''DO'''
CLLCD
'''IF''' TICKS OVER - 8192 / B→R '''THEN'''
LAST INV 3 DISP '''END'''
0 130 '''FOR''' x
0 63 '''FOR''' y
'''IF''' RAND 0.5 > '''THEN''' x y R→C PIXEL '''END'''
'''NEXT NEXT'''
'''UNTIL''' 0 '''END'''
≫ '<span style="color:blue">NOISE</span>' STO
HP-28 users shall replace <code>TICKS</code> by a <code>SYSEVAL</code> call, which address value depends on their ROM version.
====HP-48G version====
From the HP-48G model, the graphics system has been completely reviewed, and so the commands:
≪ TICKS
'''DO'''
ERASE
'''IF''' TICKS OVER - 8192 / B→R '''THEN'''
LASTARG INV 1 →GROB PICT RCL {#0h #42h} ROT GOR PICT STO {#0 #0} PVIEW '''END'''
0 130 '''FOR''' x
0 63 '''FOR''' y
'''IF''' RAND 0.5 > '''THEN''' x R→B y R→B 2 →LIST PIXON '''END'''
'''NEXT NEXT'''
{#0 #0} PVIEW
'''UNTIL''' 0 '''END'''
≫ '<span style="color:blue">NOISE</span>' STO
FPS = 0.0095
 
=={{header|Ruby}}==
Line 2,160 ⟶ 3,287:
{{libheader|ruby-opengl}}
 
<langsyntaxhighlight lang="ruby">require 'rubygems'
require 'gl'
require 'glut'
Line 2,182 ⟶ 3,309:
 
Glut.glutCreateWindow "noise"
Glut.glutMainLoop</langsyntaxhighlight>
 
{{libheader|rubygems}}
{{libheader|JRubyArt}}
JRubyArt is a port of processing to ruby.
<syntaxhighlight lang="ruby">
PALLETE = %w[#000000 #FFFFFF]
attr_reader :black, :dim, :white
def settings
size(320, 240)
end
 
def setup
sketch_title 'Image Noise'
@black = color(PALLETE[0])
@white = color(PALLETE[1])
@dim = width * height
load_pixels
end
 
def draw
dim.times { |idx| pixels[idx] = (rand < 0.5) ? black : white }
update_pixels
fill(0, 128)
rect(0, 0, 60, 20)
fill(255)
text(frame_rate, 5, 15)
end
</syntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">begSec = time$("seconds")
graphic #g, 320,240
tics = 320 * 240
Line 2,197 ⟶ 3,352:
print "Seconds;";totSec;" Count:";tics;" Tics / sec:";tics/totSec;" fps:";1/totSec
render #g
#g "flush"</langsyntaxhighlight>
 
=={{header|Scala}}==
This is basically the same as the Java version, except without using BufferedImage.
<langsyntaxhighlight lang="scala">
import java.awt.event.{ActionEvent, ActionListener}
import swing.{Panel, MainFrame, SimpleSwingApplication}
Line 2,247 ⟶ 3,402:
repainter.start()
framerateChecker.start()
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{libheader|Tk}}
<langsyntaxhighlight lang="tcl">package require Tk
 
proc generate {img width height} {
Line 2,284 ⟶ 3,440:
pack [label .l -image noise]
update
looper</langsyntaxhighlight>
 
{{omit from|PARI/GP}}
 
=={{header|Visual Basic .NET}}==
{{lines too long|Visual Basic .NET}}
Windows Forms Application.
 
<langsyntaxhighlight lang="vbnet">Imports System.Drawing.Imaging
 
Public Class frmSnowExercise
Dim bRunning As Boolean = True
 
Private Sub Form1_Load(ByVal sender As System.Object,
Dim bRunning As Boolean = True
ByVal e As System.EventArgs) Handles MyBase.Load
 
' Tell windows we want to handle all the painting and that we want it
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' to double buffer the form's rectangle (Double Buffering
' removes/ reduces flickering).
SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _
Or ControlStyles.OptimizedDoubleBuffer, True)
UpdateStyles()
 
' Tell windows we want' to handle allPrevent the paintinguser andfrom thatresizing the wewindow. wantOur itdraw tocode doubleis buffernot
' setup to recalculate on the fly.
' the form's rectangle (Double Buffering removes/reduces flickering).
FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint Or ControlStyles.OptimizedDoubleBuffer, True)
MaximizeBox = False
UpdateStyles()
 
' Prevent the user from' resizing theThe window. Oursize drawand codethe isclient notrectangle aren't the same.
' To get the proper dimensions for our exercise we need to
' setup to recalculate on the fly.
' figure out the difference and add it to our 320x240
FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
' requirement.
MaximizeBox = False
Width = 320 + Size.Width - ClientSize.Width
Height = 240 + Size.Height - ClientSize.Height
 
' ThePop the window, sizebring andit to the clientfront rectangleand aren'tgive thewindows time to same.
' reflect the changes.
' To get the proper dimensions for our exercise we need to
Show()
' figure out the difference and add it to our 320x240
' requirement. Activate()
Application.DoEvents()
Width = 320 + Size.Width - ClientSize.Width
Height = 240 + Size.Height - ClientSize.Height
 
' Pop the window, bring' it toHit the frontloop and givekeep going until we windowsreceive timea toclose request.
' reflect the changes. RenderLoop()
Show()
Activate()
Application.DoEvents()
 
' We're done. Exit the application.
' Hit the loop and keep going until we receive a close request.
RenderLoop Close()
 
End Sub
' We're done. Exit the application.
Close()
 
Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _
End Sub
System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
' Close the application when the user hits escape.
If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False
End Sub
 
Private Sub Form1_KeyPressForm1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress_
System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
' Close the application when the user hits escape.
' We'll cancel the form close request if we're still running so we
If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False
' don't get an error during runtime and set the close request flag.
End Sub
e.Cancel = bRunning
bRunning = False
End Sub
 
Private Sub RenderLoop()
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
' We'll cancel the form close request if we're still running so we don't get an error during runtime and set the close request flag.
e.Cancel = bRunning
bRunning = False
End Sub
 
Const cfPadding As Single = 5.0F
Private Sub RenderLoop()
 
Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,
Const cfPadding As Single = 5.0F
PixelFormat.Format32bppArgb)
Dim g As Graphics = Graphics.FromImage(b)
Dim r As New Random(Now.Millisecond)
Dim oBMPData As BitmapData = Nothing
Dim oPixels() As Integer = Nothing
Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}
Dim oStopwatch As New Stopwatch
Dim fElapsed As Single = 0.0F
Dim iLoops As Integer = 0
Dim sFPS As String = "0.0 FPS"
Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)
Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -
oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
 
' Get ourselves a nice, clean, black canvas to work with.
Dim b As New Bitmap(ClientSize.Width, ClientSize.Width, PixelFormat.Format32bppArgb)
g.Clear(Color.Black)
Dim g As Graphics = Graphics.FromImage(b)
Dim r As New Random(Now.Millisecond)
Dim oBMPData As BitmapData = Nothing
Dim oPixels() As Integer = Nothing
Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}
Dim oStopwatch As New Stopwatch
Dim fElapsed As Single = 0.0F
Dim iLoops As Integer = 0
Dim sFPS As String = "0.0 FPS"
Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)
Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding - oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
 
' Get ourselves a nice,' clean,Prep blackour canvasbitmap tofor worka withread.
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),
g.Clear(Color.Black)
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)
 
' PrepAllocate oursufficient bitmapspace for athe pixel data and read.
' flash copy it to our array.
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)
' We want an integer to hold the color for each pixel in the canvas.
Array.Resize(oPixels, b.Width * b.Height)
Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,
oPixels, 0, oPixels.Length)
b.UnlockBits(oBMPData)
' Start looping.
Do
' Find our frame time and add it to the total amount of time
' elapsed since our last FPS update (once per second).
fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F
oStopwatch.Reset() : oStopwatch.Start()
' Adjust the number of loops since the last whole second has elapsed
iLoops += 1
If fElapsed >= 1.0F Then
' Since we've now had a whole second elapse
' figure the Frames Per Second,
' measure our string,
' setup our backing rectangle for the FPS string
' (so it's clearly visible over the snow)
' reset our loop counter
' and our elapsed counter.
sFPS = (iLoops / fElapsed).ToString("0.0") & " FPS"
oFPSSize = g.MeasureString(sFPS, Font)
oFPSBG = New RectangleF(ClientSize.Width - cfPadding -
oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
' We don't set this to 0 in case our frame time has gone
' a bit over 1 second since last update.
fElapsed -= 1.0F
iLoops = 0
End If
 
' Generate our snow.
' Allocate sufficient space for the pixel data and
For i As Integer = 0 To oPixels.GetUpperBound(0)
' flash copy it to our array.
oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))
' We want an integer to hold the color for each pixel in the canvas.
Next
Array.Resize(oPixels, b.Width * b.Height)
Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0, oPixels, 0, oPixels.Length)
b.UnlockBits(oBMPData)
 
' Prep the bitmap for an update.
' Start looping.
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),
Do
ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)
' Find our frame time and add it to the total amount of time
' Flash copy the new data into our bitmap.
' elapsed since our last FPS update (once per second).
Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,
fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F
oPixels.Length)
oStopwatch.Reset()
oStopwatch b.StartUnlockBits(oBMPData)
 
' Adjust the number of loops since' Draw the lastbacking wholefor secondour hasFPS elapseddisplay.
g.FillRectangle(Brushes.Black, oFPSBG)
iLoops += 1
' Draw our FPS.
g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)
 
' Update the form's background and draw.
If fElapsed >= 1.0F Then
' Since we've now hadBackgroundImage a= whole second elapseb
Invalidate(ClientRectangle)
' figure the Frames Per Second,
' measure our string,
' setup our backing rectangle for the FPS string (so it's clearly visible over the snow)
' reset our loop counter
' and our elapsed counter.
sFPS = (iLoops / fElapsed).ToString("0.0") & " FPS"
oFPSSize = g.MeasureString(sFPS, Font)
oFPSBG = New RectangleF(ClientSize.Width - cfPadding - oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
fElapsed -= 1.0F ' We don't set this to 0 incase our frame time has gone a bit over 1 second since last update.
iLoops = 0
End If
 
' GenerateLet windows handle some ourqueued snowevents.
For i As Integer = 0 To oPixelsApplication.GetUpperBoundDoEvents(0)
Loop While bRunning
oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))
Next
 
End Sub
' Prep the bitmap for an update.
End Class
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)
</syntaxhighlight>
' Flash copy the new data into our bitmap.
Sample:<BR>
Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0, oPixels.Length)
[[Image:SHSnowExercise.jpg]]
b.UnlockBits(oBMPData)
 
=={{header|Wren}}==
' Draw the backing for our FPS display.
{{libheader|DOME}}
g.FillRectangle(Brushes.Black, oFPSBG)
<syntaxhighlight lang="wren">import "dome" for Window
' Draw our FPS.
import "graphics" for Canvas, Color
g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)
import "random" for Random
 
class Game {
' Update the form's background and draw.
static init() {
BackgroundImage = b
Window.title = "Image Noise"
Invalidate(ClientRectangle)
__w = 320
__h = 240
Window.resize(__w, __h)
Canvas.resize(__w, __h)
__r = Random.new()
__t = System.clock
}
 
static update() {}
' Let windows handle some queued events.
Application.DoEvents()
Loop While bRunning
 
static draw(dt) {
End Sub
Canvas.cls() // default background is black
End Class</lang>
for (x in 0...__w) {
Sample:<BR>
for (y in 0...__h) {
[[Image:SHSnowExercise.jpg]]
if (__r.int(2) == 0) {
Canvas.pset(x, y, Color.white)
}
}
}
var t = System.clock
var fps = (1/(t - __t)).round
Canvas.print("FPS: %(fps)", 10, 10, Color.red)
__t = t
}
}</syntaxhighlight>
 
=={{header|XPL0}}==
Line 2,430 ⟶ 3,632:
intrinsic could display this image at 327 FPS if Ran(2) was faster.)
 
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int CpuReg, \address of CPU register array (from GetReg)
FPS, \frames per second, the display's update rate
Line 2,455 ⟶ 3,657:
until KeyHit;
SetVid(3); \restore normal text mode
]</langsyntaxhighlight>
 
=={{header|Z80 Assembly}}==
{{works with|Game Boy Color}}
Omitting the initialization code and the other logic keeping the machine working, this will focus solely on the code responsible for creating the effect. The "random" noise was generated by loading this program's ROM image in YY-CHR (a binary file editor) and copying it to its own file, then loading that file into the Game Boy Color's video memory. The framerate is usually 60 FPS but occasionally dips to 59. At first, every tile on screen is the same, but the "noise" effect is caused by:
 
* A "frame timer" variable that increments every vertical blank is used as a pseudo-RNG.
* A variable called "cosine_index" is incremented and its cosine is taken, then the screen is scrolled by that amount.
* Each iteration of the main game loop alters the interrupt handler (which is executed in RAM, having been copied from ROM before the main game loop begins) so that the sine is taken rather than the cosine.
* During the main game loop, the frame timer is also used to select a random graphics tile from among 16 possibilities, and draws it to a randomly selected tile on screen using a simple "xor-shift" routine.
 
<syntaxhighlight lang="z80">forever:
ld hl,frametimer
ld a,(hl)
rrca
rrca
rrca
xor (hl) ;crude xorshift rng used to select a "random" location to draw to.
 
ld h,0
ld L,a ;this random value becomes the low byte of HL
 
rlc L
rl h ;reduce the RNG's bias towards the top of the screen by shifting one bit into H.
ld a,&98 ;high byte of gb vram
add h ;h will equal either 0 or 1.
ld H,a ;now H will either equal &98 or &99
ld a,(frametimer) ;it's possible that this value is different from before since every vblank it increments.
;the vblank code was omitted because it's mostly irrelevant to the task.
and &0f ;select one of sixteen tiles to draw to the screen at the randomly chosen VRAM location.
call LCDWait ;disable interrupts, and wait until the Game Boy is ready to update the tilemap
ei ;enable interrupts again.
ld (hl),a ;now we can store the frame timer AND &0F into video ram.
ld hl,vblankflag ;set to 1 by the vblank routine.
xor a
wait:
halt ;waits for an interrupt.
cp (hl) compare 0 to vblankflag
jr z,wait ;vblank flag is still 1 so keep waiting.
ld (hl),a ;clear vblank flag.
 
 
ld hl,&FFFF ;master interrupt register
res 1,(hl) ;disable hblank interrupt.
 
ld bc,2
ld a,(frametimer)
bit 4,a ;check bit 4 of frametimer, if zero, we'll do sine instead of cosine. Bit 4 was chosen arbitrarily.
jr nz,doSine
ld hl,cos
jr nowStore
doSine:
ld hl,sin
nowStore: ;store desired routine as the CALL address
ld a,L
LD (&A000+(callpoint-TV_Static_FX+1)),a
;using label arithmetic we can work out the place to modify the code.
;hblank interrupt immediately jumps to cartridge RAM at &A000
ld a,H
LD (&A000+(callpoint-TV_Static_FX+2)),a ;store the high byte.
 
ld hl,&FFFF
set 1,(hl) ;re-enable hblank interrupt
 
jp forever</syntaxhighlight>
 
And the interrupt handler located at memory address <code>&A000</code>:
<syntaxhighlight lang="z80">TV_Static_FX:
;this code runs every time the game boy finishes drawing one row of pixels, unless the interrupt is disabled as described above.
push hl
push af
ld hl,(COSINE_INDEX)
inc (hl)
ld a,(hl)
 
callpoint:
call cos ;<--- SMC, gets changed to "CALL SIN" by main game loop when bit 4 of frametimer equals 0, and back to
;"CALL COS" when bit 4 of frametimer equals 1.
; returns cos(A) into A
 
LD (&FF43),A ;output cos(frametimer) to horizontal scroll register
done_TV_Static_FX:
pop af
pop hl
reti ;return to main program
TV_Static_FX_End:</syntaxhighlight>
 
{{out}}
[https://ibb.co/Ns7jy0x Output image of program]
2,052

edits