-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathsim-2.lua
More file actions
2502 lines (2312 loc) · 98.8 KB
/
sim-2.lua
File metadata and controls
2502 lines (2312 loc) · 98.8 KB
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local sim = table.clone(_S.internalApi.sim)
sim.version = 2
local locals = {}
__2 = {} -- sometimes globals are needed (but __2 only for sim-2)
local simEigen = require 'simEigen'
local checkargs = require('checkargs-2')
require('motion-2').extend(sim)
function sim.callMethod(target, name, ...)
if locals[name] or (string.sub(name, 1, 1) == "@") then
if string.sub(name, 1, 1) == "@" then
-- c-side is calling!
if not sim.Object:isobject(target) then
function getTargetObj(t)
return sim.Object(t)
end
local ok, err = pcall(getTargetObj, target)
if not ok then
function dummyFunc()
error("error in 'sim.callMethod': target does not exist.")
end
local ok, err = pcall(dummyFunc)
return err -- error msg
end
end
name = name:sub(2)
if type(locals[name]) == 'function' then
local res = table.pack(pcall(locals[name], target, name, ...))
if res[1] then
return '', table.unpack(res, 2, res.n)
else
return res[2] -- error msg
end
else
function dummyFunc()
error("error in 'sim.callMethod': method '" .. name .. "' does not exist.")
end
local ok, err = pcall(dummyFunc)
return err -- error msg
end
else
return locals[name](target, name, ...)
end
else
if sim.Object:isobject(target) then
target = target.handle
end
return sim._callMethod(target, name, ...)
--[[
function toSimpleType(arg)
local t = -1 -- stands for simple types directly supported (e.g. sim.stackitem_double, sim.stackitem_table, etc.)
if arg == nil then
t = sim.stackitem_null
arg = 0
elseif type(arg) == 'table' then
if isbuffer(arg) then
t = -2 -- stands for buffer
arg = tostring(arg)
elseif sim.Object:isobject(arg) then
t = sim.stackitem_handle
arg = arg.handle
elseif simEigen.Matrix:ismatrix(arg) then
t = 'm' .. tostring(arg:rows()) .. 'x' .. tostring(arg:cols()) -- "m[rows]x[cols]"
arg = arg:data()
elseif simEigen.Quaternion:isquaternion(arg) then
t = sim.stackitem_quaternion
arg = arg:data()
elseif simEigen.Pose:ispose(arg) then
t = sim.stackitem_pose
arg = arg:data()
else
local narg = {}
t = {}
for k, v in pairs(arg) do
local arg_, t_ = toSimpleType(v)
narg[k] = arg_
t[k] = t_
end
arg = narg
end
end
return arg, t
end
function toExtendedType(arg, t)
if t == -2 then
arg = tobuffer(arg)
elseif t == sim.stackitem_null then
arg = nil
elseif t == sim.stackitem_handle then
arg = sim.Object(arg)
elseif t == sim.stackitem_quaternion then
arg = simEigen.Quaternion(arg)
elseif t == sim.stackitem_pose then
arg = simEigen.Pose(arg)
elseif type(t) == 'string' then
local rows, cols = t:match("m(%d+)x(%d+)") -- "m[rows]x[cols]"
arg = simEigen.Matrix(tonumber(rows), tonumber(cols), arg)
elseif type(t) == 'table' then
local narg = {}
for k, v in pairs(arg) do
local arg_ = toExtendedType(v, t[k])
narg[k] = arg_
end
arg = narg
end
return arg
end
local args = table.pack(...)
local types = {}
for i = 1, args.n do
local arg, t = toSimpleType(args[i])
args[i] = arg
types[i] = t
end
args.n = nil -- important!!
local retVals = {}
local ret = table.pack(sim._callMethod(target, name, args, types))
ret.n = nil
for i = 1, #ret // 2 do
local arg = toExtendedType(ret[2 * (i - 1) + 1], ret[2 * (i - 1) + 2])
retVals[i] = arg
end
return table.unpack(retVals)
--]]
end
end
function locals.registerFunctionHook(target, methodName, funcNm, func, before)
if before == nil then before = true end
if type(func) == 'string' then
registerScriptFuncHook(funcNm, func, before, false)
else
local str = tostring(func)
registerScriptFuncHook(funcNm, '__2.' .. str, before, false)
__2[str] = func
end
end
function locals.removeFunctionHook(target, methodName, funcNm, func, before)
if before == nil then before = true end
if type(func) == 'string' then
registerScriptFuncHook(funcNm, func, before, true)
else
local str = tostring(func)
registerScriptFuncHook(funcNm, '__2.' .. str, before, true)
__2[str] = nil
end
end
function locals.lock(target, methodName, acquire)
setYieldAllowed(not acquire)
end
function locals.yield(target, methodName)
if getYieldAllowed() then
local thread, yieldForbidden = coroutine.running()
if not yieldForbidden then coroutine.yield() end
end
end
function locals.step(target, methodName)
locals.yield(target, methodName)
end
function locals.getAncestors(target, methodName, ...)
local objTypes, depth, objTypesMap = checkargs.checkargsEx({funcName = methodName}, {
{type = 'table', item_type = 'string', size = '0..*', default = {'sceneObject'}},
{type = 'int', default = 9999},
{type = 'table', default_nil = true, nullable = true},
}, ...)
local types = {}
if objTypesMap then
types = objTypesMap
else
for i = 1, #objTypes do
types[objTypes[i]] = true
end
end
local retVal = {}
while target do
target = target.parent
if target then
if types[target.objectType] or types['sceneObject'] then
retVal[#retVal + 1] = target
end
else
break
end
depth = depth - 1
if depth == 0 then
break
end
end
return retVal
end
function locals.getDescendants(target, methodName, ...)
local objTypes, depth, objTypesMap = ...
if #methodName > 0 then
-- Do not verify again with reentrance
objTypes, depth, objTypesMap = checkargs.checkargsEx({funcName = methodName}, {
{type = 'table', item_type = 'string', size = '0..*', default = {'sceneObject'}},
{type = 'int', default = 9999},
{type = 'table', default_nil = true, nullable = true},
}, ...)
end
local types = {}
if objTypesMap then
types = objTypesMap
else
for i = 1, #objTypes do
types[objTypes[i]] = true
end
end
local retVal = {}
if depth > 0 then
if target == sim.scene then
for i = 1, #target.orphans do
local child = target.orphans[i]
if types[child.objectType] or types['sceneObject'] then
retVal[#retVal + 1] = child
end
retVal = table.add(retVal, locals.getDescendants(child, '', {}, depth - 1, types))
end
else
for i = 1, #target.children do
local child = target.children[i]
if types[child.objectType] or types['sceneObject'] then
retVal[#retVal + 1] = child
end
retVal = table.add(retVal, locals.getDescendants(child, '', {}, depth - 1, types))
end
end
end
return retVal
end
function locals.getFunctions(target, methodName, ...)
return setmetatable({}, {
__index = function(self, k)
return function(self_, ...)
assert(self_ == self, 'methods must be called with object:method(args...)')
return target:callFunction(k, ...)
end
end,
})
end
sim.auxiliaryConsoleClose = wrap(sim.auxiliaryConsoleClose, function(origFunc)
return function(...)
origFunc(...)
end
end)
sim.auxiliaryConsolePrint = wrap(sim.auxiliaryConsolePrint, function(origFunc)
return function(...)
origFunc(...)
end
end)
sim.auxiliaryConsoleShow = wrap(sim.auxiliaryConsoleShow, function(origFunc)
return function(...)
origFunc(...)
end
end)
function sim.getObjectAliasRelative(handle, baseHandle, aliasOptions, options)
if handle == baseHandle then return '.' end
aliasOptions = aliasOptions or -1
options = options or {}
local function getPath(h, parent)
parent = parent or -1
local tmp = h
local path = {}
while tmp ~= parent do
if tmp == -1 then return end
table.insert(path, 1, tmp)
tmp = sim.getObjectParent(tmp)
end
return path
end
local path = getPath(handle)
local basePath = getPath(baseHandle)
local commonAncestor = -1
local commonAncestorModel = -1
for i = 1, math.min(#path, #basePath) do
if path[i] == basePath[i] then
commonAncestor = path[i]
if sim.getBoolProperty(path[i], 'modelBase') then
commonAncestorModel = path[i]
end
else
break
end
end
local function isAncestor(a, h)
-- true iff. h is a (grand-)child of a
if a == h then return true end
local tmp = h
while tmp ~= -1 do
tmp = sim.getObjectParent(tmp)
if tmp == a then return true end
end
return false
end
if commonAncestor == -1 then
return sim.getObjectAlias(handle, aliasOptions)
elseif commonAncestor == baseHandle then
-- simple case: handle is a (grand-)child of baseHandle
local p = getPath(handle, baseHandle)
p = filter(
function(h)
return sim.getBoolProperty(h, 'modelBase') or h == p[#p]
end, p
)
return (options.noDot and '' or './') .. table.join(map(sim.getObjectAlias, p), '/')
elseif commonAncestor == handle then
-- reverse case: go upwards in the hierarchy
for col = 1, 0, -1 do
for up = 0, 30 do
for colcol = 0, 30 do
local p = {}
for _ = 1, col do table.insert(p, ':') end
for _ = 1, colcol do table.insert(p, '::') end
for _ = 1, up do table.insert(p, '..') end
p = table.join(p, '/')
if sim.getObject(p, {proxy = baseHandle, noError = true}) == handle then
return p
end
end
end
end
else
local p_bh_cam = sim.getObjectAliasRelative(commonAncestorModel, baseHandle, aliasOptions)
local p_cam_h = sim.getObjectAliasRelative(handle, commonAncestorModel, aliasOptions, {noDot = true} )
if commonAncestorModel ~= -1 and p_bh_cam and p_cam_h then
return p_bh_cam .. '/' .. p_cam_h
end
local p_bh_ca = sim.getObjectAliasRelative(commonAncestor, baseHandle, aliasOptions)
local p_ca_h = sim.getObjectAliasRelative(handle, commonAncestor, aliasOptions, {noDot = true} )
if p_bh_ca and p_ca_h then return p_bh_ca .. '/' .. p_ca_h end
end
end
function sim.fastIdleLoop(enable)
local data = sim.getBufferProperty(sim.handle_app, 'signal.__IDLEFPSSTACKSIZE__', {noError = true}) -- sim-1 uses buffers too, stay compatible!
local stage = 0
local defaultIdleFps
if data and #data > 0 then
data = sim.unpackInt32Table(data)
stage = data[1]
defaultIdleFps = data[2]
else
defaultIdleFps = sim.getIntProperty(sim.handle_app, 'idleFps')
end
if enable then
stage = stage + 1
else
if stage > 0 then stage = stage - 1 end
end
if stage > 0 then
sim.setIntProperty(sim.handle_app, 'idleFps', 0)
else
sim.setIntProperty(sim.handle_app, 'idleFps', defaultIdleFps)
end
sim.setBufferProperty(sim.handle_app, 'signal.__IDLEFPSSTACKSIZE__', sim.packInt32Table({stage, defaultIdleFps}))
end
--[[
function sim.isPluginLoaded(pluginName)
local index = 0
local moduleName = ''
while moduleName do
moduleName = sim.getPluginName(index)
if moduleName == pluginName then return true end
index = index + 1
end
return false
end
--]]
function sim.throttle(t, func, ...)
locals.lastExecTime = locals.lastExecTime or {}
locals.throttleSched = locals.throttleSched or {}
local h = string.dump(func)
local now = sim.getSystemTime()
-- cancel any previous scheduled execution: (see sim.scheduleExecution below)
if locals.throttleSched[h] then
sim.cancelScheduledExecution(locals.throttleSched[h])
locals.throttleSched[h] = nil
end
if locals.lastExecTime[h] == nil or locals.lastExecTime[h] + t < now then
func(...)
locals.lastExecTime[h] = now
else
-- if skipping the call (i.e. because it exceeds target rate)
-- schedule the last call in the future:
locals.throttleSched[h] = sim.scheduleExecution(function(...)
func(...)
locals.lastExecTime[h] = now
end, {...}, locals.lastExecTime[h] + t)
end
end
function locals.schedulerCallback()
local function fn(t, pq)
local item = pq:peek()
if item and item.timePoint <= t then
item.func(table.unpack(item.args or {}))
pq:pop()
fn(t, pq)
end
end
fn(sim.getSystemTime(), locals.scheduler.rtpq)
if sim.getSimulationState() == sim.simulation_advancing_running then
fn(sim.getSimulationTime(), locals.scheduler.simpq)
end
if locals.scheduler.simpq:isempty() and locals.scheduler.rtpq:isempty() then
sim.registerScriptFuncHook('sysCall_nonSimulation', locals.schedulerCallback, true)
sim.registerScriptFuncHook('sysCall_sensing', locals.schedulerCallback, true)
sim.registerScriptFuncHook('sysCall_suspended', locals.schedulerCallback, true)
locals.scheduler.hook = false
end
end
function sim.scheduleExecution(func, args, timePoint, simTime)
if not locals.scheduler then
local priorityqueue = require 'priorityqueue'
locals.scheduler = {
simpq = priorityqueue(),
rtpq = priorityqueue(),
simTime = {},
nextId = 1,
}
end
local id = locals.scheduler.nextId
locals.scheduler.nextId = id + 1
local pq
if simTime then
pq = locals.scheduler.simpq
locals.scheduler.simTime[id] = true
else
pq = locals.scheduler.rtpq
end
pq:push(timePoint, {
id = id,
func = func,
args = args,
timePoint = timePoint,
simTime = simTime,
})
if not locals.scheduler.hook then
sim.registerScriptFuncHook('sysCall_nonSimulation', locals.schedulerCallback, true)
sim.registerScriptFuncHook('sysCall_sensing', locals.schedulerCallback, true)
sim.registerScriptFuncHook('sysCall_suspended', locals.schedulerCallback, true)
locals.scheduler.hook = true
end
return id
end
function sim.cancelScheduledExecution(id)
if not locals.scheduler then return end
local pq = nil
if locals.scheduler.simTime[id] then
locals.scheduler.simTime[id] = nil
pq = locals.scheduler.simpq
else
pq = locals.scheduler.rtpq
end
return pq:cancel(function(item) return item.id == id end)
end
function sim.closePath(...)
local path, times = checkargs({
{type = 'table', item_type = 'float', size = '2..*'},
{type = 'table', item_type = 'float', size = '2..*'},
}, ...)
local confCnt = #times
local dof = #path // confCnt
local firstCp = table.slice(path, 1, dof)
local lastCp = table.slice(path, #path - dof + 1, #path)
path = table.add(path, firstCp)
local nl = sim.getPathLengths(table.add(lastCp, firstCp), dof)
times = table.add(times, {times[#times] + nl[2]})
confCnt = confCnt + 1
return path, times
end
function sim.getPathInterpolatedConfig(...)
local path, times, t, method, types = checkargs({
{type = 'table', item_type = 'float', size = '2..*'},
{type = 'table', item_type = 'float', size = '2..*'},
{type = 'float'},
{type = 'table', default = {type = 'linear', strength = 1.0, forceOpen = false}, nullable = true},
{type = 'table', item_type = 'int', size = '1..*', default_nil = true, nullable = true},
}, ...)
method = method or {}
local pathType = method.type or 'linear'
local forceOpen = method.forceOpen == true
local closed = method.closed == true
local strength = method.strength or 1.
-- "forceOpen" can be set if not passing "closed", otherwise it's opposite value
if method.closed ~= nil then
forceOpen = not closed
end
if closed then
path, times = sim.closePath(path, times)
end
local confCnt = #times
local dof = #path // confCnt
if (dof * confCnt ~= #path) or (types and dof ~= #types) then error("Bad table size.") end
if types == nil then
types = {}
for i = 1, dof, 1 do types[i] = 0 end
end
local retVal = {}
local li = 1
local hi = 2
if t < 0 then t = 0 end
-- if confCnt>2 then
if t >= times[#times] then t = times[#times] - 0.00000001 end
local ll, hl
for i = 2, #times, 1 do
li = i - 1
hi = i
ll = times[li]
hl = times[hi]
if hl > t then -- >= gives problems with overlapping points
break
end
end
t = (t - ll) / (hl - ll)
-- else
-- if t>1 then t=1 end
-- end
closed = true -- if path is closed is determined a few lines below
if pathType == 'quadraticBezier' then
local w = math.max(0.05, strength)
for i = 1, dof, 1 do
if (path[i] ~= path[(confCnt - 1) * dof + i]) then
closed = false
break
end
end
if forceOpen then closed = false end
local i0, i1, i2
if t < 0.5 then
if li == 1 and not closed then
retVal = locals.linearInterpolate(locals.getConfig(path, dof, li), locals.getConfig(path, dof, hi), t, types)
else
if t < 0.5 * w then
i0 = li - 1
i1 = li
i2 = hi
if li == 1 then i0 = confCnt - 1 end
local a = locals.linearInterpolate(locals.getConfig(path, dof, i0), locals.getConfig(path, dof, i1), 1 - 0.25 * w + t * 0.5, types)
local b = locals.linearInterpolate(locals.getConfig(path, dof, i1), locals.getConfig(path, dof, i2), 0.25 * w + t * 0.5, types)
retVal = locals.linearInterpolate(a, b, 0.5 + t / w, types)
else
retVal = locals.linearInterpolate(locals.getConfig(path, dof, li), locals.getConfig(path, dof, hi), t, types)
end
end
else
if hi == confCnt and not closed then
retVal = locals.linearInterpolate(locals.getConfig(path, dof, li), locals.getConfig(path, dof, hi), t, types)
else
if t > (1 - 0.5 * w) then
i0 = li
i1 = hi
i2 = hi + 1
if hi == confCnt then i2 = 2 end
t = t - (1 - 0.5 * w)
local a = locals.linearInterpolate(locals.getConfig(path, dof, i0), locals.getConfig(path, dof, i1), 1 - 0.5 * w + t * 0.5, types)
local b = locals.linearInterpolate(locals.getConfig(path, dof, i1), locals.getConfig(path, dof, i2), t * 0.5, types)
retVal = locals.linearInterpolate(a, b, t / w, types)
else
retVal = locals.linearInterpolate(locals.getConfig(path, dof, li), locals.getConfig(path, dof, hi), t, types)
end
end
end
elseif pathType == 'linear' then
retVal = locals.linearInterpolate(locals.getConfig(path, dof, li), locals.getConfig(path, dof, hi), t, types)
end
return retVal
end
function sim.createPath(...)
local retVal
local attrib, intParams, floatParams, col = ...
if type(attrib) == 'number' then
retVal = sim._createPath(attrib, intParams, floatParams, col) -- for backward compatibility
else
local ctrlPts, options, subdiv, smoothness, orientationMode, upVector = checkargs({
{type = 'table', item_type = 'float', size = '14..*'},
{type = 'int', default = 0},
{type = 'int', default = 100},
{type = 'float', default = 1.0},
{type = 'int', default = 0},
{type = 'table', item_type = 'float', size = '3', default = {0, 0, 1}},
}, ...)
local fl = setYieldAllowed(false)
local code = [[function path.shaping(path,pathIsClosed,upVector)
local section={0.02,-0.02,0.02,0.02,-0.02,0.02,-0.02,-0.02,0.02,-0.02}
local color={0.7,0.9,0.9}
local options=0
if pathIsClosed then
options=options|4
end
local shape=sim.generateShapeFromPath(path,section,options,upVector)
sim.setShapeColor(shape,nil,sim.colorcomponent_ambient_diffuse,color)
return shape
end]]
retVal = sim.createDummy(0.04, {0, 0.68, 0.47, 0, 0, 0, 0, 0, 0, 0, 0, 0})
sim.setObjectAlias(retVal, "Path")
code = "path = require('models.path_customization-2')\n\n" .. code
local scriptHandle = sim.createScript(sim.scripttype_customization, code)
sim.setObjectParent(scriptHandle, retVal)
local prop = sim.getIntProperty(retVal, 'model.propertyFlags')
sim.setIntProperty(retVal, 'model.propertyFlags', (prop | sim.modelproperty_not_model) - sim.modelproperty_not_model)
prop = sim.getIntProperty(retVal, 'objectPropertyFlags')
sim.setIntProperty(retVal, 'objectPropertyFlags', prop | sim.objectproperty_collapsed)
local data = sim.packTable({ctrlPts, options, subdiv, smoothness, orientationMode, upVector})
sim.setBufferProperty(retVal, "customData.ABC_PATH_CREATION", data)
sim.initScript(scriptHandle)
setYieldAllowed(fl)
end
return retVal
end
function sim.createCollection(arg)
return sim.createCollectionEx(arg or 0)
end
function sim.resamplePath(...)
local path, pathLengths, finalConfigCnt, method, types = checkargs({
{type = 'table', item_type = 'float', size = '2..*'},
{type = 'table', item_type = 'float', size = '2..*'},
{type = 'int'},
{type = 'table', default = {type = 'linear', strength = 1.0, forceOpen = false}},
{type = 'table', item_type = 'int', size = '1..*', default_nil = true, nullable = true},
}, ...)
method = table.deepcopy(method) or {}
local closed = method.closed == true
local confCnt = #pathLengths
local dof = math.floor(#path / confCnt)
if dof * confCnt ~= #path or (confCnt < 2) or (types and dof ~= #types) then
error("Bad table size.")
end
if closed then
confCnt = confCnt + 1
path, pathLengths = sim.closePath(path, pathLengths)
method.closed = nil
method.forceOpen = false
end
local retVal = {}
for i = 1, finalConfigCnt, 1 do
local c = sim.getPathInterpolatedConfig(
path, pathLengths, pathLengths[#pathLengths] * (i - 1) / (finalConfigCnt - 1),
method, types
)
for j = 1, dof, 1 do retVal[(i - 1) * dof + j] = c[j] end
end
return retVal
end
function sim.getConfigDistance(...)
local confA, confB, metric, types = checkargs({
{type = 'table', item_type = 'float', size = '1..*'},
{type = 'table', item_type = 'float', size = '1..*'},
{type = 'table', item_type = 'float', default_nil = true, nullable = true},
{type = 'table', item_type = 'int', default_nil = true, nullable = true},
}, ...)
if (#confA ~= #confB) or (metric and #confA ~= #metric) or (types and #confA ~= #types) then
error("Bad table size.")
end
return locals.getConfigDistance(confA, confB, metric, types)
end
function locals.getConfigDistance(confA, confB, metric, types)
if metric == nil then
metric = {}
for i = 1, #confA, 1 do metric[i] = 1 end
end
if types == nil then
types = {}
for i = 1, #confA, 1 do types[i] = 0 end
end
local d = 0
local qcnt = 0
for j = 1, #confA, 1 do
local dd = 0
if types[j] == 0 then
dd = (confB[j] - confA[j]) * metric[j] -- e.g. joint with limits
end
if types[j] == 1 then
local dx = math.atan2(math.sin(confB[j] - confA[j]), math.cos(confB[j] - confA[j]))
local v = confA[j] + dx
dd = math.atan2(math.sin(v), math.cos(v)) * metric[j] -- cyclic rev. joint (-pi;pi)
end
if types[j] == 2 then
qcnt = qcnt + 1
if qcnt == 4 then
qcnt = 0
local q1 = simEigen.Quaternion({confA[j - 3], confA[j - 2], confA[j - 1], confA[j - 0]})
local q2 = simEigen.Quaternion({confB[j - 3], confB[j - 2], confB[j - 1], confB[j - 0]})
local a, angle = q1:axisangle(q2)
dd = angle * metric[j - 3]
end
end
d = d + dd * dd
end
return math.sqrt(d)
end
function sim.getPathLengths(...)
local simEigen = require('simEigen')
local path, dof, cb = checkargs({
{type = 'table', item_type = 'float', size = '2..*'}, {type = 'int'},
{type = 'any', default_nil = true, nullable = true},
}, ...)
local confCnt = math.floor(#path / dof)
if dof < 1 or (confCnt < 2) then error("Bad table size.") end
local distancesAlongPath = {0}
local totDist = 0
local pM = simEigen.Matrix(confCnt, dof, path)
local metric = {}
local tt = {}
for i = 1, dof, 1 do
if i > 3 then
metric[#metric + 1] = 0.0
else
metric[#metric + 1] = 1.0
end
tt[#tt + 1] = 0
end
for i = 1, pM:rows() - 1, 1 do
local d
if cb then
if type(cb) == 'string' then
d = _G[cb](pM:row(i):data(), pM:row(i + 1):data(), dof)
else
d = cb(pM:row(i):data(), pM:row(i + 1):data(), dof)
end
else
d = sim.getConfigDistance(pM:row(i):data(), pM:row(i + 1):data(), metric, tt)
end
totDist = totDist + d
distancesAlongPath[i + 1] = totDist
end
return distancesAlongPath, totDist
end
function sim.changeEntityColor(...)
local entityHandle, color, colorComponent = checkargs({
{type = 'int'},
{type = 'table', size = 3, item_type = 'float'},
{type = 'int', default = sim.colorcomponent_ambient_diffuse},
}, ...)
local colorData = {}
local objs = {entityHandle}
if sim.isHandle(entityHandle, sim.objecttype_collection) then
objs = sim.getCollectionObjects(entityHandle)
end
for i = 1, #objs, 1 do
if sim.getObjectType(objs[i]) == sim.sceneobject_shape then
local visible = sim.getBoolProperty(objs[i], 'visible')
if visible == 1 then
local res, col = sim.getShapeColor(objs[i], '@compound', colorComponent)
colorData[#colorData + 1] = {handle = objs[i], data = col, comp = colorComponent}
sim.setShapeColor(objs[i], nil, colorComponent, color)
end
end
end
return colorData
end
function sim.restoreEntityColor(...)
local colorData = checkargs({{type = 'table'}, size = '1..*'}, ...)
for i = 1, #colorData, 1 do
if sim.isHandle(colorData[i].handle, sim.objecttype_sceneobject) then
sim.setShapeColor(colorData[i].handle, '@compound', colorData[i].comp, colorData[i].data)
end
end
end
function sim.wait(...)
local dt, simTime = checkargs({{type = 'float'}, {type = 'bool', default = true}}, ...)
local retVal = 0
if simTime then
local st = sim.getSimulationTime()
while sim.getSimulationTime() - st < dt do sim.step() end
retVal = sim.getSimulationTime() - st - dt
else
local st = sim.getSystemTime()
while sim.getSystemTime() - st < dt do sim.step() end
end
return retVal
end
function sim.waitForSignal(target, sigName)
local retVal
if type(target) == 'number' then
-- Signals via properties
while true do
retVal = sim.getProperty(target, 'signal.' .. sigName, {noError = true})
if retVal then break end
sim.step()
end
end
return retVal
end
function sim.serialRead(...)
local portHandle, length, blocking, closingStr, timeout = checkargs({
{type = 'int'},
{type = 'int'},
{type = 'bool', default = false},
{type = 'string', default = ''},
{type = 'float', default = 0},
}, ...)
local retVal
if blocking then
local st = sim.getSystemTime()
while true do
local data = _S.serialPortData[portHandle]
_S.serialPortData[portHandle] = ''
if #data < length then
local d = sim._serialRead(portHandle, length - #data)
if d then data = data .. d end
end
if #data >= length then
retVal = string.sub(data, 1, length)
if #data > length then
data = string.sub(data, length + 1)
_S.serialPortData[portHandle] = data
end
break
end
if closingStr ~= '' then
local s, e = string.find(data, closingStr, 1, true)
if e then
retVal = string.sub(data, 1, e)
if #data > e then
data = string.sub(data, e + 1)
_S.serialPortData[portHandle] = data
end
break
end
end
if sim.getSystemTime() - st >= timeout and timeout ~= 0 then
retVal = data
break
end
sim.step()
_S.serialPortData[portHandle] = data
end
else
local data = _S.serialPortData[portHandle]
_S.serialPortData[portHandle] = ''
if #data < length then
local d = sim._serialRead(portHandle, length - #data)
if d then data = data .. d end
end
if #data > length then
retVal = string.sub(data, 1, length)
data = string.sub(data, length + 1)
_S.serialPortData[portHandle] = data
else
retVal = data
end
end
return retVal
end
function sim.serialOpen(...)
local portString, baudRate = checkargs({{type = 'string'}, {type = 'int'}}, ...)
local retVal = sim._serialOpen(portString, baudRate)
if not _S.serialPortData then _S.serialPortData = {} end
_S.serialPortData[retVal] = ''
return retVal
end
function sim.serialClose(...)
local portHandle = checkargs({{type = 'int'}}, ...)
sim._serialClose(portHandle)
if _S.serialPortData then _S.serialPortData[portHandle] = nil end
end
function sim.setShapeBB(handle, size)
local s = sim.getShapeBB(handle)
for i = 1, 3, 1 do if math.abs(s[i]) > 0.00001 then s[i] = size[i] / s[i] end end
sim.scaleObject(handle, s[1], s[2], s[3], 0)
end
function sim.getProperty(target, pname, opts)
local retVal
local noError = opts and opts.noError
local ptype, pflags, descr = sim.getPropertyInfo(target, pname, opts)
if not noError then
assert(ptype, 'no such property: ' .. pname)
end
if ptype then
retVal = sim.getPropertyGetter(ptype)(target, pname)
end
return retVal
end
function sim.setProperty(target, pname, pvalue, ptype)
if string.startswith(pname, 'customData.') then
-- custom data properties need type (param `ptype`, can be string
-- e.g.: 'intvector', or can be int, e.g.: sim.propertytype_intvector)
-- if not specified, it will be inferred from lua's variable type
if type(ptype) == 'string' then
ptype = sim['propertytype_' .. ptype]
assert(ptype, 'invalid property type string')
end
if ptype == nil then
-- ptype not provided -> guess it
local ltype = type(pvalue)
if ltype == 'number' then
if math.type(pvalue) == 'integer' then
ptype = sim.propertytype_int
else
ptype = sim.propertytype_float
end
elseif ltype == 'string' then
ptype = sim.propertytype_string
elseif ltype == 'boolean' then
ptype = sim.propertytype_bool
elseif ltype == 'table' then
local Color = require 'Color'
local simEigen = require 'simEigen'
if Color:iscolor(pvalue) then
ptype = sim.propertytype_color
elseif sim.Object:isobject(pvalue) then
ptype = sim.propertytype_handle
elseif simEigen.Vector:isvector(pvalue, 2) then
ptype = sim.propertytype_vector2
elseif simEigen.Vector:isvector(pvalue, 3) then
ptype = sim.propertytype_vector3
elseif simEigen.Quaternion:isquaternion(pvalue) then
ptype = sim.propertytype_quaternion
elseif simEigen.Pose:ispose(pvalue) then
ptype = sim.propertytype_pose
elseif simEigen.Matrix:ismatrix(pvalue, 3, 3) then
ptype = sim.propertytype_matrix3x3
elseif simEigen.Matrix:ismatrix(pvalue, 4, 4) then
ptype = sim.propertytype_matrix4x4
elseif simEigen.Matrix:ismatrix(pvalue) then
ptype = sim.propertytype_matrix
else
ptype = sim.propertytype_table
end
else
error('unsupported property type: ' .. ltype)
end
end
else
assert(ptype == nil, 'cannot specify type for static properties')
ptype = sim.getPropertyInfo(target, pname)
assert(ptype ~= nil, 'no such property: ' .. pname)
end