-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathPaintshop.lua
1787 lines (1648 loc) · 65.5 KB
/
Paintshop.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
--[[
Whole code is a bit of a mess and definitely needs reworking: splitting in separate modules,
reorganazing, etc. But at this stage it’s mostly just a small API test.
]]
local sim = ac.getSim()
local uiState = ac.getUI()
local car = ac.getCar(0)
local carDir = ac.getFolder(ac.FolderID.ContentCars)..'/'..ac.getCarID(car.index)
local skinDir = carDir..'/skins/'..ac.getCarSkinID(0)
local carNode = ac.findNodes('carRoot:0')
local carMeshes = carNode:findMeshes('{ ! material:DAMAGE_GLASS & lod:A }')
-- Calling it once at the start to initialize RealTimeStylus API and get Assetto Corsa to work
-- nicely with pens and styluses (check `ac.getPenPressure()` description for more information).
ac.getPenPressure()
local selectedMeshes ---@type ac.SceneReference
local carTexture
local aoTexture
local shortcuts = {
undo = ui.shortcut({ key = ui.KeyIndex.Z, ctrl = true }, ui.KeyIndex.XButton1),
redo = ui.shortcut({ key = ui.KeyIndex.Y, ctrl = true }, ui.KeyIndex.XButton2),
save = ui.shortcut{ key = ui.KeyIndex.S, ctrl = true },
export = ui.shortcut{ key = ui.KeyIndex.S, ctrl = true, shift = true, alt = true },
load = ui.shortcut{ key = ui.KeyIndex.O, ctrl = true },
swapColors = ui.shortcut(ui.KeyIndex.X),
flipSticker = ui.shortcut(ui.KeyIndex.Z),
toggleSymmetry = ui.shortcut(ui.KeyIndex.Y),
toggleDrawThrough = ui.shortcut(ui.KeyIndex.R),
toolBrush = ui.shortcut(ui.KeyIndex.B),
toolEraser = ui.shortcut(ui.KeyIndex.E),
toolStamp = ui.shortcut(ui.KeyIndex.S),
toolMirroringStamp = ui.shortcut(ui.KeyIndex.K),
toolBlurTool = ui.shortcut({ key = ui.KeyIndex.B, alt = true }),
toolEyeDropper = ui.shortcut(ui.KeyIndex.I),
toolMasking = ui.shortcut(ui.KeyIndex.M),
toolText = ui.shortcut(ui.KeyIndex.T),
toggleMasking = ui.shortcut({ key = ui.KeyIndex.M, ctrl = true }),
toggleOrbitCamera = ui.shortcut({ key = ui.KeyIndex.Space, ctrl = true }),
toggleProjectOtherSide = ui.shortcut({ key = ui.KeyIndex.E, ctrl = true }),
arrowLeft = ui.shortcut(ui.KeyIndex.Left),
arrowRight = ui.shortcut(ui.KeyIndex.Right),
arrowUp = ui.shortcut(ui.KeyIndex.Up),
arrowDown = ui.shortcut(ui.KeyIndex.Down),
opacity = table.range(9, 0, function (index)
return ui.shortcut(ui.KeyIndex.D0 + index), index
end)
}
local icons = ui.atlasIcons('res/icons.png', 4, 4, {
Brush = {1, 1},
Eraser = {1, 2},
Undo = {1, 3},
Redo = {1, 4},
EyeDropper = {2, 1},
Camera = {2, 2},
Save = {2, 3},
Open = {2, 4},
Stamp = {3, 1},
Masking = {3, 2},
Stencil = {3, 3},
Export = {3, 4},
Text = {4, 1},
MirroringStamp = {4, 2},
BlurTool = {4, 3},
MirroringHelper = {4, 4},
})
local taaFix = { On = 1, Off = 0 }
ac.onRelease(function ()
if carTexture and selectedMeshes then
selectedMeshes:setMaterialTexture('txDiffuse', carTexture):setMotionStencil(taaFix.Off)
end
end)
local carPreview ---@type ac.GeometryShot
local hoveredMaterial
local camera ---@type ac.GrabbedCamera
local appVisible = false
local function MeshSelection()
local ray = render.createMouseRay()
local ref = ac.emptySceneReference()
if sim.isWindowForeground and carMeshes:raycast(ray, ref) ~= -1 then
ui.text('Found:')
ui.pushFont(ui.Font.Small)
ui.text('\tMesh: '..tostring(ref:name()))
ui.text('\tMaterial: '..tostring(ref:materialName()))
ui.text('\tTexture: '..tostring(ref:getTextureSlotFilename('txDiffuse')))
ui.popFont()
ui.offsetCursorY(20)
if hoveredMaterial ~= ref:materialName() then
hoveredMaterial = ref:materialName()
if carPreview then carPreview:dispose() end
carPreview = ac.GeometryShot(carNode:findMeshes('{ material:'..hoveredMaterial..' & lod:A }'), vec2(420, 320))
carPreview:setClearColor(rgbm(0.14, 0.14, 0.14, 1))
end
local mat = mat4x4.rotation(ui.time()*0.1, vec3(0, 1, 0)):mul(car.bodyTransform)
carPreview:update(mat:transformPoint(car.aabbCenter + vec3(0, 2, 4)), mat:transformVector(vec3(0, -1, -2)), nil, 50)
ui.image(carPreview, vec2(210, 160))
ui.offsetCursorY(20)
local size = ui.imageSize(ref:getTextureSlotFilename('txDiffuse'))
if size.x > 0 and size.y > 0 then
ui.textWrapped('• Hold Shift and click to start drawing.\n• Hold Ctrl+Shift and click to start drawing using custom AO map.')
ui.offsetCursorY(20)
ui.pushFont(ui.Font.Small)
ui.textWrapped('For best results, either use a custom AO map or make sure this texture is an AO map (grayscale colors with nothing but shadows).')
ui.popFont()
ui.setShadingOffset(1, 0, 1, 1)
ui.image(ref:getTextureSlotFilename('txDiffuse'), vec2(210, 210 * size.y / size.x))
ui.resetShadingOffset()
if uiState.shiftDown and not uiState.altDown and uiState.isMouseLeftKeyClicked and not uiState.wantCaptureMouse then
if uiState.ctrlDown then
local _selectedMeshes = carNode:findMeshes('{ material:'..hoveredMaterial..' & lod:A }')
local _carTexture = ref:getTextureSlotFilename('txDiffuse')
os.openFileDialog({
title = 'Open Base AO Map',
folder = carDir,
fileTypes = { { name = 'Images', mask = '*.png;*.jpg;*.jpeg;*.dds' } },
addAllFilesFileType = true,
flags = bit.bor(os.DialogFlags.PathMustExist, os.DialogFlags.FileMustExist)
}, function (err, filename)
if not err and filename then
selectedMeshes = _selectedMeshes
carTexture = _carTexture
aoTexture = filename
camera = ac.grabCamera('Paintshop')
if camera then camera.ownShare = 0 end
end
end)
else
selectedMeshes = carNode:findMeshes('{ material:'..hoveredMaterial..' & lod:A }')
carTexture = ref:getTextureSlotFilename('txDiffuse')
aoTexture = nil
camera = ac.grabCamera('Paintshop')
if camera then camera.ownShare = 0 end
end
end
else
ui.text('Texture is missing')
end
else
ui.text('Hover a car mesh to start drawing…')
end
end
local editingCanvas, aoCanvas, maskingCanvas ---@type ui.ExtraCanvas
local editingCanvasPhase = 0
local lastRay ---@type ray
local stored = ac.storage{
color = rgbm(0, 0.2, 1, 0.5),
bgColor = rgbm(1, 1, 1, 1),
orbitCamera = true,
projectOtherSide = false,
eyeDropperRange = 1,
selectedStickerSet = 2,
alignSticker = 3,
activeToolIndex = 1,
selectedFont = '',
fontBold = false,
fontItalic = false,
hasPen = false
}
local function brushSizeMult(brush)
local p = ac.getPenPressure()
if p ~= 1 and not stored.hasPen then stored.hasPen = true end
return math.lerp(brush.penMinRadiusMult, 1, p)
end
local function brushParams(key, defaultSize, defaultAlpha, extraFields)
local t = {
brushTex = '',
brushSize = defaultSize or 0.05,
brushAspectMult = 1,
brushStepSize = 0.005,
brushAngle = 0,
brushRandomizedAngle = false,
brushAlpha = defaultAlpha or 0.5,
brushMirror = false,
penMinRadiusMult = 0.05,
withMirror = false,
paintThrough = false,
smoothing = 0
}
if extraFields then
for k, v in pairs(extraFields) do t[k] = v end
end
return ac.storage(t, key)
end
local ignoreMousePress = true
local drawing = false
local brushesDir = __dirname..'/brushes'
local decalsDir = __dirname..'/decals'
local brushes
local stickers
local selectedStickerSet
local selectedBrushOutline ---@type ui.ExtraCanvas
local selectedBrushOutlineDirty = true
local brushDistance = 1
local cameraAngle = vec2(-2.6, 0.1)
local maskingDragging = 0
local changesMade = 0
local saveFilename
-- local maskingCarStored = {} ---@type ac.GeometryShot
local undoStack = {}
local redoStack = {}
local maskingActive = false
local maskingPos = vec3(0, 0.3, 0)
local maskingDir = vec3(0, 1, 0)
local maskingCreatingFrom, maskingCreatingTo
local maskingPoints = {
vec3(0, 0.3, -1),
vec3(0, 0.3, 1),
vec3(-1, 0.3, 0),
vec3(1, 0.3, 0),
}
local function drawWithAO(baseCanvas, aoTexture)
-- Draw base editing canvas and apply AO to it. One way of doing it is to use shading offset:
-- ui.drawImage(aoTexture, 0, ui.windowSize())
-- ui.setShadingOffset(0, 0, 0, -1)
-- ui.drawImage(aoTexture, 0, ui.windowSize(), rgbm.colors.black)
-- ui.resetShadingOffset()
-- But now there is another way, to use a custom shader:
ui.renderShader({
p1 = vec2(),
p2 = ui.windowSize(),
blendMode = render.BlendMode.Opaque,
textures = {
txBase = baseCanvas,
txAO = aoTexture
},
shader = [[float4 main(PS_IN pin) {
float4 diffuseColor = txAO.SampleLevel(samLinear, pin.Tex, 0);
float4 canvasColor = txBase.SampleLevel(samLinear, pin.Tex, 0);
canvasColor.rgb *= max(diffuseColor.r, max(diffuseColor.g, diffuseColor.b)); // use maximum value of AO RGB color
canvasColor.a = 1; // return fully opaque texture so that txDetail would not bleed and CMAA2 would be happy
return canvasColor;
}]]
})
end
local function finishEditing()
selectedMeshes:setMaterialTexture('txDiffuse', carTexture):setMotionStencil(taaFix.Off)
selectedMeshes = nil
carTexture = nil
editingCanvas = nil
saveFilename = nil
-- maskingCarView = nil
undoStack = {}
redoStack = {}
changesMade = 0
ac.setWindowTitle('paintshop', nil)
if camera then
local cameraRelease
cameraRelease = setInterval(function ()
camera.ownShare = math.applyLag(camera.ownShare, 0, 0.85, ac.getDeltaT())
if camera.ownShare < 0.001 then
clearInterval(cameraRelease)
camera:dispose()
camera = nil
end
end)
end
end
local function rescanBrushes()
brushes = table.map(io.scanDir(brushesDir, '*.png'), function (x) return { string.sub(x, 1, #x - 4), brushesDir..'/'..x } end)
end
local function rescanStickers()
stickers = table.map(io.scanDir(decalsDir, '*'), function (x) return {
name = x,
items = table.map(io.scanDir(decalsDir..'/'..x, '*.png'), function (y) return { string.sub(y, 1, #y - 4), decalsDir..'/'..x..'/'..y } end)
} end)
selectedStickerSet = stickers[stored.selectedStickerSet]
end
local accessibleData ---@type ui.ExtraCanvasData
local function maskingBackup()
local b = stringify({ maskingPos, maskingDir, maskingPoints }, true)
return function (action)
if action == 'memoryFootprint' then return 0 end
if action == 'update' then return maskingBackup() end
if action == 'dispose' then return end
maskingPos, maskingDir, maskingPoints = table.unpack(stringify.parse(b))
maskingActive = true
end
end
local function addUndo(undo)
if #undoStack > 29 then
undoStack[1]('dispose')
table.remove(undoStack, 1)
end
table.insert(undoStack, undo)
table.clear(redoStack)
changesMade = changesMade + 1
end
local function stepUndo()
local last = undoStack[#undoStack]
if not last then return end
table.insert(redoStack, last('update'))
last()
last('dispose')
table.remove(undoStack)
changesMade = changesMade - 1
editingCanvasPhase = editingCanvasPhase + 1
end
local function stepRedo()
local last = redoStack[#redoStack]
if not last then return end
table.insert(undoStack, last('update'))
last()
last('dispose')
table.remove(redoStack)
changesMade = changesMade + 1
editingCanvasPhase = editingCanvasPhase + 1
end
local function undoMemoryFootpring()
return table.sum(undoStack, function (u) return u('memoryFootprint') end)
+ table.sum(redoStack, function (u) return u('memoryFootprint') end)
end
local function updateAccessibleData()
editingCanvasPhase = editingCanvasPhase + 1
if accessibleData then accessibleData:dispose() end
editingCanvas:accessData(function (err, data)
if data then accessibleData = data
elseif err then ac.warn('Failed to access canvas: '..tostring(err)) end
end)
end
local autosaveDir = ac.getFolder(ac.FolderID.Cfg)..'/apps/paintshop/autosave'
local autosaveIndex = 1
local autosavePhase = 0
setInterval(function ()
if not editingCanvas or autosavePhase == editingCanvasPhase or uiState.isMouseLeftKeyDown then return end
autosavePhase = editingCanvasPhase
io.createDir(autosaveDir)
editingCanvas:save(string.format('%s/autosave-%s.zip', autosaveDir, autosaveIndex), ac.ImageFormat.ZippedDDS)
autosaveIndex = autosaveIndex + 1
if autosaveIndex == 10 then autosaveIndex = 1 end
end, 20)
local function IconButton(icon, tooltip, active, enabled)
local r = ui.button('##'..icon, vec2(32, 32), enabled == false and ui.ButtonFlags.Disabled or active and ui.ButtonFlags.Active or ui.ButtonFlags.None)
ui.addIcon(icon, 24, 0.5, nil, 0)
if tooltip and ui.itemHovered() then ui.setTooltip(tooltip) end
return r
end
local function DrawControl()
ac.setWindowTitle('paintshop', string.gsub(saveFilename and saveFilename or carTexture..' (new)', '.+[/\\:]', '')..(changesMade ~= 0 and '*' or ''))
if IconButton(icons.Undo, nil, false, #undoStack > 0) or #undoStack > 0 and shortcuts.undo() then
stepUndo()
end
if ui.itemHovered() then
ui.setTooltip(string.format('Undo (Ctrl+Z)', #undoStack, math.ceil(undoMemoryFootpring() / (1024 * 1024))))
end
ui.sameLine(0, 4)
if IconButton(icons.Redo, string.format('Redo (Ctrl+Y)', #redoStack), false, #redoStack > 0) or #redoStack > 0 and shortcuts.redo() then
stepRedo()
end
ui.sameLine(0, 4)
if IconButton(icons.Open, 'Load image (Ctrl+O)\n\nChoose an image without ambient occlusion, preferably one saved earlier with “Save” button of this tool.\n\nIf you accidentally forgot to save or a crash happened, there are some automatically saved backups\nin “Documents/Assetto Corsa”/cfg/apps/paintshop/autosave”.\n\n(There is also an “Import” option in context menu of this button to add a semi-transparent image on top\nof current one.)') or shortcuts.load() then
os.openFileDialog({
title = 'Open',
folder = skinDir,
fileTypes = { { name = 'Images', mask = '*.png;*.jpg;*.jpeg;*.dds' } },
}, function (err, filename)
if not err and filename then
ui.setAsynchronousImagesLoading(false)
addUndo(editingCanvas:backup())
editingCanvas:clear(rgbm.new(stored.bgColor.rgb, 1)):update(function ()
ui.unloadImage(filename)
ui.drawImage(filename, 0, ui.windowSize())
end)
setTimeout(updateAccessibleData)
if not filename:lower():match('%.dds$') then
saveFilename = filename
end
changesMade = 0
end
end)
end
ui.itemPopup('openMenu', function ()
if ui.selectable('Clear canvas') then
addUndo(editingCanvas:backup())
editingCanvas:clear(rgbm.new(stored.bgColor.rgb, 1))
end
if ui.itemHovered() then
ui.setTooltip('Clears canvas using background (eraser) color')
end
if ui.selectable('Import…') then
os.openFileDialog({
title = 'Import',
folder = skinDir,
fileTypes = { { name = 'Images', mask = '*.png;*.jpg;*.jpeg;*.dds' } },
}, function (err, filename)
if not err and filename then
ui.setAsynchronousImagesLoading(false)
addUndo(editingCanvas:backup())
editingCanvas:update(function ()
ui.unloadImage(filename)
ui.drawImage(filename, 0, ui.windowSize())
end)
setTimeout(updateAccessibleData)
end
end)
end
if autosaveDir and ui.selectable('Open autosaves folder') then
io.createDir(autosaveDir)
os.openInExplorer(autosaveDir)
end
end)
ui.sameLine(0, 4)
if IconButton(icons.Save, 'Save image (Ctrl+S)\n\nImage saved like that would not have antialiasing or ambient occlusion. To apply texture, use “Export texture”\nbutton on the right.\n\n(There is also a “Save as” option in context menu of this button.)') or shortcuts.save() then
if saveFilename ~= nil then
editingCanvas:save(saveFilename)
changesMade = 0
else
os.saveFileDialog({
title = 'Save Image',
folder = skinDir,
fileTypes = { { name = 'PNG', mask = '*.png' }, { name = 'JPEG', mask = '*.jpg;*.jpeg' } },
fileName = carTexture and string.gsub(carTexture, '.+[/\\:]', ''):gsub('%.[a-zA-Z]+$', '.png'),
defaultExtension = 'dds',
}, function (err, filename)
if not err and filename then
editingCanvas:save(filename)
saveFilename = filename
changesMade = 0
end
end)
end
end
ui.itemPopup('saveMenu', function ()
if ui.selectable('Save as…') then
os.saveFileDialog({
title = 'Save Image As',
folder = skinDir,
fileTypes = { { name = 'PNG', mask = '*.png' }, { name = 'JPEG', mask = '*.jpg;*.jpeg' } },
fileName = carTexture and string.gsub(carTexture, '.+[/\\:]', ''):gsub('%.[a-zA-Z]+$', '.png'),
defaultExtension = 'dds',
}, function (err, filename)
if not err and filename then
editingCanvas:save(filename)
saveFilename = filename
changesMade = 0
end
end)
end
if autosaveDir and ui.selectable('Open autosaves folder') then
io.createDir(autosaveDir)
os.openInExplorer(autosaveDir)
end
end)
ui.sameLine(0, 4)
if IconButton(icons.Export, 'Export texture (Ctrl+Shift+Alt+S)\n\nImage saved like that is ready to use, with ambient occlusion and everything. To save an intermediate\nresult and continue working on it later, use “Save” button on the left.') or shortcuts.export() then
os.saveFileDialog({
title = 'Export Texture',
folder = skinDir,
fileTypes = { { name = 'PNG', mask = '*.png' }, { name = 'JPEG', mask = '*.jpg;*.jpeg' }, { name = 'DDS', mask = '*.dds' } },
fileName = carTexture and string.gsub(carTexture, '.+[/\\:]', ''),
fileTypeIndex = 3,
defaultExtension = 'dds',
}, function (err, filename)
if not err and filename then
aoCanvas:update(function (dt)
drawWithAO(editingCanvas, aoTexture or carTexture)
end):save(filename)
end
end)
end
ui.sameLine(0, 4)
if IconButton(ui.Icons.Leave, changesMade == 0 and 'Finish editing' or 'Cancel editing\nThere are some unsaved changes') then
if changesMade ~= 0 then
ui.modalPopup('Cancel editing', 'Are you sure to exit without saving changes?', function (okPressed)
if okPressed then
finishEditing()
end
end)
else
finishEditing()
end
end
end
local palette = {
builtin = {
rgbm(1, 1, 1, 1),
rgbm(0.8, 0.8, 0.8, 1),
rgbm(0.6, 0.6, 0.6, 1),
rgbm(1, 0, 0, 1),
rgbm(1, 0.5, 0, 1),
rgbm(1, 1, 0, 1),
rgbm(0.5, 1, 0, 1),
rgbm(0, 1, 0, 1),
rgbm(0, 1, 0.5, 1),
rgbm(0, 1, 1, 1),
rgbm(0, 0.5, 1, 1),
rgbm(0, 0, 1, 1),
rgbm(0.5, 0, 1, 1),
rgbm(1, 0, 1, 1),
rgbm(1, 0, 0.5, 1),
rgbm(0, 0, 0, 1),
rgbm(0.2, 0.2, 0.2, 1),
rgbm(0.4, 0.4, 0.4, 1),
rgbm(1, 0, 0, 1):scale(0.5),
rgbm(1, 0.5, 0, 1):scale(0.5),
rgbm(1, 1, 0, 1):scale(0.5),
rgbm(0.5, 1, 0, 1):scale(0.5),
rgbm(0, 1, 0, 1):scale(0.5),
rgbm(0, 1, 0.5, 1):scale(0.5),
rgbm(0, 1, 1, 1):scale(0.5),
rgbm(0, 0.5, 1, 1):scale(0.5),
rgbm(0, 0, 1, 1):scale(0.5),
rgbm(0.5, 0, 1, 1):scale(0.5),
rgbm(1, 0, 1, 1):scale(0.5),
rgbm(1, 0, 0.5, 1):scale(0.5),
},
user = stringify.tryParse(ac.storage.palette) or table.range(15, function (index, callbackData)
return rgbm(math.random(), math.random(), math.random(), 1)
end)
}
function palette.addToUserPalette(color)
local _, i = table.findFirst(palette.user, function (item) return item == color end)
if i ~= nil then
table.remove(palette.user, i)
else
table.remove(palette.user, 1)
end
table.insert(palette.user, color:clone())
ac.storage.palette = stringify(palette.user, true)
end
local function ColorTooltip(color)
ui.tooltip(0, function ()
ui.dummy(20)
ui.drawRectFilled(0, 20, color)
ui.drawRect(0, 20, rgbm.colors.black)
end)
end
local editing = false
local colorFlags = bit.bor(ui.ColorPickerFlags.NoAlpha, ui.ColorPickerFlags.NoSidePreview, ui.ColorPickerFlags.PickerHueWheel, ui.ColorPickerFlags.DisplayHex)
local function ColorBlock(key)
key = key or 'color'
local col = stored[key]:clone()
ui.colorPicker('##color', col, colorFlags)
if ui.itemEdited() then
stored[key] = col
editing = true
elseif editing and not ui.itemActive() then
editing = false
palette.addToUserPalette(col)
end
for i = 1, #palette.builtin do
ui.drawRectFilled(ui.getCursor(), ui.getCursor() + 14, palette.builtin[i])
if ui.invisibleButton(i, 14) then
stored[key] = palette.builtin[i]:clone()
palette.addToUserPalette(stored[key])
end
if ui.itemHovered() then
ColorTooltip(palette.builtin[i])
end
ui.sameLine(0, 0)
if ui.availableSpaceX() < 14 then
ui.newLine(0)
end
end
for i = 1, #palette.user do
ui.drawRectFilled(ui.getCursor(), ui.getCursor() + 14, palette.user[i])
if ui.invisibleButton(100 + i, 14) then
stored[key] = palette.user[i]:clone()
palette.addToUserPalette(stored[key])
end
if ui.itemHovered() then
ColorTooltip(palette.user[i])
end
ui.sameLine(0, 0)
end
ui.newLine()
if shortcuts.swapColors() then
stored[key] = stored[key] == palette.user[#palette.user] and palette.user[#palette.user - 1] or palette.user[#palette.user]
palette.addToUserPalette(stored[key])
end
end
local function BrushBaseBlock(brush, maxSize, stickerMode, noStepSize, noSymmetry)
if not ui.mouseBusy() then
local w = ui.mouseWheel()
if ui.keyboardButtonPressed(ui.KeyIndex.SquareOpenBracket, true) then w = w - 1 end
if ui.keyboardButtonPressed(ui.KeyIndex.SquareCloseBracket, true) then w = w + 1 end
if w ~= 0 then -- changing brush size with mouse wheel
if uiState.shiftDown then w = w / 10 end
if uiState.altDown then
brush.brushAngle = brush.brushAngle + w * 30
elseif not uiState.ctrlDown then
brush.brushSize = math.clamp(brush.brushSize * (1 + w * 0.15), 0.001, maxSize)
elseif stickerMode then
brush.brushAspectMult = math.clamp(brush.brushAspectMult * (1 + w * 0.25), 0.04, 25)
end
selectedBrushOutlineDirty = true
end
for i = 0, 9 do -- changing opacity photoshop style
if shortcuts.opacity[i]() then brush.brushAlpha = i == 0 and 1 or i / 10 end
end
end
if stickerMode then
if ui.checkbox('Flip sticker', brush.brushMirror) or shortcuts.flipSticker() then brush.brushMirror = not brush.brushMirror end
if ui.itemHovered() then ui.setTooltip('Flip sticker (Z)') end
end
brush.brushSize = ui.slider('##brushSize', brush.brushSize * 100, 0.1, maxSize * 100, 'Size: %.1f cm', 2) / 100
if ui.itemHovered() then ui.setTooltip('Use mouse wheel to quickly change size') end
if ui.itemEdited() then selectedBrushOutlineDirty = true end
if stored.hasPen then
brush.penMinRadiusMult = ui.slider('##penMinRadiusMult', brush.penMinRadiusMult * 100, 0, 100, 'Minimum size: %.1f%%') / 100
if ui.itemHovered() then ui.setTooltip('Size of a brush with minimum pen pressure') end
end
if stickerMode then
ui.setNextItemWidth(ui.availableSpaceX() - 60)
brush.brushAspectMult = ui.slider('##brushAspectMult', brush.brushAspectMult * 100, 4, 2500, 'Stretch: %.0f%%', 4) / 100
if ui.itemHovered() then ui.setTooltip('Use mouse wheel and hold Ctrl to quickly change size') end
if ui.itemEdited() then selectedBrushOutlineDirty = true end
ui.sameLine(0, 4)
if ui.button('Reset', vec2(56, 0)) then
brush.brushAspectMult = 1
selectedBrushOutlineDirty = true
end
end
if not stickerMode and not noStepSize then
brush.brushStepSize = ui.slider('##brushStepSize', brush.brushStepSize * 100, 0.1, 50, 'Step size: %.1f cm', 2) / 100
end
brush.brushAlpha = ui.slider('##alpha', brush.brushAlpha * 100, 0, 100, 'Opacity: %.1f%%') / 100
if ui.itemHovered() then ui.setTooltip('Use digit buttons to quickly change opacity') end
if ui.checkbox('##randomAngle', brush.brushRandomizedAngle) then brush.brushRandomizedAngle = not brush.brushRandomizedAngle end
if ui.itemHovered() then ui.setTooltip('Randomize angle when drawing') end
ui.sameLine(0, 4)
ui.setNextItemWidth(210 - 22 - 4 - 60)
brush.brushAngle = (brush.brushAngle % 360 + 360) % 360
brush.brushAngle = ui.slider('##brushAngle', brush.brushAngle, 0, 360, 'Angle: %.0f°')
if ui.itemHovered() then ui.setTooltip('Use mouse wheel and hold Alt to quickly change angle') end
ui.sameLine(0, 4)
if ui.button('Reset##angle', vec2(56, 0)) then
brush.brushAngle = 0
end
if not stickerMode and not noStepSize then
brush.smoothing = ui.slider('##smoothing', brush.smoothing * 100, 0, 100, 'Smoothing: %.1f%%') / 100
if ui.itemHovered() then ui.setTooltip('Smoothing makes brush move smoother and slower') end
end
if not noSymmetry then
if ui.checkbox('With symmetry', brush.withMirror) or shortcuts.toggleSymmetry() then brush.withMirror = not brush.withMirror end
if ui.itemHovered() then ui.setTooltip('Paith with symmetry (Y)\nMirrors things from one side of a car to another') end
end
if ui.checkbox('Paint through', brush.paintThrough) or shortcuts.toggleDrawThrough() then brush.paintThrough = not brush.paintThrough end
if ui.itemHovered() then ui.setTooltip('Paint through model (R)\nIf enabled, drawings would go through model and leave traces on the opposite side as well') end
end
local function BrushBlock(brush)
if brush.brushTex == '' then brush.brushTex = brushes[1][2] end
local anySelected = false
ui.childWindow('brushesList', vec2(210, 60), false, bit.bor(ui.WindowFlags.HorizontalScrollbar, ui.WindowFlags.AlwaysHorizontalScrollbar, ui.WindowFlags.NoBackground), function ()
ui.pushStyleColor(ui.StyleColor.Button, rgbm.colors.transparent)
for i = 1, #brushes do
local selected = brushes[i][2] == brush.brushTex
if ui.button('##'..i, 48, selected and ui.ButtonFlags.Active or ui.ButtonFlags.None) then
brush.brushTex = brushes[i][2]
selectedBrushOutlineDirty = true
end
if selected then
anySelected = true
end
ui.addIcon(brushes[i][2], 36, 0.5, nil, 0)
if ui.itemHovered() then ui.setTooltip('Brush: '..brushes[i][1]) end
ui.sameLine(0, 4)
end
ui.popStyleColor()
ui.newLine()
end)
if not anySelected then
brush.brushTex = brushes[1][2]
end
ui.itemPopup(function ()
if ui.selectable('Open in Explorer') then
os.openInExplorer(brushesDir)
end
if ui.selectable('Refresh') then
rescanBrushes()
end
end)
end
local function fitMaskingPoints(fitFirst)
if fitFirst then
maskingDir = math.cross(maskingPoints[1] - maskingPoints[2], maskingPoints[4] - maskingPoints[3]):normalize()
maskingPos = (maskingPoints[1] + maskingPoints[2]) / 2
local ort1 = math.cross(maskingDir, vec3(1, 0, 0)):normalize()
local ort2 = math.cross(maskingDir, vec3(0, 0, 1)):normalize()
maskingPoints[3] = vec3(maskingPoints[3].x, maskingPos.y - maskingPos.z * ort1.y / ort1.z + ort2.y * maskingPoints[3].x / ort2.x, 0)
maskingPoints[4] = vec3(maskingPoints[4].x, maskingPos.y - maskingPos.z * ort1.y / ort1.z + ort2.y * maskingPoints[4].x / ort2.x, 0)
else
maskingDir = math.cross(maskingPoints[1] - maskingPoints[2], maskingPoints[4] - maskingPoints[3]):normalize()
maskingPos = (maskingPoints[3] + maskingPoints[4]) / 2
local ort2 = math.cross(maskingDir, vec3(0, 0, 1)):normalize()
local ort1 = math.cross(maskingDir, vec3(1, 0, 0)):normalize()
maskingPoints[1] = vec3(0, maskingPos.y - maskingPos.x * ort2.y / ort2.x + ort1.y * maskingPoints[1].z / ort1.z, maskingPoints[1].z)
maskingPoints[2] = vec3(0, maskingPos.y - maskingPos.x * ort2.y / ort2.x + ort1.y * maskingPoints[2].z / ort1.z, maskingPoints[2].z)
end
end
local function applyQuickMasking(from, to)
if math.abs(from.x - to.x) < math.abs(from.z - to.z) then
maskingPoints[1] = vec3(0, from.y, from.z)
maskingPoints[2] = vec3(0, to.y, to.z)
maskingPoints[3] = vec3(-1, 0, 0)
maskingPoints[4] = vec3(1, 0, 0)
fitMaskingPoints(true)
else
maskingPoints[1] = vec3(0, 0, -1)
maskingPoints[2] = vec3(0, 0, 1)
maskingPoints[3] = vec3(from.x, from.y, 0)
maskingPoints[4] = vec3(to.x, to.y, 0)
fitMaskingPoints(false)
end
end
local function getBrushUp(dir, tool)
local brush = tool.brush
return mat4x4.rotation(math.rad(brush.brushRandomizedAngle and tool.__brushRandomAngle or brush.brushAngle), dir):transformVector(car.up)
end
local fonts
local fontsDir = __dirname..'/fonts'
local function rescanFonts()
fonts = {
{ name = 'Arial', source = 'Arial:@System' },
{ name = 'Bahnschrift', source = 'Bahnschrift:@System' },
{ name = 'Calibri', source = 'Calibri:@System' },
{ name = 'Comic Sans MS', source = 'Comic Sans MS:@System' },
{ name = 'Consolas', source = 'Consolas' },
{ name = 'Courier New', source = 'Courier New:@System' },
{ name = 'Impact', source = 'Impact:@System' },
{ name = 'Orbitron', source = 'Orbitron' },
{ name = 'Segoe UI', source = 'Segoe UI' },
{ name = 'Times New Roman', source = 'Times New Roman:@System' },
{ name = 'VCR OSD Mono', source = 'VCR OSD Mono' },
{ name = 'Webdings', source = 'Webdings:@System' },
}
for _, v in ipairs(io.scanDir(fontsDir, '*.ttf')) do
table.insert(fonts, { name = v:sub(1, #v - 4), source = v:sub(1, #v - 4)..':'..__dirname..'/fonts' })
end
table.sort(fonts, function (a, b) return a.name < b.name end)
end
local tools = {
{
name = 'Brush (B)',
key = shortcuts.toolBrush,
icon = icons.Brush,
ui = function (s)
ui.header('Color:')
ColorBlock()
ui.offsetCursorY(20)
ui.header('Brush:')
BrushBlock(s.brush)
BrushBaseBlock(s.brush, 0.5)
end,
brush = brushParams('brush'),
brushColor = function(s) return rgbm.new(stored.color.rgb, s.brush.brushAlpha) end,
brushSize = function (s) return vec2(s.brush.brushSize, s.brush.brushSize) end,
-- blendMode = render.BlendMode.BlendAccurate,
},
{
name = 'Eraser (E)',
key = shortcuts.toolEraser,
icon = icons.Eraser,
ui = function (s)
ui.header('Background color:')
ColorBlock('bgColor')
ui.offsetCursorY(20)
ui.header('Eraser:')
BrushBlock(s.brush)
BrushBaseBlock(s.brush, 0.5)
end,
brush = brushParams('eraser'),
brushColor = function(s) return stored.bgColor end,
brushSize = function (s) return vec2(s.brush.brushSize, s.brush.brushSize) end,
},
{
name = 'Stamp (S)',
key = shortcuts.toolStamp,
icon = icons.Stamp,
ui = function (s)
ui.header('Color:')
ColorBlock()
ui.offsetCursorY(20)
ui.header('Stamp:')
ui.combo('##set', string.format('Set: %s', selectedStickerSet.name), ui.ComboFlags.None, function ()
for i = 1, #stickers do
if ui.selectable(stickers[i].name, stickers[i] == selectedStickerSet) then
selectedStickerSet = stickers[i]
stored.selectedStickerSet = i
end
end
if ui.selectable('New category…') then
ui.modalPrompt('Create new category', 'Category name:', nil, function (value)
if #value > 0 and io.createDir(decalsDir..'/'..value) then
ui.toast(ui.Icons.Confirm, 'New category created: '..tostring(value))
rescanStickers()
selectedStickerSet = table.findFirst(stickers, function (item) return item.name == value end)
else
ui.toast(ui.Icons.Warning, 'Couldn’t create a new category: '..tostring(value))
end
end)
end
end)
local items = selectedStickerSet.items
if s.brush.brushTex == '' then s.brush.brushTex = items[1][2] end
ui.childWindow('stickersList', vec2(210, 210), false, ui.WindowFlags.AlwaysVerticalScrollbar, function ()
ui.pushStyleColor(ui.StyleColor.Button, rgbm.colors.transparent)
local itemSize = vec2(100, 60)
for i = 1, #items do
if ui.areaVisible(itemSize) then
local size = ui.imageSize(items[i][2])
if ui.button('##'..i, vec2(100, 60), s.brush.brushTex == items[i][2] and ui.ButtonFlags.Active or ui.ButtonFlags.None) then
s.brush.brushTex = items[i][2]
selectedBrushOutlineDirty = true
end
local s = vec2(90, 90 * size.y / size.x)
if s.y > 54 then s:scale(54 / s.y) end
ui.addIcon(items[i][2], s, 0.5, nil, 0)
if ui.itemHovered() then ui.setTooltip('Brush: '..items[i][1]) end
else
ui.dummy(itemSize)
end
if i % 2 == 1 then ui.sameLine(0, 0) end
end
ui.popStyleColor()
ui.newLine()
end)
local _, i = table.findFirst(items, function (item, _, tex)
return item[2] == tex
end, s.brush.brushTex)
i = i or 0
if shortcuts.arrowRight() then
s.brush.brushTex = items[i % #items + 1][2]
selectedBrushOutlineDirty = true
end
if shortcuts.arrowDown() then
s.brush.brushTex = items[(i + 1) % #items + 1][2]
selectedBrushOutlineDirty = true
end
if shortcuts.arrowLeft() then
s.brush.brushTex = items[(i - 2 + #items) % #items + 1][2]
selectedBrushOutlineDirty = true
end
if shortcuts.arrowUp() then
s.brush.brushTex = items[(i - 3 + #items) % #items + 1][2]
selectedBrushOutlineDirty = true
end
if ui.itemHovered() then
ui.setTooltip('Use arrow keys to quickly switch between items')
end
ui.itemPopup(function ()
if ui.selectable('Add new decal…') then
os.openFileDialog({
title = 'Add new decal',
defaultFolder = ac.getFolder(ac.FolderID.Root),
fileTypes = { { name = 'Images', mask = '*.png' } },
addAllFilesFileType = true,
flags = bit.bor(os.DialogFlags.PathMustExist, os.DialogFlags.FileMustExist)
}, function (err, filename)
if filename then
local fileName = filename:gsub('.+[/\\\\]', '')
if io.copyFile(filename, decalsDir..'/'..selectedStickerSet.name..'/'..fileName, true) then
rescanStickers()
selectedStickerSet = table.findFirst(stickers, function (item) return item.name == selectedStickerSet.name end)
s.brush.brushTex = decalsDir..'/'..selectedStickerSet.name..'/'..fileName
ui.toast(ui.Icons.Confirm, 'New decal added: '..fileName:sub(1, #fileName - 4))
return
end
end
if err or filename then
ui.toast(ui.Icons.Warning, 'Couldn’t add a new decal: '..(err or 'unknown error'))
end
end)
end
if ui.selectable('Open in Explorer') then
os.openInExplorer(decalsDir)
end
if ui.selectable('Refresh') then
rescanStickers()
end
end)
ui.alignTextToFramePadding()
ui.text('Align sticker:')
ui.sameLine()
ui.setNextItemWidth(ui.availableSpaceX())
stored.alignSticker = ui.combo('##alignSticker', stored.alignSticker, ui.ComboFlags.None, {
'No',
'Align to surface',
'Fully align'
})
local brush = s.brush
BrushBaseBlock(brush, 4, true)
end,
brush = brushParams('stamp', 0.2, 1),
brushColor = function(s) return rgbm.new(stored.color.rgb, s.brush.brushAlpha) end,
brushSize = function (s)
local size = ui.imageSize(s.brush.brushTex)
return vec2(s.brush.brushSize, s.brush.brushSize * size.y / size.x)
end,
stickerMode = true,
stickerContinious = false,
},
{
name = 'Mirroring stamp (K)',
key = shortcuts.toolMirroringStamp,
icon = icons.MirroringStamp,
ui = function (s)
ui.header('Mirroring stamp:')
BrushBlock(s.brush)
BrushBaseBlock(s.brush, 0.5, false, true, true)
end,
brush = brushParams('mirroringStamp'),
procBrushTex = function (s, ray, previewMode)
if not s._shot then
s._shot = ac.GeometryShot(selectedMeshes, 256):setShadersType(render.ShadersType.SampleColor)
s._ksAmbient = selectedMeshes:getMaterialPropertyValue('ksAmbient')
end
local up = getBrushUp(ray.dir, s)
selectedMeshes:setMaterialTexture('txDiffuse', editingCanvas)
selectedMeshes:setMaterialProperty('ksAmbient', 1)
s._shot:clear(table.random(rgbm.colors))
local lpos, ldir, lup = car.worldToLocal:transformPoint(ray.pos), car.worldToLocal:transformVector(ray.dir), car.worldToLocal:transformVector(up)
lpos.x, ldir.x, lup.x = -lpos.x, -ldir.x, -lup.x
local ipos, idir, iup = car.bodyTransform:transformPoint(lpos), car.bodyTransform:transformVector(ldir), car.bodyTransform:transformVector(lup)
local brushSize = previewMode and s.brush.brushSize or s.brush.brushSize * brushSizeMult(s.brush)
s._shot:setOrthogonalParams(vec2(brushSize, brushSize), 100):update(ipos, idir, iup, 0)
selectedMeshes:setMaterialTexture('txDiffuse', aoCanvas)
selectedMeshes:setMaterialProperty('ksAmbient', s._ksAmbient)
-- DebugTex = s._shot
return s._shot
end,
procProjParams = function (s, pr)
pr.mask2 = s.brush.brushTex
pr.mask2Flags = render.TextureMaskFlags.UseAlpha
end,
brushColor = function(s) return rgbm(1, 1, 1, s.brush.brushAlpha) end,
brushSize = function (s) return vec2(-s.brush.brushSize, s.brush.brushSize) end,
stickerMode = true,
stickerNoAlignment = true,
stickerContinious = true