Subversion Repositories eduke32

Rev

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