summaryrefslogtreecommitdiff
path: root/Data/BuiltIn/Libraries/lua-addons/addons/BattleStations/battlestations.lua
blob: 5c2922ad1f7a0b8997e4eab54580c9f707e68a97 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
--[[
Copyright © 2018, Sjshovan (Apogee)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of Battle Stations nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Sjshovan (Apogee) BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
]]

_addon.name     = 'Battle Stations'
_addon.description = 'Change or remove the default battle music.'
_addon.author   = 'Sjshovan (Apogee) sjshovan@gmail.com'
_addon.version  = '0.9.1'
_addon.commands = {'battlestations', 'stations', 'bs'}

local _logger = require('logger')
local _config  = require('config')
local _packets = require('packets')

require('functions')
require('constants')
require('helpers')

local defaults = {
    stations = {
        solo = 107.3,
        party = 107.3
    }
}

local settings = _config.load(defaults)

local help = {
    commands = {
        buildHelpSeperator('=', 28),
        buildHelpTitle('Commands'),
        buildHelpSeperator('=', 28),
        buildHelpCommandEntry('list [radios|stations] [category#]', 'Display the available radios and or stations.'),
        buildHelpCommandEntry('set <station> [radio]', 'Set radio(s) to the given station.'),
        buildHelpCommandEntry('get [radio]', 'Display currently set station on the given radio(s).'),
        buildHelpCommandEntry('default [radio]', 'Set radio(s) to the default station (Current Zone Music).'),
        buildHelpCommandEntry('normal [radio]', 'Set radio(s) to the original game music.'),
        buildHelpCommandEntry('reload', 'Reload Battle Stations.'),
        buildHelpCommandEntry('about', 'Display information about Battle Stations.'),
        buildHelpCommandEntry('help', 'Display Battle Stations commands.'),
        buildHelpSeperator('=', 28),
    },

    radios = {
        buildHelpSeperator('=', 25),
        buildHelpTitle('Radios'),
        buildHelpSeperator('=', 25),
        buildHelpRadioEntry(stations.receivers.solo:ucfirst(), 'Plays Solo Battle Music'),
        buildHelpRadioEntry(stations.receivers.party:ucfirst(), 'Plays Party Battle Music'),
        buildHelpSeperator('=', 25),
    },
    
     about = {
        buildHelpSeperator('=', 23),
        buildHelpTitle('About'),
        buildHelpSeperator('=', 23),
        buildHelpTypeEntry('Name', _addon.name),
        buildHelpTypeEntry('Description', _addon.description),
        buildHelpTypeEntry('Author', _addon.author),
        buildHelpTypeEntry('Version', _addon.version),
        buildHelpSeperator('=', 23),
    },
    
    aliases = {
        list = {
            stations = T{
                's', 
                'station',
                'stations',
            },
            radios = T{
                'r',
                'radio', 
                'radios',
                'receiver',
                'receivers'
            },
            categories = T{
                'c',
                'cat',
                'category',
                'categories'
            },
            all = T{
                '*',
                'a',
                'all',
            }
        } 
    }
}

function displayHelp(table_help)
    for index, command in pairs(table_help) do
        displayResponse(command)
    end
end

function displayStations(range)
    displayResponse(buildHelpSeperator('=', 27))
    displayResponse(buildHelpTitle('Stations'))
    displayResponse(buildHelpSeperator('=', 27))
    
    if range ~= nil then 
        if categoryValid(range) then
            displayRangeFrequencies(range)
        end
    else
        for i=100, 107, 1 do
            range = tostring(i)
            displayRangeFrequencies(range)
       end
    end
    displayResponse(buildHelpSeperator('=', 26))    
end

function displayRangeFrequencies(range, name)
    local categories = stations.categories
    
    if categoryValid(range) then
        local name = categories[range]
        displayResponse(buildHelpStationCategoryEntry(range, name))
        displayFrequencies(range)
    end
end

function displayFrequencies(range)
    for i=1, 9, 1 do
        local frequency = range .. '.%s':format(tostring(i))
        if frequencyValid(frequency) then 
            local frequencyObj = getFrequencyObjByValue(frequency)
            local response = buildHelpStationEntry(frequency, frequencyObj.callSign)
            displayResponse(response)
        end
    end
end

function displayCategories()
    displayResponse(buildHelpSeperator('=', 27))
    displayResponse(buildHelpTitle('Categories'))
    displayResponse(buildHelpSeperator('=', 27))
    for i=100, 107, 1 do
        local range = tostring(i)
        if categoryValid(range) then
            local name = stations.categories[range]
            displayResponse(buildHelpStationCategoryEntry(range, name))
        end
    end
    displayResponse(buildHelpSeperator('=', 27))  
end 

function getStations()
    return settings.stations
end

function setStation(radio, frequency)
    if radio == stations.receivers.solo then
        settings.stations.solo = frequency
    elseif radio == stations.receivers.party then
        settings.stations.party = frequency
    else
        settings.stations.solo = frequency
        settings.stations.party = frequency
    end
        
    settings:save()
end

function resolveCurrentStations()
    local current_stations = getStations()
    local radio = 'solo'
    local frequency = tostring(defaults.stations.solo)
    local message_template = '%s station found in settings was not valid and was set to the default %s (%s).'
    
    if not frequencyValid(current_stations.solo) then
        current_stations.solo = frequency
        setStation(radio, frequency)
        
        displayResponse(
            buildWarningMessage(
                message_template:format(
                    radio:ucfirst():color(colors.secondary),
                    frequency:color(colors.primary), 
                    getFrequencyObjByValue(frequency).callSign
                )
            )
        )
    end
    
    if not frequencyValid(current_stations.party) then
        radio = 'party'
        frequency = tostring(defaults.stations.party)
        current_stations.party = party_default
        
        setStation(radio, frequency)
        
        displayResponse(
            buildWarningMessage(
                message_template:format(
                    radio:ucfirst():color(colors.secondary),
                    frequency:color(colors.primary), 
                    getFrequencyObjByValue(frequency).callSign
                )
            )
        )
    end
    
    return current_stations
end

function injectBattleMusic()
    local current_stations = resolveCurrentStations()
    local song = getFrequencyObjByValue(current_stations.solo).song
    local music_type = music.types.battle_solo
    
    if playerInParty() then 
        music_type = music.types.battle_party
        song = getFrequencyObjByValue(current_stations.party).song
    end
    
    song = getConditionalSongTranslation(song)
    
    _packets.inject(_packets.new('incoming', packets.inbound.music_change.id, {
        ['BGM Type'] = music_type,
        ['Song ID'] = song
    }))
end

function getFrequencyObjByValue(frequency)
    return stations.frequencies[tostring(frequency)]
end

function getCurrentTime(formatted)
    local timestamp = tostring(windower.ffxi.get_info().time)
    local hours = (timestamp / 60):floor()
    local minutes = timestamp % 60
    if formatted then 
        return "%s:%s":format(hours, minutes)
    end
    return timestamp
end

function getZoneBGMTable() 
    local data = windower.packets.last_incoming(packets.inbound.zone_update.id)
    local packet = _packets.parse('incoming', data)
    return {
        day = packet['Day Music'],
        night = packet['Night Music'],
        solo = packet['Solo Combat Music'],
        party = packet['Party Combat Music']
    }
end

function getConditionalSongTranslation(song)
    local zone_bgm_table = getZoneBGMTable()
    if song == music.songs.others.zone then    
        if timeIsDaytime() then
            song = zone_bgm_table.day
        else 
            song = zone_bgm_table.night
        end
       
        if playerInReive() then
            song = music.songs.seekers_of_adoulin.breaking_ground
        end
          
    elseif song == music.songs.others.normal then
        if playerInParty() then
            song = zone_bgm_table.party
        else 
            song = zone_bgm_table.solo
        end
    end
    return song 
end

function getPlayerBuffs()
    return T(windower.ffxi.get_player().buffs)
end

function timeIsDaytime()
    local current_time = tonumber(getCurrentTime())
    return current_time >= 6*60 and current_time <= 18*60
end

function playerIsFighting()
    return windower.ffxi.get_player().status == player.statuses.fighting
end

function playerInParty() 
    return windower.ffxi.get_party().alliance_count > 1
end

function playerInReive()
    return getPlayerBuffs():contains(player.buffs.reiveMark)
end

function frequencyValid(frequency)
    return stations.frequencies[tostring(frequency)] ~= nil
end

function radioValid(radio)
    return stations.receivers[radio] ~= nil or radio == '*'
end

function categoryValid(category) 
    return stations.categories[category] ~= nil
end

function listTypeValid(list_type) 
    return help.lists[list_type] ~= nil
end

function handleInjectionNeeds() 
    if needs_inject then
        injectBattleMusic()
        needs_inject = false;
    end
end

windower.register_event('load', function () 
    injectBattleMusic()
end)

windower.register_event('unload', function() 
    local music_type = music.types.battle_solo
    local zone_bgm_table = getZoneBGMTable()
    local song = zone_bgm_table.solo
    
    if playerInParty() then
       music_type = music.types.battle_party
       song = zone_bgm_table.solo
    end
                   
    _packets.inject(_packets.new('incoming', packets.inbound.music_change.id, {
        ['BGM Type'] = music_type,
        ['Song ID'] = song,
    }))
end)

windower.register_event('action', function(act)
    if act.actor_id == windower.ffxi.get_player().id then
        if act.category == 4 and act.recast == 225 and act.targets[1].actions[1].animation == 939 then
            if not playerInParty() then
                functions.loop(injectBattleMusic, 1, 5)          
            end    
        end
    end
end)

windower.register_event('outgoing chunk', function(id, data)
    if id == packets.outbound.action.id then
        local packet = _packets.parse('outgoing', data)
        if packet.Category == packets.outbound.action.categories.engage then
            injectBattleMusic()
        end
    end
end) 

windower.register_event('addon command', function(command, ...)
    if command then
        command = command:lower()
    else 
        displayHelp(help.commands)
        return
    end
  
    local command_args = {...}
    
    local respond = false
    local response_message = ''
    local success = true

    if command == 'list' or command == 'l' then
        local list_type = (command_args[1] or '*'):lower()
        local category = command_args[2]
        
        if help.aliases.list.stations:contains(list_type) then
            if category then
                if categoryValid(category) then
                    displayStations(category)
                
                else
                   respond = true
                   success = false
                   response_message = 'Category not recognized.'
                end
            else 
                displayStations()
            end       
        
        elseif help.aliases.list.radios:contains(list_type) then 
            displayHelp(help.radios)
            
        elseif help.aliases.list.categories:contains(list_type) then
            displayCategories()
        
        elseif help.aliases.list.all:contains(list_type) then
            displayHelp(help.radios)
            displayStations()
        
        else 
            respond = true
            success = false
            response_message = 'List type not recognized.'
        end
        
    elseif command == 'set' or command == 's' then
        respond = true
        
        local frequency = command_args[1]:lower()
     
        local radio = (command_args[2] or '*'):lower()
        
        if not frequencyValid(frequency) then
            success = false
            response_message = 'Frequency not recognized.'
        
        elseif not radioValid(radio) then
            success = false
            response_message = 'Radio not recognized.'           
        else 
            needs_inject = true
            
            local context = 'radio'
            
            setStation(radio, tonumber(frequency))
            
            if radio == '*' then
                context = 'radios'
                radio = 'Solo and Party'
            end
            
            response_message = buildSetResponseMessage(
                radio:ucfirst(), 
                context, 
                frequency, 
                getFrequencyObjByValue(frequency).callSign
            )..'.'
        end

    elseif command == 'get' or command == 'g' then
        respond = true
        
        local current_stations = resolveCurrentStations()
        local radio = (command_args[1] or '*'):lower()
        local frequency = current_stations[radio]
        local frequency2 = current_stations.party
        local individual = false
        
        if not radioValid(radio) then
            success = false
            response_message = 'Radio not recognized.'
        else
            local context = 'radio is'
            
            if radio == '*' then
                frequency = current_stations.solo
                
                if current_stations.party ~= current_stations.solo then
                   individual = true
                else 
                   context = 'radios are'
                   radio = 'Solo and Party'    
                end  
            end
            
            if not individual then
                response_message = buildGetResponseMessage(
                    radio:ucfirst(), 
                    context, 
                    frequency, 
                    getFrequencyObjByValue(frequency).callSign
                )..'.'
   
            else
                local solo_message = buildGetResponseMessage(
                    stations.receivers.solo:ucfirst(), 
                    context, 
                    frequency, 
                    getFrequencyObjByValue(frequency).callSign
                )
                
                local party_message = buildGetResponseMessage(
                   stations.receivers.party:ucfirst(), 
                   context, 
                   frequency2, 
                   getFrequencyObjByValue(frequency2).callSign
                )
                
                response_message = solo_message..' and '..party_message..'.'
            end    
        end

    elseif command == 'default' or command == 'd' then
        respond = true 
        
        local radio = (command_args[1] or '*'):lower()
        
        if not radioValid(radio) then
            success = false
            response_message = 'Radio not recognized.'           
        else 
            needs_inject = true
            
            local frequency = defaults.stations.solo
            local context = 'radio'
            
            setStation(radio, tonumber(frequency))
            
            if radio == '*' then
                context = 'radios'
                radio = 'Solo and Party'
            end
            
            response_message = buildSetResponseMessage(
                radio:ucfirst(), 
                context, 
                frequency, 
                getFrequencyObjByValue(frequency).callSign
            )..'.'
        end
       
    elseif command == 'normal' or command == 'n' then
        respond = true 
        
        local radio = (command_args[1] or '*'):lower()
        
        if not radioValid(radio) then
            success = false
            response_message = 'Radio not recognized.'           
        else
            needs_inject = true
        
            local frequency = '107.2'
            local context = 'radio'
            
            setStation(radio, tonumber(frequency))
            
            if radio == '*' then
                context = 'radios'
                radio = 'Solo and Party'
            end
            
            response_message = buildSetResponseMessage(
                radio:ucfirst(), 
                context, 
                frequency, 
                getFrequencyObjByValue(frequency).callSign
            )..'.'
        end
        
    elseif command == 'reload' or command == 'r' then
        windower.send_command('lua r battlestations')
        
    elseif command == 'about' or command == 'a' then
        displayHelp(help.about)

    elseif command == 'help' or command == 'h' then
        displayHelp(help.commands)
             
    else
        displayHelp(help.commands)
    end

    if respond then
        displayResponse(
            buildCommandResponse(response_message, success)
        )
    end
    
    handleInjectionNeeds()
end)