-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathpx9_decomp.lua
114 lines (98 loc) · 2.33 KB
/
px9_decomp.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
-- px9 decompress
-- by zep
-- x0,y0 where to draw to
-- src compressed data address
-- vget read function (x,y)
-- vset write function (x,y,v)
function
px9_decomp(x0,y0,src,vget,vset)
local function vlist_val(l, val)
-- find position
for i=1,#l do
if l[i]==val then
for j=i,2,-1 do
l[j]=l[j-1]
end
l[1] = val
return i
end
end
end
-- bit cache is between 16 and
-- 31 bits long with the next
-- bit always aligned to the
-- lsb of the fractional part
local cache,cache_bits=0,0
function getval(bits)
if cache_bits<16 then
-- cache next 16 bits
cache+=%src>>>16-cache_bits
cache_bits+=16
src+=2
end
-- clip out the bits we want
-- and shift to integer bits
local val=cache<<32-bits>>>16-bits
-- now shift those bits out
-- of the cache
cache=cache>>>bits
cache_bits-=bits
return val
end
-- get number plus n
function gnp(n)
local bits=0
repeat
bits+=1
local vv=getval(bits)
n+=vv
until vv<(1<<bits)-1
return n
end
-- header
local
w,h_1, -- w,h-1
eb,el,pr,
x,y,
splen,
predict
=
gnp"1",gnp"0",
gnp"1",{},{},
0,0,
0
--,nil
for i=1,gnp"1" do
add(el,getval(eb))
end
for y=y0,y0+h_1 do
for x=x0,x0+w-1 do
splen-=1
if(splen<1) then
splen,predict=gnp"1",not predict
end
local a=y>y0 and vget(x,y-1) or 0
-- create vlist if needed
local l=pr[a]
if not l then
l={}
for e in all(el) do
add(l,e)
end
pr[a]=l
end
-- grab index from stream
-- iff predicted, always 1
local v=l[predict and 1 or gnp"2"]
-- update predictions
vlist_val(l, v)
vlist_val(el, v)
-- set
vset(x,y,v)
-- advance
x+=1
y+=x\w
x%=w
end
end
end