-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpixelnebula.go
More file actions
1469 lines (1274 loc) · 38.6 KB
/
pixelnebula.go
File metadata and controls
1469 lines (1274 loc) · 38.6 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
package pixelnebula
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"hash"
"log"
"os"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/landaiqing/go-pixelnebula/animation"
"github.com/landaiqing/go-pixelnebula/cache"
"github.com/landaiqing/go-pixelnebula/converter"
"github.com/landaiqing/go-pixelnebula/errors"
"github.com/landaiqing/go-pixelnebula/style"
"github.com/landaiqing/go-pixelnebula/theme"
)
const (
hashLength = 12
)
var (
// 优化正则表达式,使用更高效的模式
numberRegex = regexp.MustCompile(`[0-9]`)
// 使用非贪婪模式并优化颜色匹配模式
colorRegex = regexp.MustCompile(`#([^;]*);`)
// 使用字节池减少内存分配
hashBufPool = sync.Pool{
New: func() interface{} {
buf := make([]byte, 64)
return &buf
},
}
// 使用分片锁减少锁竞争
keyCacheShards = 16 // 分片数量
keyCacheLocks = make([]sync.RWMutex, keyCacheShards)
keyCacheShardData = make([]map[string][2]int, keyCacheShards)
// 使用对象池减少内存分配
builderPool = sync.Pool{
New: func() interface{} {
return &strings.Builder{}
},
}
mapPool = sync.Pool{
New: func() interface{} {
return make(map[string]string, 6)
},
}
keyMapPool = sync.Pool{
New: func() interface{} {
return make(map[string][2]int, 6)
},
}
)
// init 初始化分片缓存
func init() {
// 初始化分片缓存
for i := 0; i < keyCacheShards; i++ {
keyCacheShardData[i] = make(map[string][2]int)
}
}
// 计算字符串哈希获取分片索引
func getShardIndex(key string) int {
var hashKey uint32
for i := 0; i < len(key); i++ {
hashKey = hashKey*31 + uint32(key[i])
}
return int(hashKey % uint32(keyCacheShards))
}
type PNOptions struct {
ThemeIndex int // 主题索引
StyleIndex int // 风格索引
ParallelRender bool // 是否启用并行渲染
ConcurrencyPool int // 并发池大小,默认为CPU核心数
}
type PixelNebula struct {
SvgEnd string
ThemeManager *theme.Manager
StyleManager *style.Manager
AnimManager *animation.Manager
Cache *cache.PNCache
Hasher hash.Hash
Options *PNOptions
Width int
Height int
ImgData []byte
}
// NewPixelNebula 创建一个PixelNebula实例
func NewPixelNebula() *PixelNebula {
return &PixelNebula{
SvgEnd: "</svg>",
ThemeManager: theme.NewThemeManager(),
StyleManager: style.NewShapeManager(),
AnimManager: animation.NewAnimationManager(),
Hasher: sha256.New(),
Options: &PNOptions{ThemeIndex: -1, StyleIndex: -1, ParallelRender: false, ConcurrencyPool: runtime.NumCPU()}, // 初始化为 -1 表示未设置
Width: 231,
Height: 231,
}
}
// getSvgStart 根据当前宽高生成SVG开始标签
func (pn *PixelNebula) getSvgStart() string {
return fmt.Sprintf("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 %d %d\">", pn.Width, pn.Height)
}
// WithTheme 设置固定主题
func (pn *PixelNebula) WithTheme(themeIndex int) *PixelNebula {
// 如果已设置 style,则验证主题索引是否有效
if styleIndex := pn.Options.StyleIndex; styleIndex >= 0 {
// 获取该风格下的主题数量
themeCount := pn.ThemeManager.ThemeCount(styleIndex)
if themeIndex < 0 || themeIndex >= themeCount {
log.Printf("pixelnebula: theme index range is:[0, %d), but got %d", themeCount, themeIndex)
panic(errors.ErrInvalidTheme)
}
}
pn.Options.ThemeIndex = themeIndex
return pn
}
// WithStyle 设置固定风格
func (pn *PixelNebula) WithStyle(style style.StyleType) *PixelNebula {
styleIndex, err := pn.StyleManager.GetStyleIndex(style)
if err != nil {
panic(err)
}
pn.Options.StyleIndex = styleIndex
return pn
}
// WithSize 设置尺寸
func (pn *PixelNebula) WithSize(width, height int) *PixelNebula {
pn.Width = width
pn.Height = height
return pn
}
// WithCustomizeTheme 设置自定义主题
func (pn *PixelNebula) WithCustomizeTheme(theme []theme.Theme) *PixelNebula {
pn.ThemeManager.CustomizeTheme(theme)
return pn
}
// WithCustomizeStyle 设置自定义风格
func (pn *PixelNebula) WithCustomizeStyle(style []style.StyleSet) *PixelNebula {
pn.StyleManager.CustomizeStyle(style)
return pn
}
// hashToNum 将哈希字符串转换为数字
func (pn *PixelNebula) hashToNum(hash []string) int64 {
if len(hash) == 0 {
return 0
}
// 使用位运算直接计算哈希值,减少内存分配和计算复杂度
var result int64
for _, h := range hash {
// 优化:直接处理字符,避免ParseInt的开销
for i := 0; i < len(h); i++ {
if h[i] >= '0' && h[i] <= '9' {
// 使用位运算进行计算: result = result*10 + (h[i] - '0')
result = (result << 3) + (result << 1) + int64(h[i]-'0')
}
}
}
// 确保结果为正数
if result < 0 {
result = -result
}
return result
}
// getCacheKey 生成缓存键的哈希表示
func (pn *PixelNebula) getCacheKey(id string, hash []string, index int, opts *PNOptions) string {
// 构造一个唯一的键字符串
var key string
if opts != nil && opts.StyleIndex >= 0 && opts.ThemeIndex >= 0 {
key = fmt.Sprintf("%s_%d_%d_%d", id, index, opts.StyleIndex, opts.ThemeIndex)
} else if len(hash) > 0 {
key = fmt.Sprintf("%s_%d_%s", id, index, strings.Join(hash, ""))
} else {
key = fmt.Sprintf("%s_%d", id, index)
}
return key
}
// calcKey 计算主题和部分的键值
func (pn *PixelNebula) calcKey(hash []string, opts *PNOptions) [2]int {
// 检查是否使用固定值
if opts != nil && opts.StyleIndex >= 0 && opts.ThemeIndex >= 0 {
return [2]int{opts.StyleIndex, opts.ThemeIndex}
}
// 计算缓存键
cacheKey := strings.Join(hash, "")
// 计算分片索引
shardIndex := getShardIndex(cacheKey)
// 尝试从缓存中获取结果,使用读锁
keyCacheLocks[shardIndex].RLock()
if result, ok := keyCacheShardData[shardIndex][cacheKey]; ok {
keyCacheLocks[shardIndex].RUnlock()
return result
}
keyCacheLocks[shardIndex].RUnlock()
// 计算哈希值
hashNum := pn.hashToNum(hash)
// 获取可用的风格数量
styleCount := pn.ThemeManager.StyleCount()
if styleCount == 0 {
return [2]int{0, 0}
}
// 使用位运算优化取模操作
styleIndex := int(hashNum % int64(styleCount))
if styleIndex < 0 {
styleIndex = -styleIndex
}
// 获取该风格下的主题数量
themeCount := pn.ThemeManager.ThemeCount(styleIndex)
if themeCount == 0 {
return [2]int{styleIndex, 0}
}
// 使用哈希值的不同部分计算主题索引
themeIndex := int(hashNum % int64(themeCount))
if themeIndex < 0 {
themeIndex = -themeIndex
}
// 将结果存入缓存,使用写锁
result := [2]int{styleIndex, themeIndex}
keyCacheLocks[shardIndex].Lock()
keyCacheShardData[shardIndex][cacheKey] = result
keyCacheLocks[shardIndex].Unlock()
return result
}
// WithCache 设置缓存选项
func (pn *PixelNebula) WithCache(options cache.CacheOptions) *PixelNebula {
pn.Cache = cache.NewCache(options)
// 确保启动监控器
if pn.Cache != nil && options.Monitoring.Enabled && pn.Cache.GetMonitor() == nil {
pn.Cache.Monitor = cache.NewMonitor(pn.Cache, options.Monitoring)
pn.Cache.Monitor.Start()
}
return pn
}
// WithDefaultCache 设置默认缓存选项
func (pn *PixelNebula) WithDefaultCache() *PixelNebula {
pn.Cache = cache.NewDefaultCache()
// 确保启动监控器
if pn.Cache != nil && pn.Cache.GetOptions().Monitoring.Enabled && pn.Cache.GetMonitor() == nil {
pn.Cache.Monitor = cache.NewMonitor(pn.Cache, pn.Cache.GetOptions().Monitoring)
pn.Cache.Monitor.Start()
}
return pn
}
// WithCompression 设置压缩选项
func (pn *PixelNebula) WithCompression(options cache.CompressOptions) *PixelNebula {
if pn.Cache != nil {
cacheOptions := pn.Cache.GetOptions()
cacheOptions.Compression = options
pn.Cache.UpdateOptions(cacheOptions)
}
return pn
}
// WithMonitoring 设置监控选项
func (pn *PixelNebula) WithMonitoring(options cache.MonitorOptions) *PixelNebula {
if pn.Cache != nil {
cacheOptions := pn.Cache.GetOptions()
cacheOptions.Monitoring = options
pn.Cache.UpdateOptions(cacheOptions)
// 如果启用了监控但监控器尚未创建,则创建并启动监控器
if options.Enabled && pn.Cache.Monitor == nil {
pn.Cache.Monitor = cache.NewMonitor(pn.Cache, options)
pn.Cache.Monitor.Start()
}
}
return pn
}
// WithAnimation 添加动画效果
func (pn *PixelNebula) WithAnimation(animation animation.Animation) *PixelNebula {
pn.AnimManager.AddAnimation(animation)
return pn
}
// WithRotateAnimation 添加旋转动画
func (pn *PixelNebula) WithRotateAnimation(targetID string, fromAngle, toAngle float64, duration float64, repeatCount int) *PixelNebula {
anim := animation.NewRotateAnimation(targetID, fromAngle, toAngle, duration, repeatCount)
pn.AnimManager.AddAnimation(anim)
return pn
}
// WithGradientAnimation 添加渐变动画
func (pn *PixelNebula) WithGradientAnimation(targetID string, colors []string, duration float64, repeatCount int, animate bool) *PixelNebula {
anim := animation.NewGradientAnimation(targetID, colors, duration, repeatCount, animate)
pn.AnimManager.AddAnimation(anim)
return pn
}
// WithTransformAnimation 添加变换动画
func (pn *PixelNebula) WithTransformAnimation(targetID string, transformType string, from, to string, duration float64, repeatCount int) *PixelNebula {
anim := animation.NewTransformAnimation(targetID, transformType, from, to, duration, repeatCount)
pn.AnimManager.AddAnimation(anim)
return pn
}
// WithFadeAnimation 添加淡入淡出动画
func (pn *PixelNebula) WithFadeAnimation(targetID string, from, to string, duration float64, repeatCount int) *PixelNebula {
anim := animation.NewFadeAnimation(targetID, from, to, duration, repeatCount)
pn.AnimManager.AddAnimation(anim)
return pn
}
// WithPathAnimation 添加路径动画
func (pn *PixelNebula) WithPathAnimation(targetID string, path string, duration float64, repeatCount int) *PixelNebula {
anim := animation.NewPathAnimation(targetID, path, duration, repeatCount)
pn.AnimManager.AddAnimation(anim)
return pn
}
// WithPathAnimationRotate 添加带旋转的路径动画
func (pn *PixelNebula) WithPathAnimationRotate(targetID string, path string, rotate string, duration float64, repeatCount int) *PixelNebula {
anim := animation.NewPathAnimation(targetID, path, duration, repeatCount)
anim.WithRotate(rotate)
pn.AnimManager.AddAnimation(anim)
return pn
}
// WithColorAnimation 添加颜色变换动画
func (pn *PixelNebula) WithColorAnimation(targetID string, property string, fromColor, toColor string, duration float64, repeatCount int) *PixelNebula {
anim := animation.NewColorAnimation(targetID, property, fromColor, toColor, duration, repeatCount)
pn.AnimManager.AddAnimation(anim)
return pn
}
// WithBounceAnimation 添加弹跳动画
func (pn *PixelNebula) WithBounceAnimation(targetID string, property string, from, to string, bounceCount int, duration float64, repeatCount int) *PixelNebula {
anim := animation.NewBounceAnimation(targetID, property, from, to, bounceCount, duration, repeatCount)
pn.AnimManager.AddAnimation(anim)
return pn
}
// WithWaveAnimation 添加波浪动画
func (pn *PixelNebula) WithWaveAnimation(targetID string, amplitude, frequency float64, direction string, duration float64, repeatCount int) *PixelNebula {
anim := animation.NewWaveAnimation(targetID, amplitude, frequency, direction, duration, repeatCount)
pn.AnimManager.AddAnimation(anim)
return pn
}
// WithBlinkAnimation 添加闪烁动画
func (pn *PixelNebula) WithBlinkAnimation(targetID string, minOpacity, maxOpacity float64, blinkCount int, duration float64, repeatCount int) *PixelNebula {
anim := animation.NewBlinkAnimation(targetID, minOpacity, maxOpacity, blinkCount, duration, repeatCount)
pn.AnimManager.AddAnimation(anim)
return pn
}
// WithParallelRender 启用并行渲染
func (pn *PixelNebula) WithParallelRender(enabled bool) *PixelNebula {
pn.Options.ParallelRender = enabled
return pn
}
// WithConcurrencyPool 设置并发池大小
func (pn *PixelNebula) WithConcurrencyPool(size int) *PixelNebula {
if size <= 0 {
size = runtime.NumCPU()
}
pn.Options.ConcurrencyPool = size
return pn
}
// SVGBuilder 用于处理SVG生成后的链式操作
type SVGBuilder struct {
pn *PixelNebula
svg string
id string
sansEnv bool
themeIndex int
styleIndex int
width int
height int
hasError error
}
// Generate 现在返回 SVGBuilder
func (pn *PixelNebula) Generate(id string, sansEnv bool) *SVGBuilder {
return &SVGBuilder{
pn: pn,
id: id,
sansEnv: sansEnv,
width: pn.Width,
height: pn.Height,
themeIndex: pn.Options.ThemeIndex,
styleIndex: pn.Options.StyleIndex,
}
}
// SetTheme 设置主题
func (sb *SVGBuilder) SetTheme(theme int) *SVGBuilder {
if sb.hasError != nil {
return sb
}
themeCount := sb.pn.ThemeManager.ThemeCount(sb.styleIndex)
if theme < 0 || theme >= themeCount {
log.Printf("pixelnebula: theme index range is:[0, %d), but got %d", themeCount, theme)
sb.hasError = errors.ErrInvalidTheme
return sb
}
sb.themeIndex = theme
return sb
}
// SetStyle 设置风格
// 注意:当使用WithCustomizeStyle设置自定义风格后,此方法将无法正常工作,应使用SetStyleByIndex代替
func (sb *SVGBuilder) SetStyle(style style.StyleType) *SVGBuilder {
if sb.hasError != nil {
return sb
}
index, err := sb.pn.StyleManager.GetStyleIndex(style)
if err != nil {
sb.hasError = err
return sb
}
sb.styleIndex = index
return sb
}
// SetStyleByIndex 设置风格索引
// 此方法可用于设置自定义风格的索引,特别是在使用WithCustomizeStyle后
func (sb *SVGBuilder) SetStyleByIndex(index int) *SVGBuilder {
if sb.hasError != nil {
return sb
}
themeCount := sb.pn.ThemeManager.StyleCount()
if index < 0 || index >= themeCount {
log.Printf("pixelnebula: style index range is:[0, %d), but got %d", themeCount, index)
sb.hasError = errors.ErrInvalidStyleName
return sb
}
sb.styleIndex = index
return sb
}
// SetSize 设置尺寸
func (sb *SVGBuilder) SetSize(width, height int) *SVGBuilder {
if sb.hasError != nil {
return sb
}
sb.width = width
sb.height = height
return sb
}
// SetAnimation 添加动画效果
func (sb *SVGBuilder) SetAnimation(anim animation.Animation) *SVGBuilder {
if sb.hasError != nil {
return sb
}
sb.pn.AnimManager.AddAnimation(anim)
return sb
}
// SetRotateAnimation 添加旋转动画
func (sb *SVGBuilder) SetRotateAnimation(targetID string, fromAngle, toAngle float64, duration float64, repeatCount int) *SVGBuilder {
if sb.hasError != nil {
return sb
}
anim := animation.NewRotateAnimation(targetID, fromAngle, toAngle, duration, repeatCount)
sb.pn.AnimManager.AddAnimation(anim)
return sb
}
// SetGradientAnimation 添加渐变动画
func (sb *SVGBuilder) SetGradientAnimation(targetID string, colors []string, duration float64, repeatCount int, animate bool) *SVGBuilder {
if sb.hasError != nil {
return sb
}
anim := animation.NewGradientAnimation(targetID, colors, duration, repeatCount, animate)
sb.pn.AnimManager.AddAnimation(anim)
return sb
}
// SetTransformAnimation 添加变换动画
func (sb *SVGBuilder) SetTransformAnimation(targetID string, transformType string, from, to string, duration float64, repeatCount int) *SVGBuilder {
if sb.hasError != nil {
return sb
}
anim := animation.NewTransformAnimation(targetID, transformType, from, to, duration, repeatCount)
sb.pn.AnimManager.AddAnimation(anim)
return sb
}
// SetFadeAnimation 添加淡入淡出动画
func (sb *SVGBuilder) SetFadeAnimation(targetID string, from, to string, duration float64, repeatCount int) *SVGBuilder {
if sb.hasError != nil {
return sb
}
anim := animation.NewFadeAnimation(targetID, from, to, duration, repeatCount)
sb.pn.AnimManager.AddAnimation(anim)
return sb
}
// SetPathAnimation 添加路径动画
func (sb *SVGBuilder) SetPathAnimation(targetID string, path string, duration float64, repeatCount int) *SVGBuilder {
if sb.hasError != nil {
return sb
}
anim := animation.NewPathAnimation(targetID, path, duration, repeatCount)
sb.pn.AnimManager.AddAnimation(anim)
return sb
}
// SetPathAnimationRotate 添加带旋转的路径动画
func (sb *SVGBuilder) SetPathAnimationRotate(targetID string, path string, rotate string, duration float64, repeatCount int) *SVGBuilder {
if sb.hasError != nil {
return sb
}
anim := animation.NewPathAnimation(targetID, path, duration, repeatCount)
anim.WithRotate(rotate)
sb.pn.AnimManager.AddAnimation(anim)
return sb
}
// SetColorAnimation 添加颜色变换动画
func (sb *SVGBuilder) SetColorAnimation(targetID string, property string, fromColor, toColor string, duration float64, repeatCount int) *SVGBuilder {
if sb.hasError != nil {
return sb
}
anim := animation.NewColorAnimation(targetID, property, fromColor, toColor, duration, repeatCount)
sb.pn.AnimManager.AddAnimation(anim)
return sb
}
// SetBounceAnimation 添加弹跳动画
func (sb *SVGBuilder) SetBounceAnimation(targetID string, property string, from, to string, bounceCount int, duration float64, repeatCount int) *SVGBuilder {
if sb.hasError != nil {
return sb
}
anim := animation.NewBounceAnimation(targetID, property, from, to, bounceCount, duration, repeatCount)
sb.pn.AnimManager.AddAnimation(anim)
return sb
}
// SetWaveAnimation 添加波浪动画
func (sb *SVGBuilder) SetWaveAnimation(targetID string, amplitude, frequency float64, direction string, duration float64, repeatCount int) *SVGBuilder {
if sb.hasError != nil {
return sb
}
anim := animation.NewWaveAnimation(targetID, amplitude, frequency, direction, duration, repeatCount)
sb.pn.AnimManager.AddAnimation(anim)
return sb
}
// SetBlinkAnimation 添加闪烁动画
func (sb *SVGBuilder) SetBlinkAnimation(targetID string, minOpacity, maxOpacity float64, blinkCount int, duration float64, repeatCount int) *SVGBuilder {
if sb.hasError != nil {
return sb
}
anim := animation.NewBlinkAnimation(targetID, minOpacity, maxOpacity, blinkCount, duration, repeatCount)
sb.pn.AnimManager.AddAnimation(anim)
return sb
}
// SetParallelRender 设置是否启用并行渲染
func (sb *SVGBuilder) SetParallelRender(enabled bool) *SVGBuilder {
if sb.hasError != nil {
return sb
}
sb.pn.Options.ParallelRender = enabled
return sb
}
// SetConcurrencyPool 设置并发池大小
func (sb *SVGBuilder) SetConcurrencyPool(size int) *SVGBuilder {
if sb.hasError != nil {
return sb
}
if size <= 0 {
size = runtime.NumCPU()
}
sb.pn.Options.ConcurrencyPool = size
return sb
}
// Build 生成最终的SVG
func (sb *SVGBuilder) Build() *SVGBuilder {
if sb.hasError != nil {
return sb
}
opts := &PNOptions{
ThemeIndex: sb.themeIndex,
StyleIndex: sb.styleIndex,
}
svg, err := sb.pn.generateSVG(sb.id, sb.sansEnv, opts)
if err != nil {
sb.hasError = err
return sb
}
sb.svg = svg
sb.pn.ImgData = []byte(svg)
sb.pn.Width = sb.width
sb.pn.Height = sb.height
return sb
}
// ToSVG 获取SVG字符串
func (sb *SVGBuilder) ToSVG() (string, error) {
if sb.svg == "" {
sb = sb.Build()
}
if sb.hasError != nil {
return "", sb.hasError
}
return sb.svg, nil
}
// ToBase64 获取Base64编码的SVG字符串 注意:这个设置宽高无效
func (sb *SVGBuilder) ToBase64() (string, error) {
if sb.svg == "" {
sb = sb.Build()
}
if sb.hasError != nil {
return "", sb.hasError
}
conv := converter.NewSVGConverter([]byte(sb.svg), sb.width, sb.height)
return conv.ToBase64()
}
// ToFile 将SVG代码保存到文件
func (sb *SVGBuilder) ToFile(filePath string) error {
if sb.svg == "" {
sb = sb.Build()
}
if sb.hasError != nil {
return sb.hasError
}
return os.WriteFile(filePath, []byte(sb.svg), 0644)
}
// 将原来的 GenerateSVG 重命名为 generateSVG,作为内部方法
func (pn *PixelNebula) generateSVG(id string, sansEnv bool, opts *PNOptions) (svg string, err error) {
if opts == nil {
opts = pn.Options
}
// 验证参数
if id == "" {
return "", errors.ErrAvatarIDRequired
}
// 如果启用了缓存,先尝试从缓存获取
if pn.Cache != nil {
cacheKey := cache.CacheKey{
Id: id,
SansEnv: sansEnv,
}
if opts != nil {
cacheKey.Theme = opts.ThemeIndex
cacheKey.Part = opts.StyleIndex
}
if cachedSVG, found := pn.Cache.Get(cacheKey); found {
return cachedSVG, nil
}
}
// 使用对象池获取缓冲区
hashBuf := hashBufPool.Get().(*[]byte)
defer hashBufPool.Put(hashBuf)
// 计算avatarId的哈希值 - 优化版本
pn.Hasher.Reset()
pn.Hasher.Write([]byte(id))
sum := pn.Hasher.Sum((*hashBuf)[:0])
s := hex.EncodeToString(sum)
hashStr := numberRegex.FindAllString(s, -1)
if len(hashStr) < hashLength {
return "", errors.ErrInsufficientHash
}
hashStr = hashStr[0:hashLength]
// 从对象池获取映射
p := keyMapPool.Get().(map[string][2]int)
defer func() {
// 清空并归还对象池
for k := range p {
delete(p, k)
}
keyMapPool.Put(p)
}()
// 计算各部分的键值
p[string(style.TypeEnv)] = pn.calcKey(hashStr[:2], opts)
p[string(style.TypeClo)] = pn.calcKey(hashStr[2:4], opts)
p[string(style.TypeHead)] = pn.calcKey(hashStr[4:6], opts)
p[string(style.TypeMouth)] = pn.calcKey(hashStr[6:8], opts)
p[string(style.TypeEyes)] = pn.calcKey(hashStr[8:10], opts)
p[string(style.TypeTop)] = pn.calcKey(hashStr[10:], opts)
// 获取结果映射
final := mapPool.Get().(map[string]string)
defer func() {
// 清空并归还对象池
for k := range final {
delete(final, k)
}
mapPool.Put(final)
}()
// 根据是否启用并行渲染选择处理方式
if opts.ParallelRender {
// 并行处理
var wg sync.WaitGroup
errChan := make(chan error, len(p))
// 创建互斥锁来保护 final map
var finalMux sync.Mutex
// 对每个部分启动一个 goroutine
for k, v := range p {
wg.Add(1)
go func(key string, val [2]int) {
defer wg.Done()
// 使用临时变量处理这个部分
tempResult := ""
// 获取主题颜色
themePart, err := pn.ThemeManager.GetTheme(val[0], val[1])
if err != nil {
errChan <- err
return
}
colors, ok := themePart[key]
if !ok {
errChan <- errors.ErrInvalidColor
return
}
// 获取形状SVG
shapeType := style.ShapeType(key)
svgPart, err := pn.StyleManager.GetShape(val[0], shapeType)
if err != nil {
errChan <- err
return
}
match := colorRegex.FindAllStringSubmatch(svgPart, -1)
// 从对象池获取Builder
sb := builderPool.Get().(*strings.Builder)
sb.Reset()
sb.Grow(len(svgPart) + 50) // 预分配足够的容量
lastIndex := 0
for i, m := range match {
if i < len(colors) {
// 找到完整匹配的位置
index := strings.Index(svgPart[lastIndex:], m[0]) + lastIndex
// 添加匹配前的部分
sb.WriteString(svgPart[lastIndex:index])
// 添加替换后的颜色
// 检查颜色值是否已经包含#前缀
if strings.HasPrefix(colors[i], "#") {
sb.WriteString(colors[i])
} else {
sb.WriteString("#")
sb.WriteString(colors[i])
}
sb.WriteString(";")
// 更新lastIndex
lastIndex = index + len(m[0])
}
}
// 添加剩余部分
sb.WriteString(svgPart[lastIndex:])
tempResult = sb.String()
// 归还Builder到对象池
builderPool.Put(sb)
// 使用互斥锁保护对 final map 的写入
finalMux.Lock()
final[key] = tempResult
finalMux.Unlock()
}(k, v)
}
// 等待所有部分处理完成
wg.Wait()
// 检查是否有错误
select {
case err := <-errChan:
return "", err
default:
// 没有错误,继续处理
}
} else {
// 串行处理
for k, v := range p {
if err := pn.processSVGPart(k, v, final); err != nil {
return "", err
}
}
}
// 使用对象池获取主Builder来构建最终SVG
builder := builderPool.Get().(*strings.Builder)
builder.Reset()
// 预估SVG大小,避免多次内存分配
builder.Grow(2048) // 2KB 应该足够容纳大多数SVG
// 添加SVG开始标签
builder.WriteString(pn.getSvgStart())
// 获取动画定义
animations := pn.AnimManager.GenerateSVGAnimations()
if animations != "" {
builder.WriteString(animations)
}
// 构建和处理旋转动画 - 使用对象池
rotateAnimations := make(map[string]bool)
rotateAnimationSVGs := make(map[string]string)
// 收集旋转动画
for _, anim := range pn.AnimManager.GetAnimations() {
if rotateAnim, ok := anim.(*animation.RotateAnimation); ok {
targetID := anim.GetTargetID()
rotateAnimations[targetID] = true
// 提取animateTransform部分
svgCode := rotateAnim.GenerateSVG()
if start := strings.Index(svgCode, "<animateTransform"); start != -1 {
if end := strings.Index(svgCode[start:], "/>"); end != -1 {
rotateAnimationSVGs[targetID] = svgCode[start : start+end+2]
}
}
}
}
// 处理环境
if !sansEnv {
if _, hasRotate := rotateAnimations["env"]; hasRotate {
builder.WriteString("<g style=\"transform-box: fill-box; transform-origin: center;\">\n")
builder.WriteString(final["env"])
if animSVG, ok := rotateAnimationSVGs["env"]; ok {
builder.WriteString(animSVG)
}
builder.WriteString("</g>\n")
} else {
builder.WriteString(final["env"])
}
}
// 处理其他元素
elements := []string{"head", "clo", "top", "eyes", "mouth"}
for _, elem := range elements {
if _, hasRotate := rotateAnimations[elem]; hasRotate {
builder.WriteString("<g style=\"transform-box: fill-box; transform-origin: center;\">\n")
builder.WriteString(final[elem])
if animSVG, ok := rotateAnimationSVGs[elem]; ok {
builder.WriteString(animSVG)
}
builder.WriteString("</g>\n")
} else {
builder.WriteString(final[elem])
}
}
builder.WriteString(pn.SvgEnd)
svg = builder.String()
// 将生成的SVG存储到实例中
pn.ImgData = []byte(svg)
// 归还Builder到对象池
builderPool.Put(builder)
// 如果启用了缓存,将结果存入缓存
if pn.Cache != nil {
cacheKey := cache.CacheKey{
Id: id,
SansEnv: sansEnv,
}
if opts != nil {
cacheKey.Theme = opts.ThemeIndex
cacheKey.Part = opts.StyleIndex
}
pn.Cache.Set(cacheKey, svg)
}
return svg, nil
}
// GetCacheStats 获取缓存统计信息
func (pn *PixelNebula) GetCacheStats() (size, hits, misses int, hitRate float64, enabled bool, maxSize int, expiration time.Duration, evictionType string) {
if pn.Cache == nil {
log.Println("pixelnebula: 缓存未初始化,请先调用WithCache或WithDefaultCache")
return 0, 0, 0, 0, false, 0, 0, ""
}
hits, misses, hitRate = pn.Cache.Stats()
options := pn.Cache.GetOptions()
return pn.Cache.Size(), hits, misses, hitRate, options.Enabled, options.Size, options.Expiration, options.EvictionType
}
// CacheItemInfo 缓存项信息结构体
type CacheItemInfo struct {
Key cache.CacheKey
SVG string
Compressed []byte
IsCompressed bool
CreatedAt time.Time
LastUsed time.Time
}
// GetCacheItems 获取所有缓存项
func (pn *PixelNebula) GetCacheItems() []CacheItemInfo {
var result []CacheItemInfo
if pn.Cache == nil {
log.Println("pixelnebula: 缓存未初始化,请先调用WithCache或WithDefaultCache")
return result
}
// 获取内部缓存项
items := pn.Cache.GetAllItems()
if len(items) == 0 {
log.Println("pixelnebula: 缓存中没有数据,请先生成一些SVG")
}
for key, item := range items {
cacheItem := CacheItemInfo{
Key: key,
SVG: item.SVG,
Compressed: item.Compressed,
IsCompressed: item.IsCompressed,
CreatedAt: item.CreatedAt,
LastUsed: item.LastUsed,
}
result = append(result, cacheItem)
}
return result
}
// MonitorSampleInfo 监控样本信息
type MonitorSampleInfo struct {
Timestamp time.Time
Size int
Hits int
Misses int
HitRate float64
MemoryUsage int64
}
// GetMonitorStats 获取监控统计信息
func (pn *PixelNebula) GetMonitorStats() (enabled bool, sampleInterval, adjustInterval time.Duration,
targetHitRate float64, lastAdjusted time.Time, samples []MonitorSampleInfo) {
if pn.Cache == nil {