-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathsim.lua
1855 lines (1707 loc) · 63.8 KB
/
sim.lua
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
-- The is the first versioned sim-namespace
-- The very first API without namespace (e.g. simGetObjectHandle) is only
-- included if 'supportOldApiNotation' is true in 'usrset.txt'
local sim = _S.sim
_S.sim = nil
sim.addLog = addLog
sim.quitSimulator = quitSimulator
sim.registerScriptFuncHook = registerScriptFuncHook
function sim.readCustomBufferData(obj, tag)
local retVal = sim.readCustomStringData(obj, tag)
if retVal then
retVal = tobuffer(retVal)
end
return retVal
end
function sim.writeCustomBufferData(obj, tag, data)
return sim.writeCustomStringData(obj, tag, data)
end
function sim.getBufferSignal(sigName)
local retVal = sim.getStringSignal(sigName)
if retVal then
retVal = tobuffer(retVal)
end
return retVal
end
function sim.setBufferSignal(sigName, data)
sim.setStringSignal(sigName, tostring(data))
end
function sim.clearBufferSignal(sigName)
sim.clearStringSignal(sigName)
end
function sim.setStepping(enable)
-- Convenience function, so that we have the same, more intuitive name also with external clients
-- Needs to be overridden by Python wrapper and remote API server code
if type(enable) ~= 'number' then enable = not enable end
return setAutoYield(enable)
end
function sim.acquireLock()
-- needs to be overridden by remote API components
setYieldAllowed(false)
end
function sim.releaseLock()
-- needs to be overridden by remote API components
setYieldAllowed(true)
end
function sim.yield()
if getYieldAllowed() then
if sim.isScriptRunningInThread() == 1 then
sim._switchThread() -- old, deprecated threads
else
local thread, yieldForbidden = coroutine.running()
if not yieldForbidden then coroutine.yield() end
end
end
end
function sim.step(wait)
-- Convenience function, for a more intuitive name, depending on the context
-- Needs to be overridden by Python wrapper and remote API server code
sim.yield()
end
require('mathx')
require('stringx')
require('tablex')
require('checkargs')
require('matrix')
require('grid')
require('functional')
require('var')
require('motion').extend(sim)
require('deprecated.old').extend(sim)
require('sim-deprecated').extend(sim)
sim.stopSimulation = wrap(sim.stopSimulation, function(origFunc)
return function(wait)
origFunc()
local t = sim.getObjectInt32Param(sim.getScript(sim.handle_self), sim.scriptintparam_type)
if wait and t ~= sim.scripttype_main and t ~= sim.scripttype_simulation and getYieldAllowed() then
local cnt = 0
while sim.getSimulationState() ~= sim.simulation_stopped and cnt < 20 do -- even if we run in a thread, we might not be able to yield (e.g. across a c-boundary)
cnt = cnt + 1
sim.step()
end
end
end
end)
-- Make sim.registerScriptFuncHook work also with a function as arg 2:
function _S.registerScriptFuncHook(funcNm, func, before)
local retVal
if type(func) == 'string' then
retVal = _S.registerScriptFuncHookOrig(funcNm, func, before)
else
local str = tostring(func)
retVal = _S.registerScriptFuncHookOrig(funcNm, '_S.' .. str, before)
_S[str] = func
end
return retVal
end
_S.registerScriptFuncHookOrig = sim.registerScriptFuncHook
sim.registerScriptFuncHook = _S.registerScriptFuncHook
function math.random2(lower, upper)
-- same as math.random, but each script has its own generator
local r = sim.getRandom()
if lower then
local b = 1
local d
if upper then
b = lower
d = upper - b
else
d = lower - b
end
local e = d / (d + 1)
r = b + math.floor(r * d / e)
end
return r
end
function math.randomseed2(seed)
-- same as math.randomseed, but each script has its own generator
sim.getRandom(seed)
end
function sim.yawPitchRollToAlphaBetaGamma(...)
local yawAngle, pitchAngle, rollAngle = checkargs({
{type = 'float'}, {type = 'float'}, {type = 'float'},
}, ...)
local lb = sim.setStepping(true)
local Rx = sim.buildMatrix({0, 0, 0}, {rollAngle, 0, 0})
local Ry = sim.buildMatrix({0, 0, 0}, {0, pitchAngle, 0})
local Rz = sim.buildMatrix({0, 0, 0}, {0, 0, yawAngle})
local m = sim.multiplyMatrices(Ry, Rx)
m = sim.multiplyMatrices(Rz, m)
local alphaBetaGamma = sim.getEulerAnglesFromMatrix(m)
local alpha = alphaBetaGamma[1]
local beta = alphaBetaGamma[2]
local gamma = alphaBetaGamma[3]
sim.setStepping(lb)
return alpha, beta, gamma
end
function sim.alphaBetaGammaToYawPitchRoll(...)
local alpha, beta, gamma = checkargs({
{type = 'float'}, {type = 'float'}, {type = 'float'}
}, ...)
local lb = sim.setStepping(true)
local m = sim.buildMatrix({0, 0, 0}, {alpha, beta, gamma})
local v = m[9]
if v > 1 then v = 1 end
if v < -1 then v = -1 end
local pitchAngle = math.asin(-v)
local yawAngle, rollAngle
if math.abs(v) < 0.999999 then
rollAngle = math.atan2(m[10], m[11])
yawAngle = math.atan2(m[5], m[1])
else
-- Gimbal lock
rollAngle = math.atan2(-m[7], m[6])
yawAngle = 0
end
sim.setStepping(lb)
return yawAngle, pitchAngle, rollAngle
end
function sim.getObjectsWithTag(tagName, justModels)
local retObjs = {}
local objs = sim.getObjectsInTree(sim.handle_scene)
for i = 1, #objs, 1 do
if (not justModels) or ((sim.getModelProperty(objs[i]) & sim.modelproperty_not_model) == 0) then
local dat = sim.readCustomDataTags(objs[i])
for j = 1, #dat, 1 do
if dat[j] == tagName then
retObjs[#retObjs + 1] = objs[i]
break
end
end
end
end
return retObjs
end
function sim.executeLuaCode(theCode)
local f = loadstring(theCode)
if f then
local a, b = pcall(f)
return a, b
else
return false, 'compilation error'
end
end
function sim.fastIdleLoop(enable)
local data = sim.readCustomStringData(sim.handle_app, '__IDLEFPSSTACKSIZE__')
local stage = 0
local defaultIdleFps
if data and #data > 0 then
data = sim.unpackInt32Table(data)
stage = data[1]
defaultIdleFps = data[2]
else
defaultIdleFps = sim.getInt32Param(sim.intparam_idle_fps)
end
if enable then
stage = stage + 1
else
if stage > 0 then stage = stage - 1 end
end
if stage > 0 then
sim.setInt32Param(sim.intparam_idle_fps, 0)
else
sim.setInt32Param(sim.intparam_idle_fps, defaultIdleFps)
end
sim.writeCustomStringData(
sim.handle_app, '__IDLEFPSSTACKSIZE__', sim.packInt32Table({stage, defaultIdleFps})
)
end
function sim.getLoadedPlugins()
local ret = {}
local index = 0
while true do
local moduleName = sim.getPluginName(index)
if moduleName then
table.insert(ret, moduleName)
else
break
end
index = index + 1
end
return ret
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.loadPlugin(name)
-- legacy plugins
local path = sim.getStringParam(sim.stringparam_application_path)
local plat = sim.getInt32Param(sim.intparam_platform)
local windows, mac, linux = 0, 1, 2
if plat == windows then
path = path .. '\\simExt' .. name .. '.dll'
elseif plat == mac then
path = path .. '/libsimExt' .. name .. '.dylib'
elseif plat == linux then
path = path .. '/libsimExt' .. name .. '.so'
else
error('unknown platform: ' .. plat)
end
return sim.loadModule(path, name)
end
function sim.getUserVariables()
local ng = {}
if _S.initGlobals then
for key, val in pairs(_G) do if not _S.initGlobals[key] then ng[key] = val end end
else
ng = _G
end
-- hide a few additional system variables:
ng.sim_call_type = nil
ng.sim_code_function_to_run = nil
ng.__notFirst__ = nil
ng.__scriptCodeToRun__ = nil
ng._S = nil
ng.H = nil
ng.restart = nil
return ng
end
function sim.getMatchingPersistentDataTags(...)
local pattern = checkargs({{type = 'string'}}, ...)
local result = {}
for index, value in ipairs(sim.getPersistentDataTags()) do
if value:match(pattern) then result[#result + 1] = value end
end
return result
end
function sim.throttle(t, func, ...)
if _S.lastExecTime == nil then _S.lastExecTime = {} end
local h = string.dump(func)
local now = sim.getSystemTime()
if _S.lastExecTime[h] == nil or _S.lastExecTime[h] + t < now then
func(...)
_S.lastExecTime[h] = now
end
end
function _S.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(), _S.scheduler.rtpq)
if sim.getSimulationState() == sim.simulation_advancing_running then
fn(sim.getSimulationTime(), _S.scheduler.simpq)
end
if _S.scheduler.simpq:isempty() and _S.scheduler.rtpq:isempty() then
sim.registerScriptFuncHook('sysCall_nonSimulation', _S.schedulerCallback, true)
sim.registerScriptFuncHook('sysCall_sensing', _S.schedulerCallback, true)
sim.registerScriptFuncHook('sysCall_suspended', _S.schedulerCallback, true)
_S.scheduler.hook = false
end
end
function sim.scheduleExecution(func, args, timePoint, simTime)
if not _S.scheduler then
local priorityqueue = require 'priorityqueue'
_S.scheduler = {
simpq = priorityqueue(),
rtpq = priorityqueue(),
simTime = {},
nextId = 1,
}
end
local id = _S.scheduler.nextId
_S.scheduler.nextId = id + 1
local pq
if simTime then
pq = _S.scheduler.simpq
_S.scheduler.simTime[id] = true
else
pq = _S.scheduler.rtpq
end
pq:push(timePoint, {
id = id,
func = func,
args = args,
timePoint = timePoint,
simTime = simTime,
})
if not _S.scheduler.hook then
sim.registerScriptFuncHook('sysCall_nonSimulation', _S.schedulerCallback, true)
sim.registerScriptFuncHook('sysCall_sensing', _S.schedulerCallback, true)
sim.registerScriptFuncHook('sysCall_suspended', _S.schedulerCallback, true)
_S.scheduler.hook = true
end
return id
end
function sim.cancelScheduledExecution(id)
if not _S.scheduler then return end
local pq = nil
if _S.scheduler.simTime[id] then
_S.scheduler.simTime[id] = nil
pq = _S.scheduler.simpq
else
pq = _S.scheduler.rtpq
end
return pq:cancel(function(item) return item.id == id end)
end
function sim.getAlternateConfigs(...)
local jointHandles, inputConfig, tipHandle, lowLimits, ranges = checkargs({
{type = 'table', item_type = 'int'},
{type = 'table', item_type = 'float'},
{type = 'int', default = -1},
{type = 'table', item_type = 'float', default = NIL, nullable = true},
{type = 'table', item_type = 'float', default = NIL, nullable = true},
}, ...)
if #jointHandles < 1 or #jointHandles ~= #inputConfig or
(lowLimits and #jointHandles ~= #lowLimits) or (ranges and #jointHandles ~= #ranges) then
error("Bad table size.")
end
local lb = sim.setStepping(true)
local initConfig = {}
local x = {}
local confS = {}
local err = false
for i = 1, #jointHandles, 1 do
initConfig[i] = sim.getJointPosition(jointHandles[i])
local c, interv = sim.getJointInterval(jointHandles[i])
local t = sim.getJointType(jointHandles[i])
local sp = sim.getObjectFloatParam(jointHandles[i], sim.jointfloatparam_screw_pitch)
if t == sim.joint_revolute and not c then
if sp == 0 then
if inputConfig[i] - math.pi * 2 >= interv[1] or inputConfig[i] + math.pi * 2 <=
interv[1] + interv[2] then
-- We use the low and range values from the joint's settings
local y = inputConfig[i]
while y - math.pi * 2 >= interv[1] do y = y - math.pi * 2 end
x[i] = {y, interv[1] + interv[2]}
end
end
end
if x[i] then
if lowLimits and ranges then
-- the user specified low and range values. Use those instead:
local l = lowLimits[i]
local r = ranges[i]
if r ~= 0 then
if r > 0 then
if l < interv[1] then
-- correct for user bad input
r = r - (interv[1] - l)
l = interv[1]
end
if l > interv[1] + interv[2] then
-- bad user input. No alternative position for this joint
x[i] = {inputConfig[i], inputConfig[i]}
err = true
else
if l + r > interv[1] + interv[2] then
-- correct for user bad input
r = interv[1] + interv[2] - l
end
if inputConfig[i] - math.pi * 2 >= l or inputConfig[i] + math.pi * 2 <=
l + r then
local y = inputConfig[i]
while y < l do y = y + math.pi * 2 end
while y - math.pi * 2 >= l do
y = y - math.pi * 2
end
x[i] = {y, l + r}
else
-- no alternative position for this joint
x[i] = {inputConfig[i], inputConfig[i]}
err = (inputConfig[i] < l) or (inputConfig[i] > l + r)
end
end
else
r = -r
l = inputConfig[i] - r * 0.5
if l < x[i][1] then l = x[i][1] end
local u = inputConfig[i] + r * 0.5
if u > x[i][2] then u = x[i][2] end
x[i] = {l, u}
end
end
end
else
-- there's no alternative position for this joint
x[i] = {inputConfig[i], inputConfig[i]}
end
confS[i] = x[i][1]
end
local configs = {}
if not err then
for i = 1, #jointHandles, 1 do sim.setJointPosition(jointHandles[i], inputConfig[i]) end
local desiredPose = 0
if tipHandle ~= -1 then desiredPose = sim.getObjectMatrix(tipHandle) end
configs =
_S.loopThroughAltConfigSolutions(jointHandles, desiredPose, confS, x, 1, tipHandle)
end
for i = 1, #jointHandles, 1 do sim.setJointPosition(jointHandles[i], initConfig[i]) end
if next(configs) ~= nil then
configs = Matrix:fromtable(configs)
configs = configs:data()
end
sim.setStepping(lb)
return configs
end
function sim.copyTable(t)
return table.deepcopy(t)
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, nullable = true},
}, ...)
local confCnt = #times
local dof = math.floor(#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
if method and method.type == 'quadraticBezier' then
local w = 1
if method.strength then w = method.strength end
if w < 0.05 then w = 0.05 end
local closed = true
for i = 1, dof, 1 do
if (path[i] ~= path[(confCnt - 1) * dof + i]) then
closed = false
break
end
end
if method.forceOpen then closed = false end
local i0, i1, i2
if t < 0.5 then
if li == 1 and not closed then
retVal = _S.linearInterpolate(_S.getConfig(path, dof, li), _S.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 = _S.linearInterpolate(_S.getConfig(path, dof, i0), _S.getConfig(path, dof, i1), 1 - 0.25 * w + t * 0.5, types)
local b = _S.linearInterpolate(_S.getConfig(path, dof, i1), _S.getConfig(path, dof, i2), 0.25 * w + t * 0.5, types)
retVal = _S.linearInterpolate(a, b, 0.5 + t / w, types)
else
retVal = _S.linearInterpolate(_S.getConfig(path, dof, li), _S.getConfig(path, dof, hi), t, types)
end
end
else
if hi == confCnt and not closed then
retVal = _S.linearInterpolate(_S.getConfig(path, dof, li), _S.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 = _S.linearInterpolate(_S.getConfig(path, dof, i0), _S.getConfig(path, dof, i1), 1 - 0.5 * w + t * 0.5, types)
local b = _S.linearInterpolate(_S.getConfig(path, dof, i1), _S.getConfig(path, dof, i2), t * 0.5, types)
retVal = _S.linearInterpolate(a, b, t / w, types)
else
retVal = _S.linearInterpolate(_S.getConfig(path, dof, li), _S.getConfig(path, dof, hi), t, types)
end
end
end
end
if not method or method.type == 'linear' then
retVal = _S.linearInterpolate(_S.getConfig(path, dof, li), _S.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")
local scriptHandle
if sim.getBoolParam(sim.boolparam_usingscriptobjects) then
code = "path = require('models.path_customization-2')\n\n" .. code
scriptHandle = sim.createScript(sim.scripttype_customization, code)
sim.setObjectParent(scriptHandle, retVal)
else
scriptHandle = sim.addScript(sim.scripttype_customization)
code = "path = require('models.deprecated.path_customization')\n\n" .. code
sim.setScriptText(scriptHandle, code)
sim.associateScriptWithObject(scriptHandle, retVal)
end
local prop = sim.getModelProperty(retVal)
sim.setModelProperty(retVal, (prop | sim.modelproperty_not_model) - sim.modelproperty_not_model) -- model
prop = sim.getObjectProperty(retVal)
sim.setObjectProperty(retVal, prop | sim.objectproperty_canupdatedna | sim.objectproperty_collapsed)
local data = sim.packTable({ctrlPts, options, subdiv, smoothness, orientationMode, upVector})
sim.writeCustomStringData(retVal, "ABC_PATH_CREATION", data)
sim.initScript(scriptHandle)
setYieldAllowed(fl)
end
return retVal
end
function sim.createCollection(arg1, arg2)
local retVal
if type(arg1) == 'string' then
retVal = sim._createCollection(arg1, arg2) -- for backward compatibility
else
if arg1 == nil then arg1 = 0 end
retVal = sim.createCollectionEx(arg1)
end
return retVal
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, nullable = 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
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, nullable = true},
{type = 'table', item_type = 'int', default = NIL, nullable = true},
}, ...)
if (#confA ~= #confB) or (metric and #confA ~= #metric) or (types and #confA ~= #types) then
error("Bad table size.")
end
return _S.getConfigDistance(confA, confB, metric, types)
end
function _S.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 m1 = sim.poseToMatrix({0, 0, 0, confA[j - 3], confA[j - 2], confA[j - 1], confA[j - 0]})
local m2 = sim.poseToMatrix({0, 0, 0, confB[j - 3], confB[j - 2], confB[j - 1], confB[j - 0]})
local a, angle = sim.getRotationAxis(m1, m2)
dd = angle * metric[j - 3]
end
end
d = d + dd * dd
end
return math.sqrt(d)
end
function sim.getPathLengths(...)
local path, dof, cb = checkargs({
{type = 'table', item_type = 'float', size = '2..*'}, {type = 'int'},
{type = 'any', default = NIL, 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 = 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[i]:data(), pM[i + 1]:data(), dof)
else
d = cb(pM[i]:data(), pM[i + 1]:data(), dof)
end
else
d = sim.getConfigDistance(pM[i]:data(), pM[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.getObjectInt32Param(objs[i], sim.objintparam_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
else
-- Legacy signals
sigName = target
while true do
retVal = sim.getInt32Signal(sigName) or sim.getFloatSignal(sigName) or sim.getStringSignal(sigName)
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.getModelBB(handle)
-- Undocumented function (for now)
local s = {}
local m = sim.getObjectFloatParam(handle, sim.objfloatparam_modelbbox_max_x)
local n = sim.getObjectFloatParam(handle, sim.objfloatparam_modelbbox_min_x)
s[1] = m - n
local m = sim.getObjectFloatParam(handle, sim.objfloatparam_modelbbox_max_y)
local n = sim.getObjectFloatParam(handle, sim.objfloatparam_modelbbox_min_y)
s[2] = m - n
local m = sim.getObjectFloatParam(handle, sim.objfloatparam_modelbbox_max_z)
local n = sim.getObjectFloatParam(handle, sim.objfloatparam_modelbbox_min_z)
s[3] = m - n
return s
end
function sim.readCustomDataBlockEx(handle, tag, options)
-- Undocumented function (for now)
options = options or {}
local data = sim.readCustomStringData(handle, tag)
if tag == '__info__' then
return data, 'cbor'
else
local info = sim.readCustomTableData(handle, '__info__')
local tagInfo = info.blocks and info.blocks[tag] or {}
local dataType = tagInfo.type or options.dataType
return data, dataType
end
end
function sim.writeCustomDataBlockEx(handle, tag, data, options)
-- Undocumented function (for now)
options = options or {}
sim.writeCustomStringData(handle, tag, data)
if tag ~= '__info__' and options.dataType then
local info = sim.readCustomTableData(handle, '__info__')
info.blocks = info.blocks or {}
info.blocks[tag] = info.blocks[tag] or {}
info.blocks[tag].type = options.dataType
sim.writeCustomTableData(handle, '__info__', info, {dataType = 'cbor'})
end
end
function sim.readCustomTableData(...)
local handle, tagName, options = checkargs({
{type = 'int'},
{type = 'string'},
{type = 'table', default = {}},
}, ...)
local data, dataType = sim.readCustomDataBlockEx(handle, tagName)
if data == nil or #data == 0 then
data = {}
else
if isbuffer(data) then
data = tostring(data)
end
if dataType == 'cbor' then
local cbor = require 'org.conman.cbor'
local data0 = data
data = cbor.decode(data0)
if type(data) ~= 'table' and tagName == '__info__' then
-- backward compat: old __info__ blocks were encoded with sim.packTable
data = sim.unpackTable(data0)
end
else
data = sim.unpackTable(data)
end
end
return data
end
function sim.writeCustomTableData(...)
local handle, tagName, theTable, options = checkargs({
{type = 'int'},
{type = 'string'},
{type = 'table'},
{type = 'table', default = {}},
}, ...)
if next(theTable) == nil then
sim.writeCustomDataBlockEx(handle, tagName, '', options)
else
if options.dataType == 'cbor' then
local cbor = require 'org.conman.cbor'
theTable = cbor.encode(theTable)
else