File size: 9,094 Bytes
7e9dc27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
--[[------------------------------------------------------

  # Parameter save and restore

  This class acts as a proxy around lua tables allowing
  paramter save and recall.

--]]------------------------------------------------------
local lub  = require 'lub'
local yaml = require 'yaml'

-- We keep table keys sorted to improve settings file stability (useful with
-- versioning systems).
yaml.configure {
  sort_table_keys = true,
}

local lib = lub.class('lub.Param')

-- Metatable for proxies.
local ProxyMt = {}

-- Metatable for controllers.
local CtrlMt  = {}

local private = {}

-- ## Dependencies
--
-- * yaml

-- # Class functions

-- Create a new parameter helper saving content to `filepath`. If the file path
-- is not provided, the default is to use the current script name with ".yml"
-- extension. For example "foo.lua" parameters would be saved to "foo.lua.yml".
function lib.new(filepath)
  if not filepath then
    filepath = lub.path('&', 3)
    if not filepath then
      -- This can happen with tail call optimization
      filepath = lub.path('&', 4)
    end
    filepath = filepath..'.yml'
  end

  local self  = {
    preset    = 'p1',
    presets   = {},
    filepath  = filepath,
    proxies   = {},
    controls  = {},
    mappings  = {},
    rmappings = {},
  }
  setmetatable(self, lib)
  private.loadpath(self, self.filepath)
  return self
end

-- # Methods

-- Create a proxy table to write to instead of the original. Writing to the
-- proxy stores the parameter value and write the value into the original table.
-- Since a single Param object can store values from different tables, the
-- `proxy_name` string is used to separate values during save/restore. Default
-- value for `proxy_name` is 'main'.
function lib:proxy(original_table, proxy_name, settings)
  local settings = settings or {}
  local proxy = setmetatable({
    __param     = self,
    __storage   = {},
    __original  = original_table,
    __name      = proxy_name    or 'main',
  }, ProxyMt)
  self.proxies[proxy.__name] = proxy
  local proxy_data = (self.presets[self.preset] or {})[proxy.__name]
  if proxy_data then
    for key, value in pairs(proxy_data) do
      self:setValue(proxy, key, value)
    end
  end
  return proxy
end

-- nodoc
function lib:setValue(proxy, key, value, controller)
  local storage = proxy.__storage
  local old_value = storage[key]
  -- Always push value to original, even if it hasn't changed (it may change in
  -- original without us knowing it).
  proxy.__original[key] = value

  -- only map or notify if parameter is CHANGED
  if old_value ~= value then
    -- Cache value so that we can write preset to file.
    rawset(storage, key, value)
    if self.learn_next then
      self.lchange = {proxy_name = proxy.__name, key = key}
      self.learn_next = false
    end
    private.notifyControls(self, proxy.__name, key, value, controller)
  end
end

-- nodoc
-- `value` is already mapped to [0,1].
function lib:control(ctrl, key, value)
  -- get mapping
  local rmapping = (self.rmappings[ctrl.name] or {})
  if not rmapping then return end

  local rmap = rmapping[key]
  if not rmap then return end

  local proxy = self.proxies[rmap.proxy_name]
  if not rmap then return end

  self:setValue(proxy, rmap.key, value, ctrl)
end

-- Map parameter. If `proxy_name` and `key` are omitted, the last changed
-- parameter is used instead.
function lib:mapParameter(ctrl_name, ctrl_key, proxy_name, key)

  if not proxy_name then
    local lchange = self.lchange
    if not lchange then
      print("missing 'last changed' parameter. Cannot learn mapping.")
      return
    end

    proxy_name = lchange.proxy_name
    key        = lchange.key
  end

  -- ctrl_name = 'mi'
  -- ctrl_key  = 44
  -- proxy_name = 'main'
  -- key = 'hello'

  -- forward mapping
  -- main:
  --   hello:
  --     mi: 44
  lub.deepMerge(self.mappings, proxy_name, {
    [key] = {
      [ctrl_name] = ctrl_key
    }
  })

  -- reverse mapping
  -- mi:
  --   44:
  --     proxy_name: main
  --     key: hello
  lub.deepMerge(self.rmappings, ctrl_name, {
    [ctrl_key] = {
      proxy_name = proxy_name,
      key        = key,
    }
  })

  private.save(self)
end

-- Serialize all preset values to yaml.
function lib:dump()
  return yaml.dump({
    preset   = self.preset,
    presets  = self.presets,
    mappings = self.mappings,
  })
end

-- Save current table values in current preset.
function lib:savePreset()
  local preset = self.presets[self.preset]
  if not preset then
    preset = {}
    self.presets[self.preset] = preset
  end
  for proxy_name, proxy in pairs(self.proxies) do
    local tbl = preset[proxy_name]
    if not tbl then
      tbl = {}
      preset[proxy_name] = tbl
    end
    for k, value in pairs(proxy.__storage) do
      tbl[k] = value
    end
  end

  -- Write to file
  private.save(self)
end

-- Select preset named `preset_name` and load all values defined in preset into
-- original tables. Values not defined in the preset are not removed and will be
-- saved with preset.
function lib:selectPreset(preset_name)
  if not preset_name then
    print('Cannot use nil as preset name !')
    return
  end
  if type(preset_name) == 'number' then
    preset_name = 'p'..preset_name
  end
  local preset_data = self.presets[preset_name]
  if preset_data then
    -- Change values defined in preset_data
    for proxy_name, proxy_data in pairs(preset_data) do
      local proxy = self.proxies[proxy_name]
      if proxy then
        for key, value in pairs(proxy_data) do
          self:setValue(proxy, key, value)
        end
      end
    end

  else
    -- New preset with same values as current values
  end
  self.preset = preset_name
end

-- Copy all currently defined values to `preset_name`. If the preset already
-- exists, it is replaced.
function lib:copyToPreset(preset_name)
  if type(preset_name) == 'number' then
    preset_name = 'p'..preset_name
  end
  self.preset = preset_name
  self:savePreset()
end


-- # Controller methods

-- Add a new controller. The optional settings table can contain the following
-- keys:
-- + min: minimal value set by controller (0)
-- + max: maximal value set by controller (1)
function lib:addController(name, settings)
  local ctrl = {
    name       = name,
    min        = settings.min or 0,
    max        = settings.max or 1,
    param      = self,
    learn_next = false,
  }
  ctrl.range = ctrl.max - ctrl.min
  assert(ctrl.range ~= 0, 'min and max values should be different')
  self.controls[name] = ctrl
  return setmetatable(ctrl, CtrlMt)
end

-- ================================================== Proxy metatable

--- Proxy metatable
function ProxyMt.__index(proxy, key)
  return proxy.__original[key]
end

function ProxyMt.__newindex(proxy, key, value)
  proxy.__param:setValue(proxy, key, value)
end

-- ================================================== Controller metatable

CtrlMt.__index = CtrlMt

function CtrlMt:learn()
  self.learn_next = true
  self.param.learn_next = true
end

function CtrlMt:__call(key, cvalue)
  local param = self.param
  if self.learn_next then
    param:mapParameter(self.name, key)
    self.learn_next = false
  end

  local value = (cvalue - self.min) / self.range
  param:control(self, key, value)
end

-- Control callback for feedback.
-- function CtrlMt:changed(key, cvalue)
  
-- ================================================== PRIVATE

-- Load presets and mappings from files system
function private:loadpath(filepath)
  if lub.exist(filepath) then
    local data     = yaml.loadpath(filepath)
    self.presets   = data.presets or {}
    self.mappings  = data.mappings or {}
    self.rmappings = {}
    local rmappings = self.rmappings

    -- mappings = 
    -- main:
    --   hello:
    --     mi: 44
    --
    -- rmappings = 
    -- mi:
    --   44: 
    --     proxy_name: main
    --     key: hello
    for proxy_name, proxy_mappings in pairs(self.mappings) do
      for key, mappings in pairs(proxy_mappings) do
        for ctrl_name, ctrl_key in pairs(mappings) do
          -- rmappings.mi = {[44] = {proxy_name = 'main', key = 'one'}}
          lub.deepMerge(rmappings, ctrl_name, {
            [ctrl_key] = {
              proxy_name = proxy_name,
              key = key,
            }
          })
        end
      end
    end

    if data.preset then
      self:selectPreset(data.preset)
    end
  end
end

function private:save()
  lub.writeall(self.filepath, self:dump())
end

function private:notifyControls(proxy_name, key, value, skip_control)
  local proxy_mappings = self.mappings[proxy_name]
  if proxy_mappings then
    local mappings = proxy_mappings[key]
    if mappings then
      local controls = self.controls
      for ctrl_name, ctrl_key in pairs(mappings) do
        local ctrl = controls[ctrl_name]
        if ctrl and ctrl ~= skip_control then
          local fun = ctrl.changed
          if fun then
            fun(ctrl, ctrl_key, ctrl.min + (value * ctrl.range))
          end
        else
          -- print("Missing control '"..ctrl_name.."'.")
        end
      end
    end
  end
end

return lib