Subversion Repositories eduke32

Rev

Rev 6569 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2611 helixhorne 1
-- INTERNAL
2034 helixhorne 2
-- definitions of BUILD and game types for the Lunatic Interpreter
3
 
3256 helixhorne 4
local require = require
2034 helixhorne 5
local ffi = require("ffi")
2863 helixhorne 6
local ffiC = ffi.C
2034 helixhorne 7
 
3821 helixhorne 8
-- Lua C API functions.
9
local CF = CF
10
 
3247 helixhorne 11
local bit = bit
3891 helixhorne 12
local coroutine = coroutine
3056 helixhorne 13
local string = string
14
local table = table
3253 helixhorne 15
local math = math
3256 helixhorne 16
 
17
local assert = assert
18
local error = error
3642 helixhorne 19
local getfenv = getfenv
3597 helixhorne 20
local getmetatable = getmetatable
3256 helixhorne 21
local ipairs = ipairs
22
local loadstring = loadstring
23
local pairs = pairs
5026 helixhorne 24
local pcall = pcall
3256 helixhorne 25
local rawget = rawget
26
local rawset = rawset
3597 helixhorne 27
local select = select
3256 helixhorne 28
local setmetatable = setmetatable
29
local setfenv = setfenv
30
local tonumber = tonumber
3319 helixhorne 31
local tostring = tostring
3256 helixhorne 32
local type = type
33
 
3914 helixhorne 34
-- Create a new module for passing stuff to other modules.
35
local lprivate = {}
36
require("package").loaded.lprivate = lprivate
37
 
3641 helixhorne 38
require("jit.opt").start("maxmcode=10240")  -- in KiB
39
 
3056 helixhorne 40
-- The "gv" global will provide access to C global *scalars* and safe functions.
3406 helixhorne 41
-- NOTE: This exposes C library functions from e.g. the global C namespace, but
42
-- without their declarations, they will be sitting there like a stone.
43
local gv_ = {}
3409 helixhorne 44
-- [key]=<boolean> forbids, [key]=<non-boolean (e.g. table, function)> overrides
3406 helixhorne 45
local gv_access = {}
2786 helixhorne 46
 
2842 helixhorne 47
-- This is for declarations of arrays or pointers which should not be
3060 helixhorne 48
-- accessible through the "gv" global. The "defs_common" module will
3056 helixhorne 49
-- use this function.
3060 helixhorne 50
--
3530 helixhorne 51
-- Notes: do not declare multiple scalars on one line (this is bad:
52
-- "int32_t a, b"). Do not name array arguments (or add a space
3227 helixhorne 53
-- between the identifier and the '[' instead).
3512 helixhorne 54
function decl(str, ...)
3227 helixhorne 55
    -- NOTE that the regexp also catches non-array/non-function identifiers
56
    -- like "user_defs ud;"
2786 helixhorne 57
    for varname in string.gmatch(str, "([%a_][%w_]*)[[(;]") do
3406 helixhorne 58
        if (ffiC._DEBUG_LUNATIC ~= 0) then
59
            print("FORBID "..varname)
60
        end
61
        gv_access[varname] = true
2786 helixhorne 62
    end
63
 
3512 helixhorne 64
    ffi.cdef(str, ...)
2786 helixhorne 65
end
66
 
4147 helixhorne 67
lprivate.decl = decl
68
 
4236 helixhorne 69
ffi.cdef[[
70
enum {
71
    LUNATIC_CLIENT_MAPSTER32 = 0,
72
    LUNATIC_CLIENT_EDUKE32 = 1,
73
 
74
    LUNATIC_CLIENT = LUNATIC_CLIENT_EDUKE32
75
}
76
]]
77
 
3320 helixhorne 78
-- Load the definitions common to the game's and editor's Lua interface.
3056 helixhorne 79
local defs_c = require("defs_common")
3256 helixhorne 80
local cansee = defs_c.cansee
3248 helixhorne 81
local strip_const = defs_c.strip_const
3253 helixhorne 82
local setmtonce = defs_c.setmtonce
2317 helixhorne 83
 
3319 helixhorne 84
-- Must be after loading "defs_common" which redefines "print" to use
85
-- OSD_Printf()
3642 helixhorne 86
local print, printf = print, defs_c.printf
3253 helixhorne 87
 
3319 helixhorne 88
 
3056 helixhorne 89
---=== EDuke32 game definitions ===---
2668 helixhorne 90
 
3564 helixhorne 91
local INV_NAMES = {
92
    "STEROIDS",
93
    "SHIELD",
94
    "SCUBA",
95
    "HOLODUKE",
96
    "JETPACK",
97
    "DUMMY1",
98
    "ACCESS",
99
    "HEATS",
100
    "DUMMY2",
101
    "FIRSTAID",
102
    "BOOTS",
103
}
104
 
105
local WEAPON_NAMES = {
106
    "KNEE",
107
    "PISTOL",
108
    "SHOTGUN",
109
    "CHAINGUN",
110
    "RPG",
111
    "HANDBOMB",
112
    "SHRINKER",
113
    "DEVISTATOR",
114
    "TRIPBOMB",
115
    "FREEZE",
116
    "HANDREMOTE",
117
    "GROW",
118
}
119
 
2317 helixhorne 120
---- game structs ----
2786 helixhorne 121
 
4030 helixhorne 122
lprivate.GET = defs_c.conststruct(INV_NAMES)
123
lprivate.WEAPON = defs_c.conststruct(WEAPON_NAMES)
2786 helixhorne 124
 
4030 helixhorne 125
ffi.cdef([[
2786 helixhorne 126
enum {
4030 helixhorne 127
    GET_MAX = 11,
128
    MAX_WEAPONS = 12,
2786 helixhorne 129
    MAXPLAYERS = 16,
3928 helixhorne 130
    GTICSPERSEC = 30,  // The real number of movement updates per second
2786 helixhorne 131
};
3564 helixhorne 132
]])
2786 helixhorne 133
 
3227 helixhorne 134
ffi.cdef[[
2864 helixhorne 135
struct action {
136
    int16_t startframe, numframes;
137
    int16_t viewtype, incval, delay;
5849 hendricks2 138
    uint16_t flags;
2864 helixhorne 139
};
140
 
141
struct move {
142
    int16_t hvel, vvel;
143
};
144
 
3463 helixhorne 145
#pragma pack(push,1)
2864 helixhorne 146
typedef struct { int32_t id; struct move mv; } con_move_t;
147
typedef struct { int32_t id; struct action ac; } con_action_t;
3463 helixhorne 148
#pragma pack(pop)
2864 helixhorne 149
 
2869 helixhorne 150
typedef struct {
151
    int32_t id;
152
    con_action_t act;
153
    con_move_t mov;
154
    int32_t movflags;
155
} con_ai_t;
3227 helixhorne 156
]]
2869 helixhorne 157
 
3928 helixhorne 158
defs_c.bitint_new_struct_type("int16_t", "SBit16")
3643 helixhorne 159
defs_c.bitint_new_struct_type("int32_t", "SBit32")
3928 helixhorne 160
defs_c.bitint_new_struct_type("uint32_t", "UBit32")
3643 helixhorne 161
 
3227 helixhorne 162
-- Struct template for actor_t. It already has 'const' fields (TODO: might need
163
-- to make more 'const'), but still has array members exposed, so is unsuited
164
-- for external exposure.
165
local ACTOR_STRUCT = [[
3968 helixhorne 166
struct {
3864 helixhorne 167
    const int32_t t_data[10];
2869 helixhorne 168
    const struct move mv;
169
    const struct action ac;
3922 helixhorne 170
    const uint16_t actiontics;
2864 helixhorne 171
 
3643 helixhorne 172
]]..defs_c.bitint_member("SBit32", "flags")..[[
3314 helixhorne 173
    vec3_t bpos; //12b
3261 helixhorne 174
    int32_t floorz,ceilingz,lastvx,lastvy; //16b
175
    int32_t lasttransport; //4b
176
 
3253 helixhorne 177
    const int16_t picnum;
178
    int16_t ang, extra;
179
    const int16_t owner;
3928 helixhorne 180
    // NOTE: not to be confused with .movflags:
181
]]..defs_c.bitint_member("SBit16", "_movflag")..[[
182
    int16_t tempang, timetosleep;
2193 helixhorne 183
 
3874 helixhorne 184
    int16_t stayputsect;
3253 helixhorne 185
    const int16_t dispicnum;
3922 helixhorne 186
    // Movement flags, sprite[i].hitag in C-CON.
187
    // XXX: more research where it was used in EDuke32's C code? (also .lotag <-> actiontics)
188
    // XXX: what if CON code knew of the above implementation detail?
189
]]..defs_c.bitint_member("UBit16", "movflags")..[[
190
    int16_t cgg;
3559 helixhorne 191
 
192
    const int16_t lightId, lightcount, lightmaxrange;
3932 helixhorne 193
    // NOTE: on 32-bit, C's lightptr+filler <=> this dummy:
3559 helixhorne 194
    const union { intptr_t ptr; uint64_t dummy; } _light;
3227 helixhorne 195
}
2786 helixhorne 196
]]
2193 helixhorne 197
 
3435 helixhorne 198
local bcarray = require("bcarray")
199
 
3445 helixhorne 200
local bcheck = require("bcheck")
201
local check_sector_idx, check_tile_idx = bcheck.sector_idx, bcheck.tile_idx
3526 helixhorne 202
local check_sprite_idx = bcheck.sprite_idx
3445 helixhorne 203
local check_weapon_idx, check_inventory_idx = bcheck.weapon_idx, bcheck.inventory_idx
204
local check_sound_idx = bcheck.sound_idx
3883 helixhorne 205
local check_number = bcheck.number
3954 helixhorne 206
local check_type = bcheck.type
3445 helixhorne 207
 
3564 helixhorne 208
bcarray.new("int16_t", 64, "loogie", "int16_x_64")  -- TODO: randomize member names
209
bcarray.new("int16_t", ffiC.MAX_WEAPONS, "weapon", "int16_x_MAX_WEAPONS", WEAPON_NAMES)
210
bcarray.new("int16_t", ffiC.GET_MAX, "inventory", "int16_x_GET_MAX", INV_NAMES)
3435 helixhorne 211
 
3530 helixhorne 212
-- NOTE: writing e.g. "ps.jetpack_on" in Lua when "ps.jetpack_on~=0" was meant
213
-- is probably one of the most commonly committed errors, so we make it a bool
214
-- type instead of uint8_t. The only issue is that if CON coders used these
215
-- fields to store more than just one bit, we're in trouble.
216
-- This will need to be documented and frozen for release.
3227 helixhorne 217
local DUKEPLAYER_STRUCT = [[
3458 helixhorne 218
__attribute__((packed)) struct {
2786 helixhorne 219
    vec3_t pos, opos, vel, npos;
4710 helixhorne 220
    vec2_t bobpos, fric;
2786 helixhorne 221
    int32_t truefz, truecz, player_par;
222
    int32_t randomflamex, exitx, exity;
223
    int32_t runspeed, max_player_health, max_shield_amount;
3109 helixhorne 224
    int32_t autostep, autostep_sbw;
2786 helixhorne 225
 
226
    uint32_t interface_toggle_flag;
227
 
3409 helixhorne 228
    int32_t pipebombControl, pipebombLifetime, pipebombLifetimeVar;
229
    int32_t tripbombControl, tripbombLifetime, tripbombLifetimeVar;
230
 
3366 helixhorne 231
    int32_t zrange;
232
    int16_t angrange, autoaimang;
233
 
2786 helixhorne 234
    uint16_t max_actors_killed, actors_killed;
4217 helixhorne 235
]]..defs_c.bitint_member("UBit16", "gotweapon")..[[
236
    uint16_t zoom;
3227 helixhorne 237
 
3435 helixhorne 238
    int16_x_64 loogiex;
239
    int16_x_64 loogiey;
2786 helixhorne 240
    int16_t sbs, sound_pitch;
241
 
3253 helixhorne 242
    int16_t ang, oang, angvel;
3653 helixhorne 243
    const<S> int16_t cursectnum;
3253 helixhorne 244
    int16_t look_ang, last_extra, subweapon;
3435 helixhorne 245
    int16_x_MAX_WEAPONS max_ammo_amount;
246
    int16_x_MAX_WEAPONS ammo_amount;
247
    int16_x_GET_MAX inv_amount;
3653 helixhorne 248
    const<I-> int16_t wackedbyactor;
3652 helixhorne 249
    int16_t pyoff, opyoff;
2786 helixhorne 250
 
251
    int16_t horiz, horizoff, ohoriz, ohorizoff;
5192 helixhorne 252
    const<I-> int16_t newowner;
3253 helixhorne 253
    int16_t jumping_counter, airleft;
3498 helixhorne 254
    int16_t fta;
3653 helixhorne 255
    const<Q> int16_t ftq;
256
    const int16_t access_wallnum, access_spritenum;
2786 helixhorne 257
    int16_t got_access, weapon_ang, visibility;
3249 helixhorne 258
    int16_t somethingonplayer, on_crane;
259
    const int16_t i;
3253 helixhorne 260
    const int16_t one_parallax_sectnum;
2786 helixhorne 261
    int16_t random_club_frame, one_eighty_count;
3653 helixhorne 262
    const<I-> int16_t dummyplayersprite;
3254 helixhorne 263
    int16_t extra_extra8;
264
    int16_t actorsqu, timebeforeexit;
3653 helixhorne 265
    const<X-> int16_t customexitsound;
3254 helixhorne 266
    int16_t last_pissed_time;
3227 helixhorne 267
 
3435 helixhorne 268
    int16_x_MAX_WEAPONS weaprecs;
2786 helixhorne 269
    int16_t weapon_sway, crack_time, bobcounter;
270
 
271
    int16_t orotscrnang, rotscrnang, dead_flag;   // JBF 20031220: added orotscrnang
272
    int16_t holoduke_on, pycount;
2854 helixhorne 273
    int16_t transporter_hold;
2786 helixhorne 274
 
275
    uint8_t max_secret_rooms, secret_rooms;
276
    uint8_t frag, fraggedself, quick_kick, last_quick_kick;
3530 helixhorne 277
    uint8_t return_to_center;
278
    bool reloading;
3444 helixhorne 279
    const uint8_t weapreccnt;
2786 helixhorne 280
    uint8_t aim_mode, auto_aim, weaponswitch, movement_lock, team;
3652 helixhorne 281
    uint8_t tipincs, hbomb_hold_delay;
3653 helixhorne 282
    const<P> uint8_t frag_ps;
3652 helixhorne 283
    uint8_t kickback_pic;
2786 helixhorne 284
 
3530 helixhorne 285
    uint8_t gm;
286
    bool on_warping_sector;
287
    uint8_t footprintcount, hurt_delay;
288
    bool hbomb_on, jumping_toggle, rapid_fire_hold, on_ground;
3516 helixhorne 289
    // NOTE: there's array indexing with inven_icon, but always after a
290
    // bound check:
3530 helixhorne 291
    uint8_t inven_icon, buttonpalette;
292
    bool over_shoulder_on;
293
    uint8_t show_empty_weapon;
2786 helixhorne 294
 
3530 helixhorne 295
    bool jetpack_on, spritebridge;
296
    uint8_t lastrandomspot;  // unused
297
    bool scuba_on;
298
    uint8_t footprintpal;
299
    bool heat_on;
300
    uint8_t invdisptime;
2786 helixhorne 301
 
3530 helixhorne 302
    bool holster_weapon;
303
    uint8_t falling_counter, footprintshade;
3652 helixhorne 304
    uint8_t refresh_inventory;
3817 helixhorne 305
    const<W> uint8_t last_full_weapon;
2786 helixhorne 306
 
4179 helixhorne 307
    const uint8_t toggle_key_flag;
3530 helixhorne 308
    uint8_t knuckle_incs, knee_incs, access_incs;
2786 helixhorne 309
    uint8_t walking_snd_toggle, palookup, hard_landing, fist_incs;
310
 
4179 helixhorne 311
    int8_t numloogs, loogcnt;
312
    const int8_t scream_voice;
3653 helixhorne 313
    const<W-> int8_t last_weapon;
4179 helixhorne 314
    const int8_t cheat_phase;
315
    int8_t weapon_pos;
3653 helixhorne 316
    const<W-> int8_t wantweaponfire;
317
    const<W> int8_t curr_weapon;
2786 helixhorne 318
 
4260 helixhorne 319
    const uint8_t palette;
3444 helixhorne 320
    palette_t _pals;
3893 helixhorne 321
    int8_t _palsfadespeed, _palsfadenext, _palsfadeprio, _padding2;
3227 helixhorne 322
 
3407 helixhorne 323
    // NOTE: In C, the struct type has no name. We only have it here to define
324
    // a metatype later.
325
    const weaponaccess_t weapon;
326
    const int8_t _padding;
3227 helixhorne 327
}
2786 helixhorne 328
]]
2854 helixhorne 329
 
3469 helixhorne 330
local PROJECTILE_STRUCT = [[
331
struct {
332
    int32_t workslike, cstat;
333
    int32_t hitradius, range, flashcolor;
334
    const int16_t spawns;
3865 helixhorne 335
    const int16_t sound, isound;
336
    int16_t vel;
3469 helixhorne 337
    const int16_t decal, trail;
338
    int16_t tnum, drop;
3865 helixhorne 339
    int16_t offset, bounces;
340
    const int16_t bsound;
3469 helixhorne 341
    int16_t toffset;
342
    int16_t extra, extra_rand;
343
    int8_t sxrepeat, syrepeat, txrepeat, tyrepeat;
344
    int8_t shade, xrepeat, yrepeat, pal;
345
    int8_t movecnt;
346
    uint8_t clipdist;
3866 helixhorne 347
    int8_t filler[2];
348
    int32_t userdata;
3469 helixhorne 349
}
350
]]
351
 
3574 helixhorne 352
-- KEEPINSYNC weapondata_mt below.
353
local WEAPONDATA_STRUCT = "struct {"..table.concat(con_lang.wdata_members, ';').."; }"
354
 
3227 helixhorne 355
local randgen = require("randgen")
2786 helixhorne 356
 
3227 helixhorne 357
local ma_rand = randgen.new(true)  -- initialize to "random" (time-based) seed
358
local ma_count = nil
359
 
360
local function ma_replace_array(typestr, neltstr)
361
    local nelts = tonumber(neltstr)
362
    if (nelts==nil) then
363
        nelts = ffiC[neltstr]
364
        assert(type(nelts)=="number")
365
    end
366
 
367
    local strtab = { "const ", typestr.." " }
368
    for i=1,nelts do
369
        local ch1 = 97 + (ma_rand:getu32() % 25)  -- 'a'..'z'
3435 helixhorne 370
        strtab[i+2] = string.format("_%c%x%s", ch1, ma_count, (i<nelts) and "," or ";")
3227 helixhorne 371
        ma_count = ma_count+1
372
    end
373
 
374
    return table.concat(strtab)
375
end
376
 
3653 helixhorne 377
---=== Protection of scalars in (currently only) DukePlayer_t struct. ===---
378
-- This is more convenient than writing dozens of set-member methods.
379
local prot_scalar_chkfunc = {
380
    S = check_sector_idx,
381
    I = check_sprite_idx,
382
 
383
    P = bcheck.player_idx,
384
    W = check_weapon_idx,
385
    X = check_sound_idx,
386
    Q = bcheck.quote_idx,
387
}
388
 
389
local DukePlayer_prot_allowneg = {}  -- [<member name>] = true if setting <0 allowed
390
local DukePlayer_prot_chkfunc = {}  -- [<member name>] = <checking function>
391
 
392
local function ma_replace_scalar(what, typestr, membname)
393
    DukePlayer_prot_chkfunc[membname] = assert(prot_scalar_chkfunc[what:sub(1,1)])
394
    DukePlayer_prot_allowneg[membname] = (what:sub(2)=="-")
395
    return ma_replace_array(typestr, 1)
396
end
397
 
3227 helixhorne 398
-- Converts a template struct definition to an external one, in which arrays
399
-- have been substituted by randomly named scalar fields.
3653 helixhorne 400
-- <also_scalars>: also handle protected scalars like "const<W-> ..." etc.
401
local function mangle_arrays(structstr, also_scalars)
3227 helixhorne 402
    ma_count = 0
403
    -- NOTE: regexp only works for non-nested arrays and for one array per line.
3653 helixhorne 404
    structstr = structstr:gsub("const%s+([%w_]+)[^\n]+%[([%w_]+)%];", ma_replace_array)
405
 
406
    if (also_scalars) then
407
        -- One protected scalar per line, too.
408
        structstr = structstr:gsub("const<(.-)>%s+([%w_]-)%s+([%w_]-);", ma_replace_scalar)
409
    end
410
 
411
    return structstr
3227 helixhorne 412
end
413
 
3653 helixhorne 414
--print(mangle_arrays(DUKEPLAYER_STRUCT, true))
3227 helixhorne 415
 
3392 helixhorne 416
--- default defines etc.
417
local con_lang = require("con_lang")
4590 helixhorne 418
local xmath = require("xmath")
3392 helixhorne 419
 
3227 helixhorne 420
ffi.cdef([[
3407 helixhorne 421
typedef struct { int32_t _p; } weaponaccess_t;
422
 
2786 helixhorne 423
typedef struct {
3928 helixhorne 424
]]..defs_c.bitint_member("UBit32", "bits")..[[
4710 helixhorne 425
    int16_t fvel, svel, avel;
426
    int8_t horz, extbits;
2786 helixhorne 427
} input_t;
428
 
3458 helixhorne 429
typedef
430
]].. mangle_arrays(ACTOR_STRUCT) ..[[
431
actor_t;
432
 
433
typedef
3653 helixhorne 434
]].. mangle_arrays(DUKEPLAYER_STRUCT, true) ..[[
3458 helixhorne 435
DukePlayer_t;
436
 
3463 helixhorne 437
typedef __attribute__((packed)) struct {
2786 helixhorne 438
    DukePlayer_t *ps;
439
    input_t *sync;
440
 
441
    int32_t netsynctime;
442
    int16_t ping, filler;
443
    int32_t pcolor, pteam;
444
    uint8_t frags[MAXPLAYERS], wchoice[MAX_WEAPONS];
445
 
3109 helixhorne 446
    char vote, gotvote, pingcnt, playerquitflag, ready;
2786 helixhorne 447
    char user_name[32];
448
    uint32_t revision;
449
} playerdata_t;
3259 helixhorne 450
 
451
typedef struct {
3408 helixhorne 452
    int32_t cur, count;
453
    int32_t gunposx, lookhalfang;
454
    int32_t gunposy, lookhoriz;
455
    int32_t shade;
456
} hudweapon_t;
457
 
3469 helixhorne 458
typedef
3590 helixhorne 459
]].. WEAPONDATA_STRUCT ..[[
460
weapondata_t;
461
 
462
typedef
3469 helixhorne 463
]].. PROJECTILE_STRUCT ..[[
464
projectile_t;
3259 helixhorne 465
 
466
typedef struct {
3939 helixhorne 467
    uint32_t _flags;  // XXX: do we want to have this accessible at game time?
4291 helixhorne 468
    int32_t _cacherange;
5188 helixhorne 469
    projectile_t *_proj;
470
    const projectile_t *_defproj;
3259 helixhorne 471
} tiledata_t;
2291 helixhorne 472
 
3405 helixhorne 473
typedef struct {
474
    vec3_t pos;
475
    int32_t dist, clock;
476
    int16_t ang, horiz;
3887 helixhorne 477
    int16_t sect;  // NOTE: protected in camera_mt's __newindex
3405 helixhorne 478
} camera_t;
479
 
2319 helixhorne 480
enum
481
{
482
    MAXMOUSEBUTTONS = 10,
483
    MAXMOUSEAXES = 2,
4826 hendricks2 484
    MAXJOYBUTTONS = 32,
485
    MAXJOYBUTTONSANDHATS = (32+4),
4829 helixhorne 486
    MAXJOYAXES = 9,
487
 
2319 helixhorne 488
    NUMGAMEFUNCTIONS = 56,
4829 helixhorne 489
 
490
    // game.h
4472 hendricks2 491
    MAXRIDECULE = 10,
492
    MAXRIDECULELENGTH = 40,
493
    MAXSAVEGAMENAME = 22,
494
    MAXPWLOCKOUT = 128,
495
    MAXRTSNAME = 128,
2319 helixhorne 496
};
2298 helixhorne 497
 
498
typedef struct {
499
    int32_t const_visibility,uw_framerate;
500
    int32_t camera_time,folfvel,folavel,folx,foly,fola;
501
    int32_t reccnt,crosshairscale;
502
 
503
    int32_t runkey_mode,statusbarscale,mouseaiming,weaponswitch,drawweapon;   // JBF 20031125
504
    int32_t democams,color,msgdisptime,statusbarmode;
505
    int32_t m_noexits,noexits,autovote,automsg,idplayers;
506
    int32_t team, viewbob, weaponsway, althud, weaponscale, textscale;
507
 
508
    int32_t entered_name,screen_tilting,shadows,fta_on,executions,auto_run;
509
    int32_t coords,tickrate,levelstats,m_coop,coop,screen_size,lockout,crosshair;
510
    int32_t playerai,angleinterpolation,obituaries;
511
 
512
    int32_t respawn_monsters,respawn_items,respawn_inventory,recstat,monsters_off,brightness;
513
    int32_t m_respawn_items,m_respawn_monsters,m_respawn_inventory,m_recstat,m_monsters_off,detail;
514
    int32_t m_ffire,ffire,m_player_skill,m_level_number,m_volume_number,multimode;
515
    int32_t player_skill,level_number,volume_number,m_marker,marker,mouseflip;
516
 
4945 hendricks2 517
    vec2_t m_origin;
4968 hendricks2 518
    int32_t playerbest;
4945 hendricks2 519
 
6224 terminx 520
    int32_t configversion, bgstretch;
2298 helixhorne 521
 
522
    int16_t pause_on,from_bonus;
523
    int16_t camerasprite,last_camsprite;
6224 terminx 524
    int16_t last_level,secretlevel;
2298 helixhorne 525
 
526
    struct {
527
        int32_t UseJoystick;
528
        int32_t UseMouse;
529
        int32_t AutoAim;
530
        int32_t ShowOpponentWeapons;
531
        int32_t MouseDeadZone,MouseBias;
532
        int32_t SmoothInput;
533
 
534
        // JBF 20031211: Store the input settings because
6056 hendricks2 535
        // (currently) mact can't regurgitate them
2319 helixhorne 536
        int32_t MouseFunctions[MAXMOUSEBUTTONS][2];
537
        int32_t MouseAnalogueAxes[MAXMOUSEAXES];
538
        int32_t MouseAnalogueScale[MAXMOUSEAXES];
4826 hendricks2 539
        int32_t JoystickFunctions[MAXJOYBUTTONSANDHATS][2];
2319 helixhorne 540
        int32_t JoystickDigitalFunctions[MAXJOYAXES][2];
541
        int32_t JoystickAnalogueAxes[MAXJOYAXES];
542
        int32_t JoystickAnalogueScale[MAXJOYAXES];
543
        int32_t JoystickAnalogueDead[MAXJOYAXES];
544
        int32_t JoystickAnalogueSaturate[MAXJOYAXES];
545
        uint8_t KeyboardKeys[NUMGAMEFUNCTIONS][2];
2298 helixhorne 546
 
547
        //
548
        // Sound variables
549
        //
4004 helixhorne 550
        int32_t MasterVolume;
2298 helixhorne 551
        int32_t FXVolume;
552
        int32_t MusicVolume;
553
        int32_t SoundToggle;
554
        int32_t MusicToggle;
555
        int32_t VoiceToggle;
556
        int32_t AmbienceToggle;
557
 
558
        int32_t NumVoices;
559
        int32_t NumChannels;
560
        int32_t NumBits;
561
        int32_t MixRate;
562
 
563
        int32_t ReverseStereo;
564
 
565
        //
566
        // Screen variables
567
        //
568
 
569
        int32_t ScreenMode;
570
 
571
        int32_t ScreenWidth;
572
        int32_t ScreenHeight;
573
        int32_t ScreenBPP;
574
 
575
        int32_t ForceSetup;
576
        int32_t NoAutoLoad;
577
 
3516 helixhorne 578
        const int32_t scripthandle;
2298 helixhorne 579
        int32_t setupread;
580
 
581
        int32_t CheckForUpdates;
582
        int32_t LastUpdateCheck;
583
        int32_t useprecache;
584
    } config;
585
 
586
    char overhead_on,last_overhead,showweapons;
587
    char god,warp_on,cashman,eog,showallmap;
2454 helixhorne 588
    char show_help,scrollmode,noclip;
4472 hendricks2 589
    char ridecule[MAXRIDECULE][MAXRIDECULELENGTH];
590
    char pwlockout[MAXPWLOCKOUT],rtsname[MAXRTSNAME];
2298 helixhorne 591
    char display_bonus_screen;
592
    char show_level_text;
5186 helixhorne 593
    char wchoice[MAX_WEAPONS];
2298 helixhorne 594
} user_defs;
3512 helixhorne 595
 
596
typedef struct {
597
    int32_t partime, designertime;
4948 hendricks2 598
    char *name, *filename, *musicfn;
3512 helixhorne 599
    void *savedstate;
600
} map_t;
2786 helixhorne 601
]])
2193 helixhorne 602
 
3931 helixhorne 603
bcarray.new("weapondata_t", ffiC.MAX_WEAPONS, "weapon", "weapondata_x_MAX_WEAPONS", WEAPON_NAMES)
4112 helixhorne 604
bcarray.new("int32_t", con_lang.MAXSESSIONVARS, "sessionvar", "int32_x_MAXSESSIONVARS")
3931 helixhorne 605
 
3409 helixhorne 606
-- EXTERNALLY EXPOSED GAME VARIABLES
607
ffi.cdef[[
608
const int32_t screenpeek;
609
hudweapon_t hudweap;
3556 helixhorne 610
int32_t g_logoFlags;
3409 helixhorne 611
]]
612
 
613
-- INTERNAL VARIABLES/FUNCTIONS
5991 hendricks2 614
decl("map_t g_mapInfo[$*$];", con_lang.MAXVOLUMES+1, con_lang.MAXLEVELS)
5988 hendricks2 615
decl("char g_volumeNames[$][33];", con_lang.MAXVOLUMES)
3512 helixhorne 616
 
2786 helixhorne 617
decl[[
4285 helixhorne 618
const int32_t myconnectindex;
4031 helixhorne 619
int32_t g_RETURN;
3787 helixhorne 620
int32_t g_elCONSize;
621
char *g_elCON;
622
void El_SetCON(const char *conluacode);
4118 helixhorne 623
void El_OnError(const char *str);
3787 helixhorne 624
 
3891 helixhorne 625
char *g_elSavecode;
626
void El_FreeSaveCode(void);
4119 helixhorne 627
const char *(*El_SerializeGamevars)(int32_t *slenptr, int32_t levelnum);
628
int32_t (*El_RestoreGamevars)(const char *savecode);
4370 helixhorne 629
int32_t (*El_GetLabelValue)(const char *label);
3796 helixhorne 630
 
3512 helixhorne 631
const char *s_buildRev;
2786 helixhorne 632
const char *g_sizes_of_what[];
633
int32_t g_sizes_of[];
4236 helixhorne 634
int32_t g_elFirstTime;
3320 helixhorne 635
int32_t g_elCallDepth;
3821 helixhorne 636
int32_t block_deletesprite;
3788 helixhorne 637
const char **g_elModules;
3516 helixhorne 638
char g_modDir[];
4112 helixhorne 639
int32_x_MAXSESSIONVARS g_elSessionVar;
2319 helixhorne 640
actor_t actor[MAXSPRITES];
3406 helixhorne 641
camera_t g_camera;
2298 helixhorne 642
user_defs ud;
4961 helixhorne 643
playerdata_t *const g_player;
3477 helixhorne 644
DukePlayer_t *g_player_ps[MAXPLAYERS];
3931 helixhorne 645
weapondata_x_MAX_WEAPONS g_playerWeapon[MAXPLAYERS];
3848 helixhorne 646
weapondata_t g_weaponOverridden[MAX_WEAPONS];
3943 helixhorne 647
int16_t WeaponPickupSprites[MAX_WEAPONS];
3345 helixhorne 648
tiledata_t g_tile[MAXTILES];
3463 helixhorne 649
projectile_t SpriteProjectile[MAXSPRITES];
2923 helixhorne 650
 
3830 helixhorne 651
int32_t g_noResetVars;
652
void (*A_ResetVars)(int32_t iActor);
653
 
3847 helixhorne 654
// Used from lunacon.lua for dynamic {tile,sound} remapping:
3568 helixhorne 655
struct
656
{
657
    const char *str;
658
    int32_t *dynvalptr;
659
    const int16_t staticval;
3847 helixhorne 660
} g_dynTileList[], g_dynSoundList[];
3568 helixhorne 661
 
5992 hendricks2 662
char *apStrings[];
3357 helixhorne 663
 
5995 hendricks2 664
const int32_t g_mostConcurrentPlayers;
5994 hendricks2 665
int16_t g_deleteQueueSize;
5987 hendricks2 666
int16_t g_blimpSpawnItems[15];
3343 helixhorne 667
int32_t g_scriptVersion;
5993 hendricks2 668
const int32_t g_frameRate;
3431 helixhorne 669
const int32_t g_currentMenu;
3480 helixhorne 670
uint16_t g_earthquakeTime;
3928 helixhorne 671
uint32_t g_moveThingsCount;
3516 helixhorne 672
char CheatKeys[2];
3247 helixhorne 673
 
3520 helixhorne 674
// Must not have functions here that may call events directly or
675
// indirectly. See lunatic_game.c.
3519 helixhorne 676
 
3247 helixhorne 677
int32_t A_IncurDamage(int32_t sn);  // not bound-checked!
3487 helixhorne 678
int32_t G_CheckActivatorMotion(int32_t lotag);
3254 helixhorne 679
int32_t A_Dodge(spritetype *s);
4590 helixhorne 680
int32_t A_MoveSpriteClipdist(int32_t spritenum, const vec3_t *change, uint32_t cliptype, int32_t clipdist);
3357 helixhorne 681
void P_DoQuote(int32_t q, DukePlayer_t *p);
5348 hendricks2 682
void P_SetGamePalette(DukePlayer_t *player, uint32_t palid, int32_t set);
3504 helixhorne 683
void G_AddUserQuote(const char *daquote);
3357 helixhorne 684
void G_ClearCameraView(DukePlayer_t *ps);
5755 hendricks2 685
void VM_DrawTileGeneric(int32_t x, int32_t y, int32_t zoom, int32_t tilenum,
3480 helixhorne 686
                       int32_t shade, int32_t orientation, int32_t p);
3487 helixhorne 687
void G_InitTimer(int32_t ticspersec);
688
void G_GetTimeDate(int32_t *vals);
689
int32_t G_ToggleWallInterpolation(int32_t w, int32_t doset);
3491 helixhorne 690
int32_t G_StartTrack(int32_t level);
3640 helixhorne 691
int32_t VM_CheckSquished2(int32_t i, int32_t snum);
5990 hendricks2 692
void Menu_Change(int32_t cm);
3366 helixhorne 693
 
3504 helixhorne 694
const char *KB_ScanCodeToString(uint8_t scancode);
695
 
3366 helixhorne 696
int32_t A_CheckAnySoundPlaying(int32_t i);
697
int32_t S_CheckSoundPlaying(int32_t i, int32_t num);
3373 helixhorne 698
void S_StopEnvSound(int32_t num, int32_t i);
5989 hendricks2 699
void S_StopAllSounds(void);
3431 helixhorne 700
void S_ChangeSoundPitch(int32_t num, int32_t i, int32_t pitchoffset);
4928 hendricks2 701
int32_t S_GetMusicPosition(void);
702
void S_SetMusicPosition(int32_t position);
3501 helixhorne 703
 
704
int32_t minitext_(int32_t x,int32_t y,const char *t,int32_t s,int32_t p,int32_t sb);
705
void G_DrawTXDigiNumZ(int32_t starttile, int32_t x,int32_t y,int32_t n,int32_t s,int32_t pal,
706
                      int32_t cs,int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t z);
6210 hendricks2 707
void G_PrintGameText(int32_t tile, int32_t x, int32_t y, const char *t,
708
                     int32_t s, int32_t p, int32_t o,
709
                     int32_t x1, int32_t y1, int32_t x2, int32_t y2,
710
                     int32_t z, int32_t a);
3845 helixhorne 711
vec2_t G_ScreenText(const int32_t font,
712
                    int32_t x, int32_t y, const int32_t z, const int32_t blockangle, const int32_t charangle,
4428 helixhorne 713
                    const char *str, const int32_t shade, int32_t pal, int32_t o, int32_t alpha,
3845 helixhorne 714
                    int32_t xspace, int32_t yline, int32_t xbetween, int32_t ybetween, const int32_t f,
715
                    const int32_t x1, const int32_t y1, const int32_t x2, const int32_t y2);
716
vec2_t G_ScreenTextSize(const int32_t font,
717
                        int32_t x, int32_t y, const int32_t z, const int32_t blockangle,
718
                        const char *str, const int32_t o,
719
                        int32_t xspace, int32_t yline, int32_t xbetween, int32_t ybetween,
720
                        const int32_t f,
721
                        int32_t x1, int32_t y1, int32_t x2, int32_t y2);
4972 helixhorne 722
const char* G_PrintYourTime(void);
723
const char* G_PrintParTime(void);
724
const char* G_PrintDesignerTime(void);
725
const char* G_PrintBestTime(void);
3845 helixhorne 726
 
4814 helixhorne 727
void G_UpdateScreenArea(void);
3794 helixhorne 728
void G_SaveMapState(void);
729
void G_RestoreMapState(void);
5231 helixhorne 730
void G_FreeMapState(int32_t mapnum);
2193 helixhorne 731
]]
732
 
2837 helixhorne 733
decl[[
734
int32_t kopen4loadfrommod(const char *filename, char searchfirst);
3343 helixhorne 735
 
3388 helixhorne 736
char **g_scriptModules;
737
int32_t g_scriptModulesNum;
738
 
3343 helixhorne 739
const char *G_ConFile(void);
740
void G_DoGameStartup(const int32_t *params);
3406 helixhorne 741
int32_t C_DefineSound(int32_t sndidx, const char *fn, int32_t args [5]);
3373 helixhorne 742
void C_DefineMusic(int32_t vol, int32_t lev, const char *fn);
3357 helixhorne 743
void C_DefineQuote(int32_t qnum, const char *qstr);
3373 helixhorne 744
void C_DefineVolumeName(int32_t vol, const char *name);
5033 hendricks2 745
void C_DefineVolumeFlags(int32_t vol, int32_t flags);
4977 hendricks2 746
void C_UndefineVolume(int32_t vol);
3375 helixhorne 747
void C_DefineSkillName(int32_t skill, const char *name);
4977 hendricks2 748
void C_UndefineSkill(int32_t skill);
3373 helixhorne 749
void C_DefineLevelName(int32_t vol, int32_t lev, const char *fn,
750
                       int32_t partime, int32_t designertime,
751
                       const char *levelname);
4977 hendricks2 752
void C_UndefineLevel(int32_t vol, int32_t lev);
3463 helixhorne 753
void C_DefineProjectile(int32_t j, int32_t what, int32_t val);
3516 helixhorne 754
void C_DefineGameFuncName(int32_t idx, const char *name);
3826 helixhorne 755
void C_DefineGameType(int32_t idx, int32_t flags, const char *name);
3516 helixhorne 756
int32_t C_SetDefName(const char *name);
4143 helixhorne 757
void C_SetCfgName(const char *cfgname);
3533 helixhorne 758
 
759
int32_t SCRIPT_GetNumber(int32_t scripthandle, const char *sectionname, const char *entryname, int32_t *number);
760
void SCRIPT_PutNumber(int32_t scripthandle, const char *sectionname, const char *entryname, int32_t number,
761
                      int32_t hexadecimal, int32_t defaultvalue);
2837 helixhorne 762
]]
763
 
2857 helixhorne 764
 
2863 helixhorne 765
-- http://lua-users.org/wiki/SandBoxes says "potentially unsafe"
766
-- as it allows to see implementations of functions.
767
--local string_dump = string.dump
768
string.dump = nil
769
 
770
 
2786 helixhorne 771
-- sanity-check struct type sizes
3109 helixhorne 772
local good = true
3865 helixhorne 773
for i=0,10 do
3109 helixhorne 774
    local what = ffi.string(ffiC.g_sizes_of_what[i])
775
    local fsz = ffi.sizeof(what)
776
    local csz = ffiC.g_sizes_of[i]
3407 helixhorne 777
    if (ffiC._DEBUG_LUNATIC ~= 0) then
778
        print(i..": "..what..": C sizeof = "..tostring(csz)..", FFI sizeof = "..tostring(fsz))
779
    end
3109 helixhorne 780
    if (fsz ~= csz) then
781
        good = false;
782
    end
2786 helixhorne 783
end
784
 
3109 helixhorne 785
if (not good) then
786
    error("Some sizes don't match between C and LuaJIT/FFI.")
787
end
2864 helixhorne 788
 
3109 helixhorne 789
 
3477 helixhorne 790
--== "player" global, needed by the "control" module ==--
791
 
4209 helixhorne 792
local player_static_members = defs_c.static_members_tab()
3477 helixhorne 793
 
4047 helixhorne 794
--[[
3843 helixhorne 795
player_static_members._INPUT_BITS = defs_c.conststruct
3477 helixhorne 796
{
797
    JUMP =                      1,
798
    CROUCH =                    2,
799
    FIRE =                      4,
800
    AIM_UP =                    8,
801
    AIM_DOWN =                 16,
802
    RUNNING =                  32,
803
    LOOK_LEFT =                64,
804
    LOOK_RIGHT =              128,
805
    -- weapons...
806
    STEROIDS =               4096,
807
    LOOK_UP =                8192,
808
    LOOK_DOWN =             16384,
809
    NIGHTVISION =           32768,
810
    MEDKIT =                65536,
811
    RESERVED =             131072,
812
    CENTER_VIEW =          262144,
813
    HOLSTER_WEAPON =       524288,
814
    INVENTORY_LEFT =      1048576,
815
    PAUSE =               2097152,
816
    QUICK_KICK =          4194304,
817
    AIM_MODE =            8388608,
818
    HOLODUKE =           16777216,
819
    JETPACK =            33554432,
820
    QUIT =               67108864,
821
    INVENTORY_RIGHT =   134217728,
822
    TURN_AROUND =       268435456,
823
    OPEN =              536870912,
824
    INVENTORY =        1073741824,
825
    ESC =              2147483648,
3253 helixhorne 826
}
827
 
3843 helixhorne 828
player_static_members._INPUT_EXT_BITS = defs_c.conststruct
3477 helixhorne 829
{
3597 helixhorne 830
    MOVE_FORWARD =  1,
831
    MOVE_BACKWARD = 2,
832
    STRAFE_LEFT =   4,
833
    STRAFE_RIGHT =  8,
834
    TURN_LEFT =    16,
835
    TURN_RIGHT =   32,
3477 helixhorne 836
}
4047 helixhorne 837
--]]
3477 helixhorne 838
 
3928 helixhorne 839
local band = bit.band
840
local lsh = bit.lshift
4590 helixhorne 841
local ivec3 = xmath.ivec3
3928 helixhorne 842
 
843
do
844
    -- player.all() iterator
845
    local function iter_allplayers(_nil, pli)
5995 hendricks2 846
        if (pli+1 < ffiC.g_mostConcurrentPlayers) then
3928 helixhorne 847
            return pli+1
848
        end
849
    end
850
 
851
    function player_static_members.all()
852
        return iter_allplayers, nil, -1
853
    end
854
 
855
    -- player.holdskey(pli, keyname)
856
    local KEYS = {  -- SK_CROUCH etc. -- "sync keys"
857
        CROUCH = lsh(1,1),
858
        RUN = lsh(1,5),
859
        OPEN = lsh(1,29),
860
    }
861
 
862
    function player_static_members.holdskey(pli, keyname)
863
        bcheck.player_idx(pli)
864
        if (KEYS[keyname] == nil) then
865
            error("invalid key name: "..tostring(keyname), 2)
866
        end
867
 
868
        return ffiC.g_player[pli].sync.bitsbits:test(KEYS[keyname])
869
    end
870
end
871
 
872
local player_holdskey = player_static_members.holdskey
873
 
3597 helixhorne 874
-- Actor flags
4209 helixhorne 875
local actor_static_members = defs_c.static_members_tab()
3597 helixhorne 876
do
877
    local our_SFLAG = {}
878
    local ext_SFLAG = con_lang.labels[4]  -- external actor flags only
879
    local USER_MASK = 0
880
 
881
    for name, flag in pairs(ext_SFLAG) do
882
        our_SFLAG[name:sub(7)] = flag  -- strip "SFLAG_"
883
        USER_MASK = bit.bor(USER_MASK, flag)
884
    end
885
 
886
    -- Add a couple of convenience defines.
887
    our_SFLAG.enemy = con_lang.SFLAG.SFLAG_BADGUY
888
    our_SFLAG.enemystayput = con_lang.SFLAG.SFLAG_BADGUY + con_lang.SFLAG.SFLAG_BADGUYSTAYPUT
889
    our_SFLAG.rotfixed = con_lang.SFLAG.SFLAG_ROTFIXED
890
 
3629 helixhorne 891
    -- Callback function chaining control flags.
4374 helixhorne 892
    our_SFLAG.replace = 0x08000000
893
    our_SFLAG.replace_soft = 0x08000000  -- compat
894
    our_SFLAG.replace_hard = 0x08000000  -- compat, deprecated
3829 helixhorne 895
    our_SFLAG.chain_beg = 0x20000000
896
    our_SFLAG.chain_end = 0x40000000
3873 helixhorne 897
    our_SFLAG._CHAIN_MASK_ACTOR = 0x78000000
898
    our_SFLAG._CHAIN_MASK_EVENT = 0x68000000
3629 helixhorne 899
 
3597 helixhorne 900
    -- XXX: CON doesn't export BADGUYSTAYPUT or ROTFIXED SFLAGs, but they are considered
901
    -- external for Lunatic.
902
    our_SFLAG.USER_MASK = bit.bor(USER_MASK, our_SFLAG.enemystayput, our_SFLAG.rotfixed)
903
 
904
    actor_static_members.FLAGS = defs_c.conststruct(our_SFLAG)
3860 helixhorne 905
 
906
    -- Sprite status numbers. Kept in 'actor', because it's more of a game-side
907
    -- concept (event though status lists are implemented in the engine), and
908
    -- to prevent confusion with sprite.CSTAT.
909
    local our_STAT = {}
910
 
911
    for name, statnum in pairs(con_lang.STAT) do
912
        -- Strip 'STAT_'.
913
        our_STAT[name:sub(6)] = statnum
914
    end
915
 
916
    actor_static_members.STAT = defs_c.conststruct(our_STAT)
3887 helixhorne 917
 
3917 helixhorne 918
    actor_static_members.MOVFLAGS = defs_c.conststruct
919
    {
920
        -- NOTE: no underscores, like in DEFS.CON.
921
        faceplayer = 1,
922
        geth = 2,
923
        getv = 4,
924
        randomangle = 8,
925
        faceplayerslow = 16,
926
        spin = 32,
927
        faceplayersmart = 64,
928
        fleeenemy = 128,
4378 helixhorne 929
        jumptoplayer_only = 256,
930
        jumptoplayer_bits = 257,  -- NOTE: two bits set!
3917 helixhorne 931
        jumptoplayer = 257,
932
        seekplayer = 512,
933
        furthestdir = 1024,
934
        dodgebullet = 4096,
935
    }
3597 helixhorne 936
end
937
 
3924 helixhorne 938
function actor_static_members.fall(i)
939
    check_sprite_idx(i)
940
    CF.VM_FallSprite(i)
941
end
942
 
4590 helixhorne 943
-- actor.move(i, vec, cliptype [, clipdist])
944
function actor_static_members.move(i, vec, cliptype, clipdist)
945
    check_sprite_idx(i)
946
    local vel = ivec3(vec.x, vec.y, vec.z)
5026 helixhorne 947
    return ffiC.A_MoveSpriteClipdist(i, vel, cliptype, clipdist or -1)
4590 helixhorne 948
end
949
 
3821 helixhorne 950
-- Delete sprite with index <i>.
951
function actor_static_members.delete(i)
952
    check_sprite_idx(i)
953
 
954
    if (ffiC.sprite[i].statnum == ffiC.MAXSTATUS) then
955
        error("Attempt to delete a sprite already not in the game world", 2)
956
    end
957
 
958
    if (ffiC.block_deletesprite ~= 0) then
959
        error("Attempt to delete sprite in EVENT_EGS", 2)
960
    end
961
 
3826 helixhorne 962
    -- TODO_MP
3821 helixhorne 963
    if (ffiC.g_player_ps[0].i == i) then
964
        error("Attempt to delete player 0's APLAYER sprite", 2)
965
    end
966
 
967
    CF.A_DeleteSprite(i)
968
end
969
 
4209 helixhorne 970
local tile_static_members = defs_c.static_members_tab()
3597 helixhorne 971
do
4731 helixhorne 972
    tile_static_members.sizx = defs_c.creategtab_membidx(ffiC.tilesiz, "x", ffiC.MAXTILES, "tilesizx[]")
973
    tile_static_members.sizy = defs_c.creategtab_membidx(ffiC.tilesiz, "y", ffiC.MAXTILES, "tilesizy[]")
3597 helixhorne 974
end
3562 helixhorne 975
 
3529 helixhorne 976
-- XXX: error message will say "g_player_ps"
5995 hendricks2 977
player = setmtonce({}, defs_c.GenStructMetatable("g_player_ps", "g_mostConcurrentPlayers", player_static_members))
3477 helixhorne 978
 
3345 helixhorne 979
-- needed by "control"
3597 helixhorne 980
actor = setmtonce({}, defs_c.GenStructMetatable("actor", "MAXSPRITES", actor_static_members))
3829 helixhorne 981
-- Some bitwise NOTs of various actor flag masks.
982
local BNOT = {
983
    USER_MASK = bit.bnot(actor.FLAGS.USER_MASK),
3873 helixhorne 984
    CHAIN_MASK_ACTOR = bit.bnot(actor.FLAGS._CHAIN_MASK_ACTOR),
985
    CHAIN_MASK_EVENT = bit.bnot(actor.FLAGS._CHAIN_MASK_EVENT),
3829 helixhorne 986
}
3345 helixhorne 987
 
5188 helixhorne 988
local projectile = defs_c.creategtab_membidx_ptr(ffiC.g_tile, "_proj", ffiC.MAXTILES, "projectile")
3562 helixhorne 989
local g_tile = setmtonce({}, defs_c.GenStructMetatable("g_tile", "MAXTILES", tile_static_members))
3463 helixhorne 990
 
2864 helixhorne 991
--== Custom operations for BUILD data structures ==--
3345 helixhorne 992
-- Among other things, declares struct action and struct move, and their
993
-- ID-wrapped types con_action_t and con_move_t
2871 helixhorne 994
local con = require("control")
2864 helixhorne 995
 
4590 helixhorne 996
do
997
    local isenemytile = con.isenemytile
3427 helixhorne 998
 
4590 helixhorne 999
    -- Add game-side metamethods to "spritetype" and register it with "metatype"
1000
    local spr_mt_index_add = {
1001
        isenemy = function(s)
1002
            return isenemytile(s.picnum)
1003
        end,
1004
    }
1005
 
1006
    defs_c.finish_spritetype(spr_mt_index_add)
1007
end
1008
 
3916 helixhorne 1009
-- Check a literal numeric action or move value.
2923 helixhorne 1010
local function check_literal_am(am, typename)
2869 helixhorne 1011
    if (type(am) ~= "number") then
2923 helixhorne 1012
        error("bad argument: expected number or "..typename, 3)
2869 helixhorne 1013
    end
1014
 
3916 helixhorne 1015
    -- Negative values are generated as con.action/con.move IDs.
2869 helixhorne 1016
    if (not (am >= 0 and am <= 32767)) then
1017
        error("bad argument: expected number in [0 .. 32767]", 3)
1018
    end
1019
end
1020
 
3437 helixhorne 1021
-- An unrestricted actor_t pointer, for internal use:
3458 helixhorne 1022
local actor_ptr_ct = ffi.typeof("$ *", ffi.typeof(strip_const(ACTOR_STRUCT)))
1023
local player_ptr_ct = ffi.typeof("$ *", ffi.typeof(strip_const(DUKEPLAYER_STRUCT)))
3469 helixhorne 1024
local projectile_ptr_ct = ffi.typeof("$ *", ffi.typeof(strip_const(PROJECTILE_STRUCT)))
3954 helixhorne 1025
-- An unrestricted weapondata_t pointer, but with the member names stripped of
1026
-- the leading underscore, too:
3590 helixhorne 1027
local weapondata_ptr_ct = ffi.typeof("$ *", ffi.typeof((strip_const(WEAPONDATA_STRUCT):gsub(" _"," "))))
2872 helixhorne 1028
 
3916 helixhorne 1029
local con_action_ct = ffi.typeof("const con_action_t")
1030
local con_move_ct = ffi.typeof("const con_move_t")
1031
local con_ai_ct = ffi.typeof("const con_ai_t")
1032
 
1033
-- All-zero bare action and move.
1034
local nullac, nullmv = ffi.new("const struct action"), ffi.new("const struct move")
1035
-- All-zero action and move with IDs. Mostly for CON support.
1036
local literal_act = { [0]=con_action_ct(0), [1]=con_action_ct(1) }
1037
local literal_mov = { [0]=con_move_ct(0), [1]=con_move_ct(1) }
1038
 
3466 helixhorne 1039
local function get_actor_idx(a)
1040
    local i = ffi.cast(actor_ptr_ct, a)-ffi.cast(actor_ptr_ct, ffiC.actor)
3964 helixhorne 1041
--    assert(not (i >= ffiC.MAXSPRITES+0ULL))
3466 helixhorne 1042
    return i
1043
end
1044
 
4796 helixhorne 1045
local actor_methods = {
1046
    -- action
1047
    set_action = function(a, act)
1048
        a = ffi.cast(actor_ptr_ct, a)
3916 helixhorne 1049
 
4796 helixhorne 1050
        if (ffi.istype(con_action_ct, act)) then
1051
            a.t_data[4] = act.id
1052
            a.ac = act.ac
1053
        else
1054
            check_literal_am(act, "action")
1055
            a.t_data[4] = act
1056
            a.ac = nullac
1057
        end
2869 helixhorne 1058
 
4796 helixhorne 1059
        a.t_data[2] = 0
1060
        a.t_data[3] = 0
1061
    end,
2864 helixhorne 1062
 
4796 helixhorne 1063
    has_action = function(a, act)
1064
        a = ffi.cast(actor_ptr_ct, a)
3916 helixhorne 1065
 
4796 helixhorne 1066
        if (ffi.istype(con_action_ct, act)) then
1067
            return (a.t_data[4]==act.id)
1068
        else
1069
            check_literal_am(act, "action")
1070
            return (a.t_data[4]==act)
1071
        end
1072
    end,
2869 helixhorne 1073
 
4796 helixhorne 1074
    -- count
1075
    set_count = function(a, count)
1076
        ffi.cast(actor_ptr_ct, a).t_data[0] = count
1077
    end,
2869 helixhorne 1078
 
4796 helixhorne 1079
    get_count = function(a)
1080
        return ffi.cast(actor_ptr_ct, a).t_data[0]
1081
    end,
2869 helixhorne 1082
 
4796 helixhorne 1083
    -- action count
1084
    reset_acount = function(a)
1085
        ffi.cast(actor_ptr_ct, a).t_data[2] = 0
1086
    end,
2869 helixhorne 1087
 
4796 helixhorne 1088
    get_acount = function(a)
1089
        return ffi.cast(actor_ptr_ct, a).t_data[2]
1090
    end,
2869 helixhorne 1091
 
4796 helixhorne 1092
    -- Override action delay. The action ID is kept.
1093
    set_action_delay = function(a, delay)
1094
        ffi.cast(actor_ptr_ct, a).ac.delay = delay
1095
    end,
3918 helixhorne 1096
 
4796 helixhorne 1097
    -- move
1098
    set_move = function(a, mov, movflags)
1099
        a = ffi.cast(actor_ptr_ct, a)
3916 helixhorne 1100
 
4796 helixhorne 1101
        if (ffi.istype(con_move_ct, mov)) then
1102
            a.t_data[1] = mov.id
1103
            a.mv = mov.mv
1104
        else
1105
            check_literal_am(mov, "move")
1106
            a.t_data[1] = mov
1107
            a.mv = nullmv
1108
        end
2869 helixhorne 1109
 
4796 helixhorne 1110
        a.t_data[0] = 0
1111
        a.movflags = movflags or 0
1112
        local spr = ffiC.sprite[get_actor_idx(a)]
2869 helixhorne 1113
 
4796 helixhorne 1114
        if (not spr:isenemy() or spr.extra > 0) then
1115
            if (bit.band(a.movflags, 8) ~= 0) then  -- random_angle
1116
                spr.ang = bit.band(ffiC.krand(), 2047)
3887 helixhorne 1117
            end
4796 helixhorne 1118
        end
1119
    end,
2869 helixhorne 1120
 
4796 helixhorne 1121
    has_move = function(a, mov)
1122
        a = ffi.cast(actor_ptr_ct, a)
3916 helixhorne 1123
 
4796 helixhorne 1124
        if (ffi.istype(con_move_ct, mov)) then
1125
            return (a.t_data[1]==mov.id)
1126
        else
1127
            check_literal_am(mov, "move")
1128
            return (a.t_data[1]==mov)
1129
        end
1130
    end,
2869 helixhorne 1131
 
4796 helixhorne 1132
    -- Override velocity, keeping move ID.
1133
    set_hvel = function(a, hvel)
1134
        ffi.cast(actor_ptr_ct, a).mv.hvel = hvel
1135
    end,
3918 helixhorne 1136
 
4796 helixhorne 1137
    set_vvel = function(a, vvel)
1138
        ffi.cast(actor_ptr_ct, a).mv.vvel = vvel
1139
    end,
3918 helixhorne 1140
 
4796 helixhorne 1141
    -- ai
1142
    set_ai = function(a, ai)
1143
        local oa = a
1144
        a = ffi.cast(actor_ptr_ct, a)
2869 helixhorne 1145
 
4796 helixhorne 1146
        -- TODO: literal number AIs?
1147
        if (not ffi.istype(con_ai_ct, ai)) then
1148
            error("bad argument: expected ai", 2)
1149
        end
2869 helixhorne 1150
 
4796 helixhorne 1151
        -- NOTE: compare with gameexec.c, "CON_AI:"
1152
        a.t_data[5] = ai.id
2869 helixhorne 1153
 
4796 helixhorne 1154
        oa:set_action(ai.act)
1155
        oa:set_move(ai.mov, ai.movflags)
2869 helixhorne 1156
 
4796 helixhorne 1157
        -- Already reset with set_move():
1158
--        a.t_data[0] = 0
1159
    end,
2869 helixhorne 1160
 
4796 helixhorne 1161
    has_ai = function(a, ai)
1162
        a = ffi.cast(actor_ptr_ct, a)
2869 helixhorne 1163
 
4796 helixhorne 1164
        if (ffi.istype(con_ai_ct, ai)) then
1165
            return (a.t_data[5]==ai.id)
1166
        else
1167
            check_literal_am(ai, "ai")
1168
            return (a.t_data[5]==ai)
1169
        end
1170
    end,
3259 helixhorne 1171
 
4796 helixhorne 1172
    -- Getters/setters.
1173
    _get_t_data = function(a, idx)
1174
        if (not (idx >= 0 and idx < 10)) then
1175
            error("invalid t_data index "..idx, 2)
1176
        end
1177
        return ffi.cast(actor_ptr_ct, a).t_data[idx]
1178
    end,
3446 helixhorne 1179
 
4796 helixhorne 1180
    _set_t_data = function(a, idx, val)
1181
        if (not (idx >= 0 and idx < 10)) then
1182
            error("invalid t_data index "..idx, 2)
1183
        end
1184
        ffi.cast(actor_ptr_ct, a).t_data[idx] = val
1185
    end,
3454 helixhorne 1186
 
4796 helixhorne 1187
    set_picnum = function(a, picnum)
1188
        if (not (picnum < 0)) then
1189
            check_tile_idx(picnum)
1190
        end
1191
        ffi.cast(actor_ptr_ct, a).picnum = picnum
1192
    end,
3454 helixhorne 1193
 
4796 helixhorne 1194
    set_owner = function(a, owner)
1195
        -- XXX: is it permissible to set to -1?
1196
        check_sprite_idx(owner)
1197
        ffi.cast(actor_ptr_ct, a).owner = owner
1198
    end,
3928 helixhorne 1199
 
4796 helixhorne 1200
    --- Custom methods ---
3928 helixhorne 1201
 
4796 helixhorne 1202
    -- Checkers for whether the movement update made the actor hit
1203
    -- something.
3928 helixhorne 1204
 
4796 helixhorne 1205
    checkhit = function(a)
1206
        -- Check whether we hit *anything*, including ceiling/floor.
1207
        return a._movflagbits:test(49152)
1208
    end,
3928 helixhorne 1209
 
4796 helixhorne 1210
    checkbump = function(a)
1211
        -- Check whether we bumped into a wall or sprite.
1212
        return (a._movflagbits:mask(49152) >= 32768)
1213
    end,
3928 helixhorne 1214
 
4796 helixhorne 1215
    hitwall = function(a)
1216
        if (a._movflagbits:mask(49152) == 32768) then
1217
            return a._movflagbits:mask(32767)
1218
        end
1219
    end,
3928 helixhorne 1220
 
4796 helixhorne 1221
    hitsprite = function(a)
1222
        if (a._movflagbits:mask(49152) == 49152) then
1223
            return a._movflagbits:mask(32767)
1224
        end
1225
    end,
3928 helixhorne 1226
 
4796 helixhorne 1227
    -- NOTE: no 'hitsector' or 'hitceiling' / 'hitfloor' for now because
1228
    -- more research is needed as to what the best way of checking c/f is.
2864 helixhorne 1229
}
3466 helixhorne 1230
 
4796 helixhorne 1231
local actor_mt = {
1232
    __index = function(a, key)
1233
        if (actor_methods[key] ~= nil) then
1234
            return actor_methods[key]
1235
        elseif (key == "proj") then
1236
            return ffiC.SpriteProjectile[get_actor_idx(a)]
1237
        else
1238
            error("invalid indexing key to actor object", 2)
1239
        end
1240
    end,
1241
}
3466 helixhorne 1242
 
2864 helixhorne 1243
ffi.metatype("actor_t", actor_mt)
1244
 
1245
 
3407 helixhorne 1246
--- PER-PLAYER WEAPON SETTINGS
3954 helixhorne 1247
local wd_sound_member = {}
1248
for _, declstr in pairs(con_lang.wdata_members) do
1249
    local member = declstr:match("const int32_t _(.*sound)$")
1250
    if (member) then
1251
        wd_sound_member[member] = true
1252
        if (ffiC._DEBUG_LUNATIC ~= 0) then
1253
            printf("weapondata_t member %s denotes a sound", member)
1254
        end
1255
    end
1256
end
1257
 
3407 helixhorne 1258
local weapondata_mt = {
3595 helixhorne 1259
    __index = function(wd, member)
1260
        -- Handle protected members that are renamed (e.g. shoots/_shoots).
3653 helixhorne 1261
        return ffi.cast(weapondata_ptr_ct, wd)[0][member]
3595 helixhorne 1262
    end,
1263
 
3407 helixhorne 1264
    __newindex = function(wd, member, val)
3848 helixhorne 1265
        -- Set to 'true' if we set a tile or sound member.
1266
        local didit = false
1267
 
3954 helixhorne 1268
        check_type(member, "string")  -- MEMBER_IS_STRING
3883 helixhorne 1269
        check_number(val)
1270
 
3954 helixhorne 1271
        if (wd_sound_member[member]) then  -- XXX: sound2time is a time, not a sound
3574 helixhorne 1272
            if (val < 0) then
3954 helixhorne 1273
                val = 0  -- Set to 0 if negative (e.g. CrackDown).
3574 helixhorne 1274
            else
1275
                check_sound_idx(val)
1276
            end
3848 helixhorne 1277
            didit = true
3463 helixhorne 1278
        elseif (member=="workslike") then
1279
            check_weapon_idx(val)
3574 helixhorne 1280
        elseif (member=="spawn" or member=="shoots") then
1281
            if (val < 0) then
1282
                -- Set to 0 if oob (e.g. CrackDown). This is a bit problematic
1283
                -- for .shoots because it's used unconditionally except in one
1284
                -- case (see player.c).
1285
                val = 0
1286
            else
1287
                check_tile_idx(val)
1288
            end
3848 helixhorne 1289
            didit = true
3463 helixhorne 1290
        end
3392 helixhorne 1291
 
3954 helixhorne 1292
        -- DEBUG:
1293
--        printf("assigning %s to weapon's %s", tostring(val), member)
3848 helixhorne 1294
 
3954 helixhorne 1295
        -- NOTE: we're indexing a *pointer* with the user-supplied 'member',
1296
        -- which could be dangerouns if it could be a number. However, we have
1297
        -- assured that is is not in MEMBER_IS_STRING above.
1298
        ffi.cast(weapondata_ptr_ct, wd)[member] = val
1299
 
3848 helixhorne 1300
        if (didit and ffiC.g_elCallDepth==0) then
1301
            -- Signal that we overrode this member at CON translation time.
1302
 
1303
            -- Get weapon index as pointer difference first. PLAYER_0.
3931 helixhorne 1304
            local wi = ffi.cast(weapondata_ptr_ct, wd)
1305
                     - ffi.cast(weapondata_ptr_ct, ffiC.g_playerWeapon)
3964 helixhorne 1306
            assert(wi >= 0 and wi < ffiC.MAX_WEAPONS)
3848 helixhorne 1307
 
1308
            -- Set g_weaponOverridden[wi][member], but without invoking
1309
            -- weapondata_t's __newindex metamethod (i.e. us)!
1310
            ffi.cast(weapondata_ptr_ct, ffiC.g_weaponOverridden[wi])[member] = 1
1311
        end
3407 helixhorne 1312
    end,
1313
}
1314
ffi.metatype("weapondata_t", weapondata_mt)
3392 helixhorne 1315
 
3407 helixhorne 1316
local weaponaccess_mt = {
3931 helixhorne 1317
    -- Syntax like "player[0].weapon.KNEE.shoots" possible because
1318
    -- g_playerWeapon[] is declared as an array of corresponding bcarray types
1319
    -- for us.
3407 helixhorne 1320
    __index = function(wa, key)
3931 helixhorne 1321
        if (type(key)~="number" and type(key)~="string") then
1322
            error("must access weapon either by number or by name")
3407 helixhorne 1323
        end
3392 helixhorne 1324
 
3931 helixhorne 1325
        return ffiC.g_playerWeapon[wa._p][key]
3407 helixhorne 1326
    end,
1327
}
1328
ffi.metatype("weaponaccess_t", weaponaccess_mt)
3392 helixhorne 1329
 
3893 helixhorne 1330
 
1331
local function clamp(num, min, max)
1332
    return num < min and min
1333
        or num > max and max
1334
        or num
1335
end
1336
 
1337
local function clamp0to1(num)
1338
    check_number(num, 4)
1339
    return clamp(num, 0, 1)
1340
end
1341
 
4796 helixhorne 1342
local player_methods = {
1343
    -- CON-like addammo/addweapon, but without the non-local control flow
1344
    -- (returns true if weapon's ammo was at the max. instead).
1345
    addammo = con._addammo,
1346
    addweapon = con._addweapon,
3254 helixhorne 1347
 
4796 helixhorne 1348
    stomp = con._pstomp,
3253 helixhorne 1349
 
4796 helixhorne 1350
    holdskey = function(p, keyname)
1351
        -- XXX: on invalid <keyname>, error will point to this next line:
1352
        return player_holdskey(p.weapon._p, keyname)
1353
    end,
3433 helixhorne 1354
 
4796 helixhorne 1355
    has_weapon = function(p, weap)
1356
        return p.gotweaponbits:test(lsh(1,weap))
1357
    end,
3928 helixhorne 1358
 
4796 helixhorne 1359
    give_weapon = function(p, weap)
1360
        p.gotweaponbits:set(lsh(1,weap))
1361
    end,
3444 helixhorne 1362
 
4796 helixhorne 1363
    take_weapon = function(p, weap)
1364
        p.gotweaponbits:clear(lsh(1,weap))
1365
    end,
3444 helixhorne 1366
 
4796 helixhorne 1367
    -- Give or take weapon, for implementation of CON's .gotweapon access.
1368
    _gt_weapon = function(p, weap, give_p)
1369
        if (give_p ~= 0) then
1370
            p:give_weapon(weap)
1371
        else
1372
            p:take_weapon(weap)
1373
        end
1374
    end,
3444 helixhorne 1375
 
4796 helixhorne 1376
    whack = function(p, no_return_to_center)
1377
        p.horiz = p.horiz + 64
1378
        if (not no_return_to_center) then
1379
            p.return_to_center = 9
1380
        end
1381
        local n = bit.arshift(128-band(ffiC.krand(),255), 1)
1382
        p.rotscrnang = n
1383
        p.look_ang = n
1384
    end,
3254 helixhorne 1385
 
4796 helixhorne 1386
    -- External, improved 'palfrom'.
1387
    -- <speed>: possibly fractional speed of tint fading, in pals.f decrements per gametic.
1388
    --          XXX: exposes internals.
1389
    -- <prio>: a value from -128 to 127, higher ones trump lower or equal ones
1390
    fadecol = function(p, fadefrac, r, g, b, speed, prio)
1391
        -- Validate inargs: clamp f,r,g,b to [0 .. 1] first and multiply by
1392
        -- 63 for the internal handling.
1393
        fadefrac = clamp0to1(fadefrac)*63
1394
        -- NOTE: a fadefrac of now <1 is allowed, e.g. for clearing the tint.
1395
        r = clamp0to1(r)*63
1396
        g = clamp0to1(g)*63
1397
        b = clamp0to1(b)*63
3893 helixhorne 1398
 
4796 helixhorne 1399
        if (speed ~= nil) then
1400
            check_number(speed)
1401
            -- Clamp to sensible values; the speed is stored in an int8_t
1402
            -- (see below).
1403
            speed = clamp(speed, 1/128, 127)
1404
        else
1405
            speed = 1
1406
        end
3893 helixhorne 1407
 
4796 helixhorne 1408
        if (prio ~= nil) then
1409
            check_number(prio)
3893 helixhorne 1410
 
4796 helixhorne 1411
            if (not (prio >= -128 and prio < 127)) then
1412
                error("invalid argument #6 (priority): must be in [-128 .. 127]", 2)
3893 helixhorne 1413
            end
4796 helixhorne 1414
        else
1415
            prio = 0
1416
        end
3893 helixhorne 1417
 
4796 helixhorne 1418
        -- Check if a currently active tint has higher priority.
1419
        if (p._pals.f > 0 and p._palsfadeprio > prio) then
1420
            return
1421
        end
3893 helixhorne 1422
 
4796 helixhorne 1423
        -- The passed tint can be applied now.
1424
        p:_palfrom(fadefrac, r, g, b)
1425
        p._palsfadeprio = prio
3893 helixhorne 1426
 
4796 helixhorne 1427
        -- Calculate .palsfade{speed,next}
1428
        if (speed >= 1) then
1429
            -- Will round to the nearest integer ("banker's
1430
            -- rounding"). NOTE: This is not correct for all numbers, see
1431
            -- http://blog.frama-c.com/index.php?post/2013/05/02/nearbyintf1
1432
            p._palsfadespeed = speed + 0.5
1433
            p._palsfadenext = 0
1434
        else
1435
            -- NOTE: Values that round to 0 have are equivalent behavior to
1436
            -- passing a <speed> of 1.
1437
            local negspeedrecip = -((1/speed) + 0.5)  -- [-128.5 .. 1/127+0.5]
1438
            p._palsfadespeed = negspeedrecip
1439
            p._palsfadenext = negspeedrecip
1440
        end
1441
    end,
3893 helixhorne 1442
 
4796 helixhorne 1443
    -- INTERNAL and CON-only.
1444
    _palfrom = function(p, f, r,g,b)
1445
        local pals = p._pals
1446
        -- Assume that CON's palfrom starts with prio 0 and speed 0.
1447
        if (pals.f == 0 or p._palsfadeprio <= 0) then
1448
            pals.f = f
1449
            pals.r, pals.g, pals.b = r, g, b
1450
            p._palsfadespeed, p._palsfadenext = 0, 0
1451
        end
1452
    end,
1453
}
3653 helixhorne 1454
 
4796 helixhorne 1455
local player_mt = {
1456
    __index = function(p, key)
1457
        if (player_methods[key] ~= nil) then
1458
            return player_methods[key]
1459
        elseif (key == "_input") then
1460
            return ffiC.g_player[p.weapon._p].sync[0]
1461
        else
1462
            -- Read access to protected player members.
1463
            return ffi.cast(player_ptr_ct, p)[0][key]
1464
        end
1465
    end,
1466
 
3653 helixhorne 1467
    __newindex = function(p, key, val)
1468
        -- Write access to protected player members.
1469
 
1470
        local allowneg = DukePlayer_prot_allowneg[key]
1471
        assert(type(allowneg)=="boolean")
1472
 
5192 helixhorne 1473
        if (allowneg==false or not (val == -1)) then
3653 helixhorne 1474
            DukePlayer_prot_chkfunc[key](val)
1475
        end
1476
        ffi.cast(player_ptr_ct, p)[key] = val
1477
    end,
3247 helixhorne 1478
}
3477 helixhorne 1479
 
3247 helixhorne 1480
ffi.metatype("DukePlayer_t", player_mt)
1481
 
3865 helixhorne 1482
local function GenProjectileSetFunc(Member, checkfunc)
1483
    return function(self, idx)
1484
        if (not (idx == -1)) then
1485
            checkfunc(idx)
3469 helixhorne 1486
        end
3865 helixhorne 1487
        ffi.cast(projectile_ptr_ct, self)[Member] = idx
3469 helixhorne 1488
    end
1489
end
1490
 
1491
local projectile_mt = {
1492
    __index = {
3865 helixhorne 1493
        set_spawns = GenProjectileSetFunc("spawns", check_tile_idx),
1494
        set_decal = GenProjectileSetFunc("decal", check_tile_idx),
1495
        set_trail = GenProjectileSetFunc("trail", check_tile_idx),
1496
 
1497
        set_sound = GenProjectileSetFunc("sound", check_sound_idx),
1498
        set_isound = GenProjectileSetFunc("isound", check_sound_idx),
1499
        set_bsound = GenProjectileSetFunc("bsound", check_sound_idx),
3469 helixhorne 1500
    },
1501
}
1502
ffi.metatype("projectile_t", projectile_mt)
1503
 
3473 helixhorne 1504
local user_defs_mt = {
1505
    __index = {
1506
        set_screen_size = function(ud, screen_size)
4814 helixhorne 1507
            if (ud.screen_size ~= screen_size) then
1508
                ud.screen_size = screen_size
1509
                ffiC.G_UpdateScreenArea()
1510
            end
3473 helixhorne 1511
        end,
1512
 
1513
        set_volume_number = function(ud, volume_number)
3843 helixhorne 1514
            -- NOTE: allow volume_number==MAXVOLUMES.
1515
            if (not (volume_number==con_lang.MAXVOLUMES)) then
1516
                bcheck.volume_idx(volume_number)
1517
            end
3473 helixhorne 1518
            ud.volume_number = volume_number
1519
        end,
3826 helixhorne 1520
 
4567 helixhorne 1521
        set_m_volume_number = function(ud, volume_number)
1522
            -- NOTE: allow volume_number==MAXVOLUMES.
1523
            if (not (volume_number==con_lang.MAXVOLUMES)) then
1524
                bcheck.volume_idx(volume_number)
1525
            end
1526
            ud.m_volume_number = volume_number
1527
        end,
1528
 
3826 helixhorne 1529
        set_level_number = function(ud, level_number)
1530
            bcheck.level_idx(level_number)
1531
            ud.level_number = level_number
1532
        end,
3473 helixhorne 1533
    },
1534
}
1535
ffi.metatype("user_defs", user_defs_mt)
1536
 
3409 helixhorne 1537
--- CUSTOM "gv" VARIABLES
3406 helixhorne 1538
local camera_mt = {
1539
    -- TODO: "set position" method, which also updates the sectnum
1540
    __index = ffiC.g_camera,
1541
    __newindex = function(_, key, val)
1542
        if (key=="sect") then
3445 helixhorne 1543
            check_sector_idx(val)
3406 helixhorne 1544
        end
1545
        ffiC.g_camera[key] = val
1546
    end,
1547
}
1548
 
3435 helixhorne 1549
gv_access.cam = setmtonce({}, camera_mt)
3473 helixhorne 1550
gv_access._ud = ffiC.ud
3406 helixhorne 1551
 
3601 helixhorne 1552
-- Support for some CON global system gamevars. RETURN handled separately.
1553
gv_access._csv = ffi.new "struct { int32_t LOTAG, HITAG, TEXTURE; }"
3466 helixhorne 1554
 
3928 helixhorne 1555
gv_access.REND = defs_c.conststruct
1556
{
1557
    CLASSIC = 0,
1558
    POLYMOST = 3,
1559
    POLYMER = 4,
1560
}
1561
 
4030 helixhorne 1562
gv_access.WEAPON = lprivate.WEAPON
1563
gv_access.GET = lprivate.GET
1564
 
3475 helixhorne 1565
function gv_access._get_yxaspect()
1566
    return ffiC.yxaspect
1567
end
1568
 
3480 helixhorne 1569
function gv_access._get_viewingrange()
1570
    return ffiC.viewingrange
1571
end
1572
 
3431 helixhorne 1573
function gv_access._currentFramerate()
5993 hendricks2 1574
    return ffiC.g_frameRate
3409 helixhorne 1575
end
1576
 
3431 helixhorne 1577
function gv_access._currentMenu()
1578
    return ffiC.g_currentMenu
1579
end
1580
 
3656 helixhorne 1581
function gv_access._changeMenu(cm)
5990 hendricks2 1582
    ffiC.Menu_Change(cm)
3656 helixhorne 1583
end
1584
 
3498 helixhorne 1585
function gv_access._set_guniqhudid(id)
1586
    local MAXUNIQHUDID = 256  -- KEEPINSYNC build.h
3964 helixhorne 1587
    if (not (id >= 0 and id < MAXUNIQHUDID)) then
3498 helixhorne 1588
        error("invalid unique HUD ID "..id)
1589
    end
1590
    ffiC.guniqhudid = id
1591
end
1592
 
3409 helixhorne 1593
function gv_access.currentEpisode()
4260 helixhorne 1594
    return ffiC.ud.volume_number + 1
3409 helixhorne 1595
end
1596
 
1597
function gv_access.currentLevel()
4260 helixhorne 1598
    return ffiC.ud.level_number + 1
3409 helixhorne 1599
end
1600
 
3480 helixhorne 1601
function gv_access.doQuake(gametics, snd)
1602
    ffiC.g_earthquakeTime = gametics
1603
    if (snd ~= nil) then
1604
        con._globalsound(ffiC.screenpeek, snd)
1605
    end
1606
end
1607
 
3366 helixhorne 1608
-- Declare all con_lang.labels constants in the global FFI namespace.
2863 helixhorne 1609
for i=1,#con_lang.labels do
3597 helixhorne 1610
    if (getmetatable(con_lang.labels[i]) ~= "noffiC") then
1611
        local strbuf = {"enum {"}
1612
        for label, val in pairs(con_lang.labels[i]) do
1613
            strbuf[#strbuf+1] = string.format("%s = %d,", label, val)
1614
        end
1615
        strbuf[#strbuf+1] = "};"
2762 helixhorne 1616
 
3597 helixhorne 1617
        ffi.cdef(table.concat(strbuf))
2762 helixhorne 1618
    end
1619
end
1620
 
1621
 
2648 helixhorne 1622
---=== Set up restricted global environment ===---
1623
 
2828 helixhorne 1624
local allowed_modules = {
1625
    coroutine=coroutine, bit=bit, table=table, math=math, string=string,
2855 helixhorne 1626
 
1627
    os = {
3935 helixhorne 1628
        clock = function() return gv_.gethiticks()*0.001 end,
2855 helixhorne 1629
    },
1630
 
3227 helixhorne 1631
    randgen = randgen,
4236 helixhorne 1632
    engine = require("engine"),
2858 helixhorne 1633
    stat = require("stat"),
2862 helixhorne 1634
    bitar = require("bitar"),
4590 helixhorne 1635
    xmath = xmath,
4147 helixhorne 1636
    fs = require("fs"),
2864 helixhorne 1637
 
1638
    con = con,
2828 helixhorne 1639
}
1640
 
3914 helixhorne 1641
do
1642
    local ctype_cansave = {}
1643
 
1644
    -- Register as "serializeable" the type of cdata object <v>.
1645
    local function reg_serializable_cv(v)
1646
        assert(type(v)=="cdata")
1647
        assert(type(v._serialize)=="function")
1648
        -- NOTE: tonumber() on a ctype cdata object gets its LuaJIT-internal
1649
        -- ID, the one that would be shown with tostring(), e.g.
1650
        -- ctype<struct 95>
1651
        ctype_cansave[tonumber(ffi.typeof(v))] = true
1652
    end
1653
 
1654
    function lprivate.cansave_cdata(v)
1655
        return type(v)=="cdata" and ctype_cansave[tonumber(ffi.typeof(v))]
1656
    end
1657
 
4590 helixhorne 1658
    reg_serializable_cv(xmath.vec3())
1659
    reg_serializable_cv(ivec3())
3914 helixhorne 1660
end
1661
 
3597 helixhorne 1662
-- Protect base modules.
3917 helixhorne 1663
local function basemod_newidx()
3870 helixhorne 1664
    error("modifying base module table forbidden", 2)
1665
end
2828 helixhorne 1666
 
3870 helixhorne 1667
for modname, themodule in pairs(allowed_modules) do
1668
    local mt = {
1669
        __index = themodule,
3917 helixhorne 1670
        __newindex = basemod_newidx,
3870 helixhorne 1671
    }
3597 helixhorne 1672
 
3870 helixhorne 1673
    allowed_modules[modname] = setmtonce({}, mt)
2828 helixhorne 1674
end
1675
 
3642 helixhorne 1676
 
3796 helixhorne 1677
---=== Module stuff ===---
1678
 
1679
local package_loaded = {}  -- [<modname>] = false/true/table
3642 helixhorne 1680
local modname_stack = {}  -- [<depth>]=string
1681
local module_gamevars = {}  -- [<modname>] = { <gvname1>, <gvname2>, ... }
3858 helixhorne 1682
local module_gvlocali = {}  -- [<modname>] = { <localidx_beg>, <localidx_end> }
3891 helixhorne 1683
local module_thread = {}  -- [<modname>] = <module_thread>
3642 helixhorne 1684
 
1685
local function getcurmodname(thisfuncname)
1686
    if (#modname_stack == 0) then
1687
        error("'"..thisfuncname.."' must be called at the top level of a require'd file", 3)
1688
        -- ... as opposed to "at runtime".
2837 helixhorne 1689
    end
1690
 
3642 helixhorne 1691
    return modname_stack[#modname_stack]
2837 helixhorne 1692
end
1693
 
3642 helixhorne 1694
 
2837 helixhorne 1695
local function errorf(level, fmt, ...)
1696
    local errmsg = string.format(fmt, ...)
1697
    error(errmsg, level+1)
1698
end
1699
 
3734 helixhorne 1700
local function readintostr_mod(fn)
3736 helixhorne 1701
    -- TODO: g_loadFromGroupOnly?
1702
    local fd = ffiC.kopen4loadfrommod(fn, 0)
1703
    if (fd < 0) then
1704
        return nil
1705
    end
1706
 
5809 helixhorne 1707
    local ret = defs_c.readintostr(fd)
1708
    ffiC.kclose(fd)
1709
    return ret
2854 helixhorne 1710
end
1711
 
3642 helixhorne 1712
 
3858 helixhorne 1713
local debug = require("debug")
1714
 
1715
-- Get the number of active locals in the function that calls the function
1716
-- calling this one.
1717
local function getnumlocals(l)
1718
    -- 200 is the max. number of locals at one level
1719
    for i=1,200 do
1720
        -- level:
4570 helixhorne 1721
        -- 0 is debug.getlocal() itself.
3891 helixhorne 1722
        -- 1 is this function (getnumlocals).
3858 helixhorne 1723
        -- 2 is the function calling getnumlocals()
1724
        -- 3 is the function calling that one.
1725
        if (debug.getlocal(3, i) == nil) then
1726
            return i-1
1727
        end
1728
    end
1729
end
1730
 
3928 helixhorne 1731
local function error_on_nil_read(_, varname)
1732
    error("attempt to read nil variable '"..varname.."'", 2)
1733
end
1734
 
3642 helixhorne 1735
local required_module_mt = {
3928 helixhorne 1736
    __index = error_on_nil_read,
1737
 
3642 helixhorne 1738
    __newindex = function()
1739
        error("modifying module table forbidden", 2)
1740
    end,
3928 helixhorne 1741
 
3642 helixhorne 1742
    __metatable = true,
1743
}
1744
 
3891 helixhorne 1745
-- Will contain a function to restore gamevars when running from savegame
1746
-- restoration. See SAVEFUNC_ARGS for its arguments.
1747
local g_restorefunc = nil
1748
 
1749
-- Local gamevar restoration function run from
1750
-- our_require('end_gamevars') <- [user module].
1751
local function restore_local(li, lval)
1752
    -- level:
1753
    -- 0 is getlocal() itself.
1754
    -- 1 is this function (restore_local).
1755
    -- 2 is the function calling restore_local(), the savecode.
1756
    -- 3 is the function calling the savecode, our_require.
1757
    -- 4 is the function calling our_require, the module function.
1758
    if (ffiC._DEBUG_LUNATIC ~= 0) then
1759
        printf("Restoring index #%d (%s) with value %s",
1760
               li, debug.getlocal(4, li), tostring(lval))
1761
    end
1762
 
1763
    assert(debug.setlocal(4, li, lval))
1764
end
1765
 
2828 helixhorne 1766
-- The "require" function accessible to Lunatic code.
1767
-- Base modules in allowed_modules are wrapped so that they cannot be
2837 helixhorne 1768
-- modified, user modules are searched in the EDuke32 search
3390 helixhorne 1769
-- path.  Also, our require
1770
--  * never messes with the global environment, it only returns the module.
1771
--  * allows passing varargs beyond the name to the module.
1772
local function our_require(modname, ...)
3734 helixhorne 1773
    local ERRLEV = 5
1774
 
3642 helixhorne 1775
    -- Check module name is valid first.
1776
    -- TODO: restrict valid names?
3788 helixhorne 1777
    if (type(modname) ~= "string" or #modname==0) then
1778
        error("module name must be a nonempty string", 2)
3642 helixhorne 1779
    end
2828 helixhorne 1780
 
3966 helixhorne 1781
    -- For _LUNATIC_DBG
1782
    if (modname:match("^_LUNATIC") and ffiC._DEBUG_LUNATIC == 0) then
1783
        return nil
1784
    end
1785
 
3642 helixhorne 1786
    -- Handle the section between module() and require("end_gamevars").
1787
    if (modname == "end_gamevars") then
1788
        local thismodname = getcurmodname("require")
1789
 
1790
        if (module_gamevars[thismodname] ~= nil) then
1791
            error("\"require 'end_gamevars'\" must be called at most once per require'd file", 2)
1792
        end
1793
 
1794
        local gvnames = {}
1795
 
1796
        for name in pairs(getfenv(2)) do
3857 helixhorne 1797
            gvnames[#gvnames+1] = name
3642 helixhorne 1798
            if (ffiC._DEBUG_LUNATIC ~= 0) then
1799
                printf("MODULE %s GAMEVAR %s", thismodname, name)
1800
            end
1801
        end
1802
 
1803
        module_gamevars[thismodname] = gvnames
3858 helixhorne 1804
        local gvmodi = module_gvlocali[thismodname]
1805
        gvmodi[2] = getnumlocals()
3642 helixhorne 1806
 
3858 helixhorne 1807
        if (ffiC._DEBUG_LUNATIC ~= 0) then
3891 helixhorne 1808
            local numlocals = gvmodi[2]-gvmodi[1]+1
1809
            if (numlocals > 0) then
1810
                printf("Module '%s' has %d locals, index %d to %d",
1811
                       thismodname, numlocals, gvmodi[1], gvmodi[2])
1812
            end
3858 helixhorne 1813
        end
1814
 
3891 helixhorne 1815
        -- Potentially restore gamevars.
1816
        if (g_restorefunc) then
1817
            local modtab = package_loaded[thismodname]
1818
            assert(type(modtab)=="table")
1819
            -- SAVEFUNC_ARGS.
1820
            g_restorefunc(thismodname, modtab, restore_local)
1821
        end
1822
 
1823
        -- Return whether we're NOT running from a savegame restore in the
1824
        -- second outarg. (Lunatic-private!)
1825
        return nil, (g_restorefunc==nil)
3642 helixhorne 1826
    end
1827
 
1828
    -- See whether it's a base module name.
2837 helixhorne 1829
    if (allowed_modules[modname] ~= nil) then
1830
        return allowed_modules[modname]
2828 helixhorne 1831
    end
1832
 
3642 helixhorne 1833
    --- Search user modules...
2837 helixhorne 1834
 
3867 helixhorne 1835
    if (modname:find("[/\\]")) then
1836
        error("Module name must not contain directory separators", ERRLEV-1)
1837
    end
1838
    -- Instead, dots are translated to directory separators. For EDuke32's
3894 helixhorne 1839
    -- virtual file system, this is always a forward slash. Keep the original
1840
    -- module name for passing to the module function.
1841
    local omodname = modname
3867 helixhorne 1842
    modname = modname:gsub("%.", "/")
1843
 
3530 helixhorne 1844
    local omod = package_loaded[modname]
1845
    if (omod ~= nil) then
3642 helixhorne 1846
        if (omod==false) then
3530 helixhorne 1847
            error("Loop while loading modules", ERRLEV-1)
1848
        end
1849
 
2837 helixhorne 1850
        -- already loaded
3642 helixhorne 1851
        assert(omod==true or type(omod)=="table")
3530 helixhorne 1852
        return omod
2837 helixhorne 1853
    end
1854
 
3343 helixhorne 1855
    local modfn = modname .. ".lua"
3734 helixhorne 1856
    local str = readintostr_mod(modfn)
3343 helixhorne 1857
    if (str == nil) then
1858
        errorf(ERRLEV-1, "Couldn't open file \"%s\"", modfn)
1859
    end
2837 helixhorne 1860
 
3891 helixhorne 1861
    -- Implant code that yields the module thread just before it would return
1862
    -- otherwise.
1863
    str = str.."\nrequire('coroutine').yield()"
1864
 
3804 helixhorne 1865
    local modfunc, errmsg = loadstring(str, modfn)
2837 helixhorne 1866
    if (modfunc == nil) then
2857 helixhorne 1867
        errorf(ERRLEV-1, "Couldn't load \"%s\": %s", modname, errmsg)
2837 helixhorne 1868
    end
1869
 
3642 helixhorne 1870
    package_loaded[modname] = false  -- 'not yet loaded'
2863 helixhorne 1871
    table.insert(modname_stack, modname)
2837 helixhorne 1872
 
3891 helixhorne 1873
    -- Run the module code in a separate Lua thread!
1874
    local modthread = coroutine.create(modfunc)
3894 helixhorne 1875
    local ok, retval = coroutine.resume(modthread, omodname, ...)
2840 helixhorne 1876
 
3891 helixhorne 1877
    if (not ok) then
3916 helixhorne 1878
        errorf(ERRLEV-1, "Failed running \"%s\": %s\n%s", modname,
1879
               retval, debug.traceback(modthread))
3891 helixhorne 1880
    end
1881
 
2863 helixhorne 1882
    table.remove(modname_stack)
2840 helixhorne 1883
 
2863 helixhorne 1884
    local modtab = package_loaded[modname]
1885
 
3891 helixhorne 1886
    if (type(modtab) ~= "table") then
1887
        -- The module didn't call our 'module'. Check if it returned a table.
1888
        -- In that case, the coroutine has finished its main function and has
1889
        -- not reached our implanted 'yield'.
1890
        if (coroutine.status(modthread)=="dead" and type(retval)=="table") then
1891
            modtab = retval
1892
            package_loaded[modname] = modtab
1893
        else
1894
            package_loaded[modname] = true
1895
        end
1896
    end
1897
 
2863 helixhorne 1898
    if (type(modtab) == "table") then
3891 helixhorne 1899
        -- Protect module table in any case (i.e. either if the module used our
1900
        -- 'module' or if it returned a table).
3642 helixhorne 1901
        setmetatable(modtab, required_module_mt)
2837 helixhorne 1902
    end
1903
 
3891 helixhorne 1904
    local gvmodi = module_gvlocali[modname]
1905
 
3965 helixhorne 1906
    if (gvmodi and gvmodi[2] and gvmodi[2]>=gvmodi[1]) then
3891 helixhorne 1907
        if (coroutine.status(modthread)=="suspended") then
1908
            -- Save off the suspended thread so that we may get its locals later on.
1909
            -- It is never resumed, but only ever used for debug.getlocal().
1910
            module_thread[modname] = modthread
1911
 
1912
            if (ffiC._DEBUG_LUNATIC ~= 0) then
1913
                printf("Keeping coroutine for module \"%s\"", modname)
1914
            end
1915
        end
1916
    end
1917
 
2840 helixhorne 1918
    return modtab
2828 helixhorne 1919
end
1920
 
2837 helixhorne 1921
 
2839 helixhorne 1922
local module_mt = {
3928 helixhorne 1923
    __index = error_on_nil_read,
2839 helixhorne 1924
}
1925
 
2863 helixhorne 1926
-- Our 'module' replacement doesn't get the module name from the function args
1927
-- since a malicious user could remove other loaded modules this way.
3642 helixhorne 1928
-- Also, our 'module' takes no varargs ("option functions" in Lua).
2863 helixhorne 1929
-- TODO: make transactional?
1930
local function our_module()
3642 helixhorne 1931
    if (#modname_stack == 0) then
2863 helixhorne 1932
        error("'module' must be called at the top level of a require'd file", 2)
3642 helixhorne 1933
        -- ... as opposed to "at runtime".
2863 helixhorne 1934
    end
2837 helixhorne 1935
 
3642 helixhorne 1936
    local modname = getcurmodname("module")
1937
 
3891 helixhorne 1938
    if (package_loaded[modname]) then
3642 helixhorne 1939
        error("'module' must be called at most once per require'd file", 2)
1940
    end
1941
 
2863 helixhorne 1942
    local M = setmetatable({}, module_mt)
2837 helixhorne 1943
    package_loaded[modname] = M
1944
    -- change the environment of the function which called us:
2863 helixhorne 1945
    setfenv(2, M)
3858 helixhorne 1946
 
1947
    module_gvlocali[modname] = { getnumlocals()+1 }
2837 helixhorne 1948
end
1949
 
2838 helixhorne 1950
-- overridden 'error' that always passes a string to the base 'error'
1951
local function our_error(errmsg, level)
1952
    if (type(errmsg) ~= "string") then
2863 helixhorne 1953
        error("error using 'error': error message must be a string", 2)
2838 helixhorne 1954
    end
1955
 
1956
    if (level) then
1957
        if (type(level) ~= "number") then
2863 helixhorne 1958
            error("error using 'error': error level must be a number", 2)
2838 helixhorne 1959
        end
1960
 
2863 helixhorne 1961
        error(errmsg, level==0 and 0 or level+1)
2838 helixhorne 1962
    end
1963
 
2863 helixhorne 1964
    error(errmsg, 2)
2838 helixhorne 1965
end
1966
 
3390 helixhorne 1967
 
1968
-- _G tweaks -- pull in only 'safe' stuff
1969
local G_ = {}  -- our soon-to-be global environment
1970
 
2074 helixhorne 1971
G_.assert = assert
2863 helixhorne 1972
G_.error = our_error
2074 helixhorne 1973
G_.ipairs = ipairs
2863 helixhorne 1974
G_.pairs = pairs
1975
G_.pcall = pcall
3319 helixhorne 1976
G_.print = print
2863 helixhorne 1977
G_.module = our_module
2074 helixhorne 1978
G_.next = next
2863 helixhorne 1979
G_.require = our_require
2074 helixhorne 1980
G_.select = select
2863 helixhorne 1981
G_.tostring = tostring
1982
G_.tonumber = tonumber
2074 helixhorne 1983
G_.type = type
2863 helixhorne 1984
G_.unpack = unpack
1985
G_.xpcall = xpcall
1986
G_._VERSION = _VERSION
2074 helixhorne 1987
 
2863 helixhorne 1988
-- Available through our 'require':
1989
-- bit, coroutine, math, string, table
1990
 
1991
-- Not available:
1992
-- collectgarbage, debug, dofile, gcinfo (DEPRECATED), getfenv, getmetatable,
1993
-- jit, load, loadfile, loadstring, newproxy (NOT STD?), package, rawequal,
1994
-- rawget, rawset, setfenv, setmetatable
1995
 
2074 helixhorne 1996
G_._G = G_
1997
 
3629 helixhorne 1998
-- Chain together two functions taking 3 input args.
1999
local function chain_func3(func1, func2)
2000
    if (func1==nil or func2==nil) then
2001
        return assert(func1 or func2)
2002
    end
2003
 
2004
    -- Return a function that runs <func1> first and then tail-calls <func2>.
2005
    return function(aci, pli, dist)
2006
        func1(aci, pli, dist)
2007
        return func2(aci, pli, dist)
2008
    end
2009
end
2010
 
3916 helixhorne 2011
-- Determines the last numeric index of a table using *pairs*, so that in
2012
-- arg-lists with "holes" (e.g. {1, 2, nil, function() end}) are handled
2013
-- properly.
3873 helixhorne 2014
local function ourmaxn(tab)
2015
    local maxi = 0
3916 helixhorne 2016
    for i in pairs(tab) do
2017
        if (type(i)=="number") then
2018
            maxi = math.max(i, maxi)
2019
        end
3873 helixhorne 2020
    end
4375 helixhorne 2021
    assert(tab[maxi] ~= nil)
3873 helixhorne 2022
    return maxi
2023
end
2024
 
3829 helixhorne 2025
-- Running for the very first time?
2026
local g_firstRun = (ffiC.g_elCONSize == 0)
2027
 
3629 helixhorne 2028
-- Actor functions, saved for actor chaining
2029
local actor_funcs = {}
3937 helixhorne 2030
-- Event functions, saved for event chaining
2031
local event_funcs = {}
3629 helixhorne 2032
 
3937 helixhorne 2033
-- Per-actor sprite animation callbacks
2034
local animsprite_funcs = {}
2035
 
3315 helixhorne 2036
local gameactor_internal = gameactor_internal  -- included in lunatic.c
3937 helixhorne 2037
local gameevent_internal = gameevent_internal  -- included in lunatic.c
2038
 
2039
local function animate_all_sprites()
2040
    for i=0,ffiC.spritesortcnt-1 do
2041
        local tspr = ffiC.tsprite[i]
2042
 
2043
        if (tspr.owner < ffiC.MAXSPRITES+0ULL) then
2044
            local spr = tspr:getspr()
2045
            local animfunc = animsprite_funcs[spr.picnum]
2046
 
2047
            if (animfunc) then
2048
                animfunc(tspr)
2049
            end
2050
        end
2051
    end
2052
end
2053
 
2054
 
5026 helixhorne 2055
local function check_arg_number(name, argpos, val)
4375 helixhorne 2056
    if (type(val) ~= "number") then
2057
        errorf(3, "invalid '%s' argument (#%d) to gameactor: must be a number", name, argpos)
2058
    end
2059
end
2060
 
3873 helixhorne 2061
-- gameactor{tilenum [, flags [, strength [, action [, move [, movflags]]]]], func}
2062
-- Every arg may be positional OR key=val (with the name indicated above as key),
2063
-- but not both.
2064
local function our_gameactor(args)
3541 helixhorne 2065
    bcheck.top_level("gameactor")
3320 helixhorne 2066
 
3873 helixhorne 2067
    if (type(args)~="table") then
2068
        error("invalid gameactor call: must be passed a table")
2069
    end
2070
 
2071
    local tilenum = args[1]
3315 helixhorne 2072
    if (type(tilenum) ~= "number") then
2073
        error("invalid argument #1 to gameactor: must be a number", 2)
2074
    end
3964 helixhorne 2075
    if (not (tilenum >= 0 and tilenum < ffiC.MAXTILES)) then
3597 helixhorne 2076
        error("invalid argument #1 to gameactor: must be a tile number [0..gv.MAXTILES-1]", 2)
3315 helixhorne 2077
    end
3597 helixhorne 2078
 
3873 helixhorne 2079
    local lastargi = ourmaxn(args)
2080
    local func = args[lastargi]
2081
    if (type(func) ~= "function") then
2082
        func = args.func
2083
        lastargi = 1/0
3315 helixhorne 2084
    end
3873 helixhorne 2085
    if (type(func) ~= "function") then
3928 helixhorne 2086
        error("invalid gameactor call: must provide a function with last numeric arg or .func", 2)
3320 helixhorne 2087
    end
3315 helixhorne 2088
 
3873 helixhorne 2089
    local flags = (lastargi > 2 and args[2]) or args.flags or 0
4375 helixhorne 2090
    check_arg_number("flags", 2, flags)
3597 helixhorne 2091
 
3629 helixhorne 2092
    local AF = actor.FLAGS
3928 helixhorne 2093
    local chainflags = band(flags, AF._CHAIN_MASK_ACTOR)
2094
    flags = band(flags, BNOT.CHAIN_MASK_ACTOR)
3629 helixhorne 2095
 
2096
    if (chainflags == 0) then
4374 helixhorne 2097
        -- Default chaining behavior: don't, replace the old actor instead.
2098
        chainflags = AF.replace
3928 helixhorne 2099
    elseif (band(chainflags, chainflags-1) ~= 0) then
3829 helixhorne 2100
        error("invalid chaining control flags to gameactor", 2)
3629 helixhorne 2101
    end
2102
 
4374 helixhorne 2103
    local replacep = (chainflags==AF.replace)
3629 helixhorne 2104
    if (not replacep and not actor_funcs[tilenum]) then
2105
        error("attempt to chain code to nonexistent actor tile "..tilenum, 2)
2106
    end
2107
 
3928 helixhorne 2108
    local flags_rbits = band(flags, BNOT.USER_MASK)
3597 helixhorne 2109
    if (flags_rbits ~= 0) then
3873 helixhorne 2110
        error("invalid 'flags' argument (#2) to gameactor: must not set reserved bits (0x"
3597 helixhorne 2111
              ..(bit.tohex(flags_rbits))..")", 2)
2112
    end
2113
 
3873 helixhorne 2114
    local strength = ((lastargi > 3 and args[3]) or args.strength) or (replacep and 0 or nil)
3629 helixhorne 2115
    if (replacep or strength~=nil) then
4375 helixhorne 2116
        check_arg_number("strength", 3, strength)
3315 helixhorne 2117
    end
2118
 
3916 helixhorne 2119
    local act = ((lastargi > 4 and args[4]) or args.action) or (replacep and literal_act[0] or nil)
3629 helixhorne 2120
    if (replacep or act ~= nil) then
3916 helixhorne 2121
        if (type(act)=="number" and (act==0 or act==1)) then
2122
            act = literal_act[act]
2123
        elseif (not ffi.istype(con_action_ct, act)) then
2124
            error("invalid 'action' argument (#4) to gameactor: must be an action", 2)
3629 helixhorne 2125
        end
3315 helixhorne 2126
    end
2127
 
3916 helixhorne 2128
    local mov = ((lastargi > 5 and args[5]) or args.move) or (replacep and literal_mov[0] or nil)
3629 helixhorne 2129
    if (replacep or mov ~= nil) then
3916 helixhorne 2130
        if (type(mov)=="number" and (mov==0 or mov==1)) then
2131
            mov = literal_mov[mov]
2132
        elseif (not ffi.istype(con_move_ct, mov)) then
2133
            error("invalid 'move' argument (#5) to gameactor: must be a move", 2)
3629 helixhorne 2134
        end
3315 helixhorne 2135
    end
2136
 
3873 helixhorne 2137
    local movflags = ((lastargi > 6 and args[6]) or args.movflags) or (replacep and 0 or nil)
3629 helixhorne 2138
    if (replacep or movflags ~= nil) then
4375 helixhorne 2139
        check_arg_number("movflags", 6, movflags)
3315 helixhorne 2140
    end
2141
 
3937 helixhorne 2142
    -- Register a potentially passed drawn sprite animation callback function.
2143
    -- TODO: allow registering without main actor execution callback.
2144
    local animfunc = args.animate
2145
    if (animfunc ~= nil) then
2146
        if (type(animfunc) ~= "function") then
2147
            error("invalid 'animate' argument to gameactor: must be a function", 2)
2148
        end
2149
 
2150
        animsprite_funcs[tilenum] = replacep and func
2151
            or (chainflags==AF.chain_beg) and chain_func3(animfunc, animsprite_funcs[tilenum])
2152
            or (chainflags==AF.chain_end) and chain_func3(animsprite_funcs[tilenum], animfunc)
2153
            or assert(false)
2154
 
2155
        -- Register our EVENT_ANIMATEALLSPRITES only now so that it is not
2156
        -- called if there are no 'animate' definitions.
4515 hendricks2 2157
        gameevent_internal(97, animate_all_sprites)  -- EVENT_ANIMATEALLSPRITES
3937 helixhorne 2158
    end
2159
 
4374 helixhorne 2160
    -- All good, bitwise-OR the tile bits and register the actor!
2161
    ffiC.g_tile[tilenum]._flags = bit.bor(ffiC.g_tile[tilenum]._flags, flags)
3597 helixhorne 2162
 
3629 helixhorne 2163
    local newfunc = replacep and func
2164
        or (chainflags==AF.chain_beg) and chain_func3(func, actor_funcs[tilenum])
2165
        or (chainflags==AF.chain_end) and chain_func3(actor_funcs[tilenum], func)
2166
        or assert(false)
2167
 
2168
    gameactor_internal(tilenum, strength, act, mov, movflags, newfunc)
2169
    actor_funcs[tilenum] = newfunc
3315 helixhorne 2170
end
2171
 
3320 helixhorne 2172
 
3873 helixhorne 2173
-- gameevent{<event idx or string> [, flags], <event function>}
2174
local function our_gameevent(args)
3872 helixhorne 2175
    bcheck.top_level("gameevent")
2176
 
3873 helixhorne 2177
    if (type(args)~="table") then
2178
        error("invalid gameevent call: must be passed a table")
2179
    end
2180
 
2181
    local event = args[1]
2182
 
3320 helixhorne 2183
    if (type(event) == "string") then
2184
        if (event:sub(1,6) ~= "EVENT_") then
2185
            event = "EVENT_"..event
2186
        end
3380 helixhorne 2187
        local eventidx = con_lang.EVENT[event]
3320 helixhorne 2188
        if (eventidx == nil) then
2189
            errorf(2, "gameevent: invalid event label %q", event)
2190
        end
2191
        event = eventidx
2192
    end
2193
    if (type(event) ~= "number") then
3629 helixhorne 2194
        error("invalid argument #1 to gameevent: must be a number or event label", 2)
3320 helixhorne 2195
    end
3964 helixhorne 2196
    if (not (event >= 0 and event < con_lang.MAXEVENTS)) then
3320 helixhorne 2197
        error("invalid argument #1 to gameevent: must be an event number (0 .. MAXEVENTS-1)", 2)
2198
    end
2199
 
3629 helixhorne 2200
    local AF = actor.FLAGS
3320 helixhorne 2201
 
3873 helixhorne 2202
    -- Kind of CODEDUP from our_gameactor.
2203
    local lastargi = ourmaxn(args)
2204
    local func = args[lastargi]
2205
    if (type(func) ~= "function") then
2206
        func = args.func
2207
        lastargi = 1/0
2208
    end
2209
    if (type(func) ~= "function") then
2210
        error("invalid gameevent call: must provide a function with last numeric arg or .func", 2)
2211
    end
2212
 
3629 helixhorne 2213
    -- Event chaining: in Lunatic, chaining at the *end* is the default.
3873 helixhorne 2214
    local flags = (lastargi > 2 and args[2]) or args.flags or AF.chain_end
2215
    if (type(flags) ~= "number") then
2216
        error("invalid 'flags' argument (#2) to gameevent: must be a number", 2)
3320 helixhorne 2217
    end
2218
 
3928 helixhorne 2219
    if (band(flags, BNOT.CHAIN_MASK_EVENT) ~= 0) then
3873 helixhorne 2220
        error("invalid 'flags' argument to gameevent: must not set reserved bits", 2)
3629 helixhorne 2221
    end
2222
 
3873 helixhorne 2223
    local newfunc = (flags==AF.replace) and func
3629 helixhorne 2224
        or (flags==AF.chain_beg) and chain_func3(func, event_funcs[event])
2225
        or (flags==AF.chain_end) and chain_func3(event_funcs[event], func)
2226
        or assert(false)
2227
 
3320 helixhorne 2228
    gameevent_internal(event, newfunc)
2229
    event_funcs[event] = newfunc
2230
end
2231
 
2650 helixhorne 2232
--- non-default data and functions
3320 helixhorne 2233
G_.gameevent = our_gameevent
3315 helixhorne 2234
G_.gameactor = our_gameactor
3463 helixhorne 2235
-- These come from above:
2236
G_.player = player
2237
G_.actor = actor
2238
G_.projectile = projectile
3562 helixhorne 2239
G_.g_tile = g_tile
2650 helixhorne 2240
 
4236 helixhorne 2241
G_.LUNATIC_FIRST_TIME = (ffiC.g_elFirstTime ~= 0)
2242
 
4147 helixhorne 2243
-- A table that can be used for temporary data when debugging from the OSD.
2244
G_.d = {}
2650 helixhorne 2245
 
4147 helixhorne 2246
 
3790 helixhorne 2247
---=== Lunatic translator setup ===---
2650 helixhorne 2248
 
3790 helixhorne 2249
read_into_string = readintostr_mod  -- for lunacon
2250
local lunacon = require("lunacon")
2251
 
2252
local concode, lineinfo
2650 helixhorne 2253
 
3787 helixhorne 2254
--- Get Lua code for CON (+ mutator) code.
3788 helixhorne 2255
if (g_firstRun) then
3787 helixhorne 2256
    -- Compiling CON for the first time.
3388 helixhorne 2257
    local confn = { ffi.string(ffiC.G_ConFile()) }
2258
 
2259
    local nummods = ffiC.g_scriptModulesNum
2260
    if (nummods > 0) then
2261
        assert(ffiC.g_scriptModules ~= nil)
2262
 
2263
        for i=1,nummods do
2264
            confn[i+1] = ffi.string(ffiC.g_scriptModules[i-1])
2265
        end
2266
    end
2267
 
3535 helixhorne 2268
    concode, lineinfo = lunacon.compile(confn)
2269
 
3390 helixhorne 2270
    if (concode == nil) then
2271
        error("Failure compiling CON code, exiting.", 0)
2272
    end
3558 helixhorne 2273
    assert(lineinfo)
3535 helixhorne 2274
 
3787 helixhorne 2275
    -- Back up the translated code on the C side.
2276
    assert(type(concode)=="string")
2277
    ffiC.El_SetCON(concode)
2278
else
2279
    -- CON was already compiled.
2280
    concode = ffi.string(ffiC.g_elCON, ffiC.g_elCONSize)
3790 helixhorne 2281
    lineinfo = lunacon.get_lineinfo(concode)
3787 helixhorne 2282
end
2283
 
3790 helixhorne 2284
if (ffiC._DEBUG_LUNATIC ~= 0) then
2285
    -- XXX: lineinfo of 2nd up time has one line less.
2286
    printf("CON line info has %d Lua lines", #lineinfo.llines)
2287
end
2288
 
3787 helixhorne 2289
do
3535 helixhorne 2290
    -- Translate one Lua line number to a CON file name + line number
2291
    local function transline(lnum)
2292
        return string.format("%s:%d", lineinfo:getfline(tonumber(lnum)))
2293
    end
2294
 
2295
    -- Register the function that tweaks an error message, looking out for
2296
    -- errors from CON and translating the line numbers.
2297
    local function tweak_traceback_msg(errmsg)
2298
        return errmsg:gsub('%[string "CON"%]:([0-9]+)', transline)
2299
    end
2300
 
4142 helixhorne 2301
    lprivate.tweak_traceback_msg = tweak_traceback_msg
2302
 
3535 helixhorne 2303
    set_tweak_traceback_internal(tweak_traceback_msg)
3343 helixhorne 2304
end
2305
 
3796 helixhorne 2306
-- XXX: May still be require'd from user code, we don't want that (at least not
2307
-- under this name).
2308
local CON_MODULE_NAME = "_CON\0"
2309
 
2310
-- Set up Lunatic gamevar serialization.
2311
do
6145 hendricks2 2312
    local savegame = require("lunasave")
3796 helixhorne 2313
 
4119 helixhorne 2314
    -- Callback for: const char *(int32_t *slenptr, int32_t levelnum);
2315
    ffiC.El_SerializeGamevars = function(slenptr, levelnum)
3796 helixhorne 2316
        local sb = savegame.savebuffer()
2317
 
3891 helixhorne 2318
        -- Module name, module table, restore_local. See SAVEFUNC_ARGS.
2319
        sb:addraw("local N,M,F=...")
2320
        -- A local to temporarily hold module locals.
2321
        sb:addraw("local L")
3796 helixhorne 2322
 
3891 helixhorne 2323
        -- XXX: System gamevars? Most of them ought to be saved with C data.
3796 helixhorne 2324
        for modname, modvars in pairs(module_gamevars) do
4570 helixhorne 2325
            local isCON = (modname==CON_MODULE_NAME)
2326
 
3908 helixhorne 2327
            sb:startmod(modname)
3891 helixhorne 2328
 
2329
            -- Handle global gamevars first.
3796 helixhorne 2330
            for i=1,#modvars do
2331
                local varname = modvars[i]
4570 helixhorne 2332
                local excludedVars = isCON and varname=="_V" and
4140 helixhorne 2333
                    package_loaded[CON_MODULE_NAME]._V._IS_NORESET_GAMEVAR or nil
2334
 
3796 helixhorne 2335
                -- Serialize gamevar named 'varname' from module named 'modname'.
2336
                -- XXX: May error. This will terminate EDuke32 since this callback
2337
                -- is run unprotected.
4140 helixhorne 2338
                if (sb:add("M."..varname, package_loaded[modname][varname], excludedVars)) then
3796 helixhorne 2339
                    -- We couldn't serialize that gamevar.
2340
                    slenptr[0] = -1
2341
                    -- Signal which gamevar that was.
4570 helixhorne 2342
                    return (isCON and "<CON>" or modname).."."..varname
3796 helixhorne 2343
                end
2344
            end
3891 helixhorne 2345
 
2346
            local modthread = module_thread[modname]
2347
 
2348
            if (modthread) then
2349
                -- Handle local gamevars.
2350
                local gvmodi = module_gvlocali[modname]
2351
 
2352
                for li=gvmodi[1],gvmodi[2] do
2353
                    -- Serialize local with index <li>. Get its value first.
2354
                    local lname, lval = debug.getlocal(modthread, 1, li)
2355
 
2356
                    if (sb:add("L", lval)) then
2357
                        -- We couldn't serialize that gamevar.
2358
                        slenptr[0] = -1
2359
                        return "local "..modname.."."..lname
2360
                    end
2361
 
4118 helixhorne 2362
                    -- Emit code to call restore_local.
3891 helixhorne 2363
                    sb:addrawf("F(%d,L)", li)
2364
                end
2365
            end
2366
 
3908 helixhorne 2367
            sb:endmod()
3796 helixhorne 2368
        end
2369
 
2370
        -- Get the whole code as a string.
2371
        local savecode = sb:getcode()
2372
 
2373
        if (ffiC._DEBUG_LUNATIC ~= 0) then
4570 helixhorne 2374
            -- Dump the code if Lunatic debugging is enabled (-Lopts=diag) and
2375
            -- there is a LUNATIC_SAVECODE_FN variable in the environment.
3796 helixhorne 2376
            local os = require("os")
2377
            local fn = os.getenv("LUNATIC_SAVECODE_FN")
2378
 
2379
            if (fn ~= nil) then
4119 helixhorne 2380
                if (levelnum >= 0) then
2381
                    fn = fn .. levelnum
2382
                end
2383
 
3796 helixhorne 2384
                local io = require("io")
2385
                local f = io.open(fn, "w")
2386
 
2387
                if (f ~= nil) then
2388
                    f:write(savecode)
2389
                    f:close()
2390
                    printf("Wrote Lunatic gamevar restoration code to \"%s\".", fn)
2391
                end
2392
            end
2393
        end
2394
 
2395
        -- Set the size of the code and return the code to C.
2396
        slenptr[0] = #savecode
2397
        return savecode
2398
    end
2399
end
2400
 
2648 helixhorne 2401
-- change the environment of this chunk to the table G_
2827 helixhorne 2402
-- NOTE: all references to global variables from this point on
2403
-- (also in functions created after this point) refer to G_ !
2648 helixhorne 2404
setfenv(1, G_)
2405
 
2863 helixhorne 2406
-- Print keys and values of a table.
2648 helixhorne 2407
local function printkv(label, table)
3060 helixhorne 2408
    print("========== Keys and values of "..label.." ("..tostring(table)..")")
2863 helixhorne 2409
    for k,v in pairs(table) do
3343 helixhorne 2410
        print(k .. ": " .. tostring(v))
2648 helixhorne 2411
    end
3343 helixhorne 2412
    print("----------")
2648 helixhorne 2413
end
2414
 
2710 helixhorne 2415
--printkv('_G AFTER SETFENV', _G)
2648 helixhorne 2416
 
2417
 
2418
---=== Restricted access to C variables from Lunatic ===---
2419
 
2298 helixhorne 2420
-- error(..., 2) is to blame the caller and get its line numbers
2294 helixhorne 2421
 
3928 helixhorne 2422
-- Map of 'gv' variable names to C ones.
2423
local varnameMap = {
2424
    gametic = "g_moveThingsCount",
4031 helixhorne 2425
    RETURN = "g_RETURN",
4112 helixhorne 2426
    _sessionVar = "g_elSessionVar",
3928 helixhorne 2427
}
2428
 
2429
gv_access.gametic = true
4031 helixhorne 2430
gv_access.RETURN = true
4112 helixhorne 2431
gv_access._sessionVar = true
3928 helixhorne 2432
 
2044 helixhorne 2433
local tmpmt = {
3597 helixhorne 2434
    __index = function(_, key)
3406 helixhorne 2435
        if (gv_access[key] == nil) then
3928 helixhorne 2436
            -- Read access allowed.
3406 helixhorne 2437
            return ffiC[key]
3928 helixhorne 2438
        elseif (type(gv_access[key])~="boolean") then
2439
            -- Overridden 'gv' pseudo-member...
3406 helixhorne 2440
            return gv_access[key]
3928 helixhorne 2441
        elseif (varnameMap[key]) then
2442
            -- Variable known under a different name on the C side.
2443
            return ffiC[varnameMap[key]]
3406 helixhorne 2444
        end
2445
        error("access forbidden", 2)
2446
    end,
3556 helixhorne 2447
 
3597 helixhorne 2448
    __newindex = function(_, key, val)
3593 helixhorne 2449
        if (gv_access[key] == nil) then
4030 helixhorne 2450
            -- Variables declared 'const' are handled by LuaJIT.
3556 helixhorne 2451
            ffiC[key] = val
4031 helixhorne 2452
        elseif (varnameMap[key]) then
2453
            ffiC[varnameMap[key]] = val
3556 helixhorne 2454
        else
2455
            error("write access forbidden", 2)
2456
        end
2457
    end,
2044 helixhorne 2458
}
3597 helixhorne 2459
gv = setmtonce(gv_, tmpmt)
2044 helixhorne 2460
 
3060 helixhorne 2461
-- This will create 'sprite', 'wall', etc. HERE, i.e. in the environment of this chunk
2462
defs_c.create_globals(_G)
2863 helixhorne 2463
 
2648 helixhorne 2464
-- REMOVE this for release
3966 helixhorne 2465
if (ffiC._DEBUG_LUNATIC ~= 0) then
2466
    local DBG_ = {}
2467
    DBG_.debug = require("debug")
2468
    DBG_.printkv = printkv
2469
    DBG_.loadstring = loadstring
2470
    DBG_.oom = function()
2471
        local s = "1"
2472
        for i=1,math.huge do
2473
            s = s..s
2474
        end
3380 helixhorne 2475
    end
2611 helixhorne 2476
 
3966 helixhorne 2477
    -- Test reading from all struct members
2478
    DBG_.testmembread = function()
2479
        for _1, sac in pairs { con_lang.StructAccessCode, con_lang.StructAccessCode2 } do
2480
            for what, labels in pairs(sac) do
2481
                if (what~="tspr") then
2482
                    for _3, membaccode in pairs(labels) do
2483
                        if (type(membaccode)=="table") then
2484
                            membaccode = membaccode[1]
2485
                        end
2486
                        if (membaccode) then
2487
                            local codestr = [[
3650 helixhorne 2488
do
2489
    local _bit,_math=require'bit',require'math'
4209 helixhorne 2490
    local _con=require'con'
3650 helixhorne 2491
    local _band,_gv=_bit.band,gv
2492
local tmp=]]..
4375 helixhorne 2493
                            membaccode:gsub("^_gud%(_pli%)", "_con._get_userdef(0)"):gsub("%%s","0").." end"
3966 helixhorne 2494
                            local code = assert(loadstring(codestr))
2495
                            code()
2496
                        end
3475 helixhorne 2497
                    end
2498
                end
2499
            end
2500
        end
2501
    end
3966 helixhorne 2502
 
2503
    allowed_modules._LUNATIC_DBG = DBG_
3475 helixhorne 2504
end
2611 helixhorne 2505
 
2648 helixhorne 2506
---=== Finishing environment setup ===---
2611 helixhorne 2507
 
2710 helixhorne 2508
--printkv('_G AFTER DECLS', _G)
2193 helixhorne 2509
 
4047 helixhorne 2510
local index_error_mt = {
2511
    __index = function(_, key)
2512
        error("attempt to read undeclared variable '"..key.."'", 2)
2513
    end,
2193 helixhorne 2514
 
4047 helixhorne 2515
    __metatable = true,
2516
}
2517
 
2310 helixhorne 2518
-- PiL 14.2 continued
2648 helixhorne 2519
-- We need this at the end because we were previously doing just that!
4047 helixhorne 2520
setmetatable(G_, index_error_mt)
3642 helixhorne 2521
 
3967 helixhorne 2522
local global_mt = {
2523
    __index = G_,
2524
 
2525
    __newindex = function()
2526
        error("attempt to write into the global environment")
2527
    end,
2528
 
2529
    __metatable = true,
2530
}
2531
 
2648 helixhorne 2532
-- Change the environment of the running Lua thread so that everything
2533
-- what we've set up will be available when this chunk is left.
3473 helixhorne 2534
-- In particular, we need the globals defined after setting this chunk's
2648 helixhorne 2535
-- environment earlier.
3967 helixhorne 2536
setfenv(0, setmetatable({}, global_mt))
3343 helixhorne 2537
 
3891 helixhorne 2538
do
2539
    -- If we're running from a savegame restoration, create the restoration
2540
    -- function. Must be here, after the above setfenv(), because it must be
2541
    -- created in this protected ('user') context!
2542
    local cstr = ffiC.g_elSavecode
2543
    if (cstr~=nil) then
2544
        local restorecode = ffi.string(cstr)
2545
        ffiC.El_FreeSaveCode()
2546
 
2547
        g_restorefunc = assert(loadstring(restorecode))
2548
    end
2549
end
2550
 
4119 helixhorne 2551
-- Restore CON gamevars from loadmapstate.
2552
-- TODO: non-user-defined gamevars.
2553
-- TODO: savegames.
2554
-- int32_t El_RestoreGamevars(const char *)
2555
ffiC.El_RestoreGamevars = function(savecode)
2556
    savecode = ffi.string(savecode)
2557
    local restorefunc = assert(loadstring(savecode))
2558
    restorefunc(CON_MODULE_NAME, package_loaded[CON_MODULE_NAME], nil)
2559
    return 0
2560
end
2561
 
3788 helixhorne 2562
-- Run the CON code translated into Lua.
4370 helixhorne 2563
if (assert(concode ~= nil)) then
3343 helixhorne 2564
    local confunc, conerrmsg = loadstring(concode, "CON")
2565
    if (confunc == nil) then
3558 helixhorne 2566
        error("Failure loading translated CON code: "..conerrmsg, 0)
3343 helixhorne 2567
    end
3796 helixhorne 2568
 
3891 helixhorne 2569
    -- Emulate our 'require' for the CON module when running it, for
2570
    -- our_module() which is called from the generated Lua code.
2571
    table.insert(modname_stack, CON_MODULE_NAME)
3917 helixhorne 2572
    local conlabels, conaction, conmove, conai = confunc()
3891 helixhorne 2573
    table.remove(modname_stack)
3870 helixhorne 2574
 
3917 helixhorne 2575
    local function protect_con_table(tab)
4047 helixhorne 2576
        -- NOTE: Some of our code specifically excepts the name tables to be
4570 helixhorne 2577
        -- indexable with nonexistent keys. See e.g. control.lua: _A_SpawnGlass()
4050 helixhorne 2578
        if (ffiC._LUNATIC_STRICT ~= 0) then
2579
            tab = setmetatable(tab, index_error_mt)
2580
        end
3917 helixhorne 2581
        return setmtonce({}, { __index=tab, __newindex=basemod_newidx })
2582
    end
3871 helixhorne 2583
 
3917 helixhorne 2584
    -- Set up CON.* modules, providing access to diffenrent kinds of labels
2585
    -- defined in CON from Lua. See CONCODE_RETURN in lunacon.lua.
2586
    allowed_modules["CON.DEFS"] = protect_con_table(conlabels)
2587
    allowed_modules["CON.ACTION"] = protect_con_table(conaction)
2588
    allowed_modules["CON.MOVE"] = protect_con_table(conmove)
2589
    allowed_modules["CON.AI"] = protect_con_table(conai)
2590
 
3871 helixhorne 2591
    -- Propagate potentially remapped defines to the control module.
2592
    con._setuplabels(conlabels)
4370 helixhorne 2593
 
4376 helixhorne 2594
    local function getLabelValue(str, doupper)
2595
        return conlabels[doupper and string.upper(str) or str]
2596
    end
2597
 
4370 helixhorne 2598
    ffiC.El_GetLabelValue = function(label)
2599
        local str = ffi.string(label)
4376 helixhorne 2600
        local ok, val = pcall(getLabelValue, str, false)
2601
        if (not ok or type(val)~="number") then
2602
            ok, val = pcall(getLabelValue, str, true)
2603
        end
2604
        return (ok and type(val)=="number") and val or bit.tobit(0x80000000)
4370 helixhorne 2605
    end
3343 helixhorne 2606
end
3788 helixhorne 2607
 
2608
-- When starting a map, load Lua modules given on the command line.
2609
if (not g_firstRun) then
2610
    local i=0
2611
    while (ffiC.g_elModules[i] ~= nil) do
3867 helixhorne 2612
        -- Get the module name and strip the trailing extension.
2613
        local modname = ffi.string(ffiC.g_elModules[i]):gsub("%.lua$","")
2614
 
2615
        if (modname:find("%.")) then
2616
            -- Because they will be replaced by dirseps in our_require().
2617
            error("Dots are not permitted in module names", 0)
2618
        end
2619
        -- Allow forward slashes in module names from the cmdline.
2620
        our_require((modname:gsub("%.lua$",""):gsub("/",".")))
2621
 
3788 helixhorne 2622
        i = i+1
2623
    end
4236 helixhorne 2624
 
2625
    ffiC.g_elFirstTime = 0
3788 helixhorne 2626
end
4570 helixhorne 2627
 
2628
if (g_restorefunc) then
2629
    -- Clear it so that it may be garbage-collected.
2630
    g_restorefunc = nil
2631
end