This repository has been archived by the owner on Sep 17, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathwikihouse.rb
executable file
·2174 lines (1836 loc) · 61.6 KB
/
wikihouse.rb
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
# Public Domain (-) 2011 The WikiHouse Authors.
# See the WikiHouse UNLICENSE file for details.
# =========================
# WikiHouse SketchUp Plugin
# =========================
require 'sketchup.rb'
# ------------------------------------------------------------------------------
# Path Utilities
# ------------------------------------------------------------------------------
def get_documents_directory(home, docs)
dir = File.join home, docs
if not (File.directory?(dir) and File.writable?(dir))
home
else
dir
end
end
def get_temp_directory
temp = '.'
for dir in [ENV['TMPDIR'], ENV['TMP'], ENV['TEMP'], ENV['USERPROFILE'], '/tmp']
if dir and File.directory?(dir) and File.writable?(dir)
temp = dir
break
end
end
File.expand_path temp
end
# ------------------------------------------------------------------------------
# Some Constants
# ------------------------------------------------------------------------------
PANEL_ID_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
PANEL_ID_ALPHABET_LENGTH = PANEL_ID_ALPHABET.length
REPLY_ABORT = 3
REPLY_CANCEL = 2
REPLY_NO = 7
REPLY_OK = 1
REPLY_RETRY = 4
REPLY_YES = 6
if RUBY_PLATFORM =~ /mswin/
WIKIHOUSE_CONF_FILE = File.join ENV['APPDATA'], 'WikiHouse.conf'
WIKIHOUSE_SAVE = get_documents_directory ENV['USERPROFILE'], 'Documents'
WIKIHOUSE_MAC = false
else
WIKIHOUSE_CONF_FILE = File.join ENV['HOME'], '.wikihouse.conf'
WIKIHOUSE_SAVE = get_documents_directory ENV['HOME'], 'Documents'
WIKIHOUSE_MAC = true
end
WIKIHOUSE_DEV = false
WIKIHOUSE_HIDE = false
WIKIHOUSE_LOCAL = false
WIKIHOUSE_SHORT_CIRCUIT = false
if WIKIHOUSE_LOCAL
WIKIHOUSE_SERVER = "http://localhost:8080"
else
WIKIHOUSE_SERVER = "http://wikihouse-cc.appspot.com"
end
WIKIHOUSE_DOWNLOAD_PATH = "/library/sketchup"
WIKIHOUSE_UPLOAD_PATH = "/library/designs/add/sketchup"
WIKIHOUSE_DOWNLOAD_URL = WIKIHOUSE_SERVER + WIKIHOUSE_DOWNLOAD_PATH
WIKIHOUSE_UPLOAD_URL = WIKIHOUSE_SERVER + WIKIHOUSE_UPLOAD_PATH
WIKIHOUSE_PLUGIN_VERSION = "0.1"
WIKIHOUSE_SPEC = "0.1"
WIKIHOUSE_TEMP = get_temp_directory
WIKIHOUSE_TITLE = "WikiHouse"
WIKIHOUSE_FONT_HEIGHT = 30.mm
WIKIHOUSE_PANEL_PADDING = 25.mm / 2
WIKIHOUSE_SHEET_HEIGHT = 1200.mm
WIKIHOUSE_SHEET_MARGIN = 15.mm - WIKIHOUSE_PANEL_PADDING
WIKIHOUSE_SHEET_WIDTH = 2400.mm
WIKIHOUSE_SHEET_INNER_HEIGHT = WIKIHOUSE_SHEET_HEIGHT - (2 * WIKIHOUSE_SHEET_MARGIN)
WIKIHOUSE_SHEET_INNER_WIDTH = WIKIHOUSE_SHEET_WIDTH - (2 * WIKIHOUSE_SHEET_MARGIN)
WIKIHOUSE_DIMENSIONS = [
WIKIHOUSE_SHEET_HEIGHT,
WIKIHOUSE_SHEET_WIDTH,
WIKIHOUSE_SHEET_INNER_HEIGHT,
WIKIHOUSE_SHEET_INNER_WIDTH,
WIKIHOUSE_SHEET_MARGIN,
WIKIHOUSE_PANEL_PADDING,
WIKIHOUSE_FONT_HEIGHT
]
# ------------------------------------------------------------------------------
# Utility Functions
# ------------------------------------------------------------------------------
def gen_status_msg(msg)
return [
msg + " .",
msg + " ..",
msg + " ...",
msg + " ....",
msg + " .....",
]
end
def get_wikihouse_thumbnail(model, view, suffix)
filename = File.join WIKIHOUSE_TEMP, "#{model.guid}-#{suffix}.png"
opts = {
:antialias => true,
:compression => 0.8,
:filename => filename,
:height => [view.vpheight, 1600].min,
:transparent => true,
:width => [view.vpwidth, 1600].min
}
view.write_image opts
data = File.open(filename, 'rb') do |io|
io.read
end
File.delete filename
data
end
def set_dom_value(dialog, id, value)
if value.length > 2097152
dialog.execute_script "WIKIHOUSE_DATA = [#{value[0...2097152].inspect}];"
start, stop = 2097152, (2097152+2097152)
idx = 1
while 1
segment = value[start...stop]
if not segment
break
end
dialog.execute_script "WIKIHOUSE_DATA[#{idx}] = #{segment.inspect};"
idx += 1
start = stop
stop = stop + 2097152
end
dialog.execute_script "document.getElementById('#{id}').value = WIKIHOUSE_DATA.join('');"
else
dialog.execute_script "document.getElementById('#{id}').value = #{value.inspect};"
end
end
def show_wikihouse_error(msg)
UI.messagebox "!! ERROR !!\n\n#{msg}"
end
# ------------------------------------------------------------------------------
# Centroid Calculation
# ------------------------------------------------------------------------------
def get_face_center(face)
# First, triangulate the polygon.
mesh = face.mesh
# Initialise aggregation variables.
idx = 0
xs = []
ys = []
areas = []
# For each triangle, calculate the surface area and center of mass.
for i in 0...mesh.count_polygons
a, b, c = mesh.polygon_points_at i+1
ax, ay, _ = a.to_a
bx, by, _ = b.to_a
cx, cy, _ = c.to_a
dax = ax - bx
dbx = bx - cx
dcx = cx - ax
day = ay - by
dby = by - cy
dcy = cy - ay
la = Math.sqrt((dax * dax) + (day * day))
lb = Math.sqrt((dbx * dbx) + (dby * dby))
lc = Math.sqrt((dcx * dcx) + (dcy * dcy))
max = (ax + bx) / 2
mbx = (bx + cx) / 2
mcx = (cx + ax) / 2
may = (ay + by) / 2
mby = (by + cy) / 2
mcy = (cy + ay) / 2
px = ((max * la) + (mbx * lb) + (mcx * lc)) / (la + lb + lc)
py = ((may * la) + (mby * lb) + (mcy * lc)) / (la + lb + lc)
# angle = (Math.acos((la * la) + (lb * lb) - (lc * lc)) * Math::PI) / (360 * la * lb)
# area = (la * lb * Math.sin(angle)) / 2
s1, s2, s3 = [la, lb, lc].sort.reverse
top = (s1 + (s2 + s3)) * (s3 - (s1 - s2)) * (s3 + (s1 - s2)) * (s1 + (s2 - s3))
# TODO(tav): Read http://www.eecs.berkeley.edu/~wkahan/Triangle.pdf and
# figure out why this fails on triangles with small angles.
if top < 0
puts "Failed surface area calculation"
next
end
area = Math.sqrt(top) / 4
xs[idx] = px
ys[idx] = py
areas[idx] = area
idx += 1
end
# Calculate the total surface area.
total = areas.inject(0) { |t, a| a + t }
# Calculate the weighted center points.
px, py = 0, 0
for i in 0...xs.length
x, y, a = xs[i], ys[i], areas[i]
px += x * a
py += y * a
end
# Calculate the center of mass.
px = px / total
py = py / total
[px, py]
end
# ------------------------------------------------------------------------------
# Status Messages
# ------------------------------------------------------------------------------
WIKIHOUSE_DETECTION_STATUS = gen_status_msg "Detecting matching faces"
WIKIHOUSE_DXF_STATUS = gen_status_msg "Generating DXF output"
WIKIHOUSE_LAYOUT_STATUS = gen_status_msg "Nesting panels for layout"
WIKIHOUSE_PANEL_STATUS = gen_status_msg "Generating panel data"
WIKIHOUSE_SVG_STATUS = gen_status_msg "Generating SVG output"
# ------------------------------------------------------------------------------
# Load Handler
# ------------------------------------------------------------------------------
class WikiHouseLoader
attr_accessor :cancel, :error
def initialize(name)
@cancel = false
@error = nil
@name = name
end
def cancelled?
@cancel
end
def onFailure(error)
@error = error
Sketchup.set_status_text ''
end
def onPercentChange(p)
Sketchup.set_status_text "LOADING #{name}: #{p.to_i}%"
end
def onSuccess
Sketchup.set_status_text ''
end
end
# ------------------------------------------------------------------------------
# App Observer
# ------------------------------------------------------------------------------
class WikiHouseAppObserver < Sketchup::AppObserver
def onNewModel(model)
end
# TODO(tav): This doesn't seem to be getting called.
def onQuit
if WIKIHOUSE_DOWNLOADS.length > 0
show_wikihouse_error "Aborting downloads from #{WIKIHOUSE_TITLE}"
end
if WIKIHOUSE_UPLOADS.length > 0
show_wikihouse_error "Aborting uploads to #{WIKIHOUSE_TITLE}"
end
end
end
# ------------------------------------------------------------------------------
# Dummy Group
# ------------------------------------------------------------------------------
class WikiHouseDummyGroup
attr_reader :name
def initialize
@name = "Ungrouped Objects"
end
end
WIKIHOUSE_DUMMY_GROUP = WikiHouseDummyGroup.new
# ------------------------------------------------------------------------------
# DXF Writer
# ------------------------------------------------------------------------------
class WikiHouseDXF
def initialize(layout)
end
def generate
""
end
end
# ------------------------------------------------------------------------------
# SVG Writer
# ------------------------------------------------------------------------------
class WikiHouseSVG
def initialize(layout, scale)
@layout = layout
@scale = scale
end
def generate
layout = @layout
scale = @scale
sheet_height, sheet_width, inner_height, inner_width, margin = layout.dimensions
sheets = layout.sheets
count = sheets.length
scaled_height = scale * sheet_height
scaled_width = scale * sheet_width
total_height = scale * ((count * (sheet_height + (12 * margin))) + (margin * 10))
total_width = scale * (sheet_width + (margin * 2))
svg = []
svg << <<-HEADER.gsub(/^ {6}/, '')
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg height="#{total_height}" version="1.1"
viewBox="0 0 #{total_width} #{total_height}" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" style="background-color: #ffffff;">
<desc>#{WIKIHOUSE_TITLE} Cutting Sheets</desc>"
<!-- linkstart -->
<g visibility="hidden" pointer-events="all">
<rect x="0" y="0" width="100%" height="100%" fill="none" />
</g>
HEADER
loop_count = 0
for s in 0...count
sheet = sheets[s]
base_x = scale * margin
base_y = scale * ((s * (sheet_height + (12 * margin))) + (margin * 9))
svg << "<rect x=\"#{base_x}\" y=\"#{base_y}\" width=\"#{scaled_width}\" height=\"#{scaled_height}\" fill=\"none\" stroke=\"rgb(210, 210, 210)\" stroke-width=\"1\" />"
base_x += scale * margin
base_y += scale * margin
sheet.each do |loops, circles, outer_mapped, centroid, label|
Sketchup.set_status_text WIKIHOUSE_SVG_STATUS[(loop_count/5) % 5]
loop_count += 1
svg << '<g fill="none" stroke="rgb(255, 255, 255)" stroke-width="1">'
for i in 0...loops.length
circle = circles[i]
if circle
center, radius = circle
x = (scale * center.x) + base_x
y = (scale * center.y) + base_y
radius = scale * radius
svg << <<-CIRCLE.gsub(/^ {14}/, '')
<circle cx="#{x}" cy="#{y}" r="#{radius}"
stroke="rgb(51, 51, 51)" stroke-width="2" fill="none" />
CIRCLE
else
loop = loops[i]
first = loop.shift
path = []
path << "M #{(scale * first.x) + base_x} #{(scale * first.y) + base_y}"
loop.each do |point|
path << "L #{(scale * point.x) + base_x} #{(scale * point.y) + base_y}"
end
path << "Z"
svg << <<-PATH.gsub(/^ {14}/, '')
<path d="#{path.join ' '}" stroke="rgb(0, 0, 0)" stroke-width="2" fill="none" />
PATH
end
end
if label and label != ""
svg << <<-LABEL.gsub(/^ {12}/, '')
<text x="#{(scale * centroid.x) + base_x}" y="#{(scale * centroid.y) + base_y}" style="font-size: 5mm; stroke: rgb(255, 0, 0); fill: rgb(255, 0, 0); text-family: monospace">#{label}</text>
LABEL
end
svg << '</g>'
end
end
svg << '<!-- linkend -->'
svg << '</svg>'
svg.join "\n"
end
end
# ------------------------------------------------------------------------------
# Layout Engine
# ------------------------------------------------------------------------------
class WikiHouseLayoutEngine
attr_accessor :sheets
attr_reader :dimensions
def initialize(panels, root, dimensions)
@dimensions = dimensions
@sheets = sheets = []
# Set local variables to save repeated lookups.
sheet_height, sheet_width, inner_height, inner_width,
sheet_margin, panel_padding, font_height = dimensions
# Filter out the singletons from the other panels.
singletons = panels.select { |panel| panel.singleton }
panels = panels.select { |panel| !panel.singleton }
# Loop through the panels.
panels.map! do |panel|
# Get padding related info.
no_padding = panel.no_padding
# Get the bounding box.
min = panel.min
max = panel.max
min_x, min_y = min.x, min.y
max_x, max_y = max.x, max.y
# Set a flag to indicate clipped panels.
clipped = false
# Determine if the potential savings exceeds the hard-coded threshold. If
# so, see if we can generate an outline with rectangular areas clipped
# from each corner.
if (panel.bounds_area - panel.shell_area) > 50
# puts (panel.bounds_area - panel.shell_area)
end
# Otherwise, treat the bounding box as the outline.
if not clipped
# Define the inner outline.
inner = [[min_x, min_y, 0], [max_x, min_y, 0], [max_x, max_y, 0], [min_x, max_y, 0]]
# Add padding around each side.
if not no_padding
min_x -= panel_padding
min_y -= panel_padding
max_x += panel_padding
max_y += panel_padding
elsif no_padding == "w"
min_y -= panel_padding
max_y += panel_padding
elsif no_padding == "h"
min_x -= panel_padding
max_x += panel_padding
end
# Calculate the surface area that will be occupied by this panel.
width = max_x - min_x
height = max_y - min_y
area = width * height
# Define the padded outer outline.
# outline = [[min_x, max_y, 0], [max_x, max_y, 0], [max_x, min_y, 0], [min_x, min_y, 0]]
outer = [[min_x, min_y, 0], [max_x, min_y, 0], [max_x, max_y, 0], [min_x, max_y, 0]]
outlines = [[nil, inner, outer]]
# See if the panel can be rotated, if so add the transformation.
if not no_padding
if (inner_width > height) and (inner_height > width)
# inner = [inner[3], inner[0], inner[1], inner[2]]
# outer = [outer[3], outer[0], outer[1], outer[2]]
outlines << [90.degrees, inner, outer]
outlines << [270.degrees, inner, outer]
end
outlines << [180.degrees, inner, outer]
end
end
# Save the generated data.
[panel, outlines, area, panel.labels.dup]
end
# Sort the panels by surface area.
panels = panels.sort_by { |data| data[2] }.reverse
# Generate new groups to hold sheet faces.
inner_group = root.add_group
inner_faces = inner_group.entities
outer_group = root.add_group
outer_faces = outer_group.entities
temp_group = root.add_group
temp_faces = temp_group.entities
total_area = inner_width * inner_height
# Initialise the loop counter.
loop_count = 0
# Make local certain global constants.
outside = Sketchup::Face::PointOutside
# panels = panels[-10...-1]
# panels = panels[-5...-1]
c = 0
# Do the optimising layout.
while 1
# Create a fresh sheet.
sheet = []
available_area = total_area
idx = 0
placed_i = []
placed_o = []
while available_area > 0
Sketchup.set_status_text WIKIHOUSE_LAYOUT_STATUS[(loop_count/20) % 5]
loop_count += 1
panel_data = panels[idx]
if not panel_data
break
end
panel, outlines, panel_area, labels = panel_data
if panel_area > available_area
idx += 1
next
end
match = true
t = nil
used = nil
# If this is the first item, do the cheap placement check.
if sheet.length == 0
transform, inner, outer = outlines[0]
point = outer[0]
translate = Geom::Transformation.translation [-point[0], -point[1], 0]
inner.each do |point|
point = translate * point
if (point.x > inner_width) or (-point.y > inner_height)
p (point.x - inner_width)
p (point.y - inner_height)
match = false
break
end
end
if not match
puts "Error: couldn't place panel onto an empty sheet"
panels.delete_at idx
next
end
t = translate
used = [inner, outer]
else
# Otherwise, loop around the already placed panel regions and see if
# the outline can be placed next to it.
match = false
placed_o.each do |face|
# Loop through the vertices of the available region.
face.outer_loop.vertices.each do |vertex|
origin = vertex.position
# Loop through each outline.
outlines.each do |angle, inner, outer|
# Loop through every vertex of the outline, starting from the
# top left.
p_idx = -1
all_match = true
while 1
p0 = outer[p_idx]
if not p0
break
end
transform = Geom::Transformation.translation ([origin.x - p0[0], origin.y - p0[1], 0])
if angle
transform = transform * Geom::Transformation.rotation(origin, Z_AXIS, angle)
end
# Check every point to see if it's within the available region.
all_match = true
inner.each do |point|
point = transform * point
px, py = point.x, point.y
if (px < 0) or (py < 0) or (px > inner_width) or (py > inner_height)
all_match = false
break
end
placed_o.each do |placement|
if placement.classify_point(point) != outside
all_match = false
break
end
end
if not all_match
break
end
end
# If the vertices don't overlap, check that the edges don't
# intersect.
if all_match
# TODO(tav): Optimise with a sweep line algorithm variant:
# http://en.wikipedia.org/wiki/Sweep_line_algorithm
outer_mapped = outer.map { |point| transform * point }
for i in 0...outer.length
p1 = outer_mapped[i]
p2 = outer_mapped[i+1]
if not p2
p2 = outer_mapped[0]
end
p1x, p1y = p1.x, p1.y
p2x, p2y = p2.x, p2.y
s1 = p2x - p1x
s2 = p2y - p1y
edge = [p1, [s1, s2, 0]]
edge_length = Math.sqrt((s1 * s1) + (s2 * s2))
placed_i.each do |placement|
placement.edges.each do |other_edge|
intersection = Geom.intersect_line_line edge, other_edge.line
if intersection
p3x, p3y = intersection.x, intersection.y
s1 = p3x - p1x
s2 = p3y - p1y
length = Math.sqrt((s1 * s1) + (s2 * s2))
if length > edge_length
next
end
s1 = p3x - p2x
s2 = p3y - p2y
length = Math.sqrt((s1 * s1) + (s2 * s2))
if length > edge_length
next
end
other_edge_length = other_edge.length
p4, p5 = other_edge.start.position, other_edge.end.position
s1 = p3x - p4.x
s2 = p3y - p4.y
length = Math.sqrt((s1 * s1) + (s2 * s2))
if length > other_edge_length
next
end
s1 = p3x - p5.x
s2 = p3y - p5.y
length = Math.sqrt((s1 * s1) + (s2 * s2))
if length > other_edge_length
next
end
all_match = false
break
end
end
if not all_match
break
end
end
if not all_match
break
end
end
end
if all_match
match = true
t = transform
used = [inner, outer]
end
p_idx -= 1
if match
break
end
end
if match
break
end
end
if match
break
end
end
if match
break
end
end
end
if match
available_area -= panel_area
inner_faces.add_face(used[0].map { |p| t * p })
outer_faces.add_face(used[1].map { |p| t * p })
placed_i = inner_faces.select { |e| e.typename == "Face" }
placed_o = outer_faces.select { |e| e.typename == "Face" }
# Generate the new loop vertices.
loops = panel.loops.map do |loop|
loop.map do |point|
t * point
end
end
# Generate the new circle data.
circles = panel.circles.map do |circle|
if circle
center = t * circle[0]
[center, circle[1]]
else
nil
end
end
# Generate the new centroid.
centroid = t * panel.centroid
# Get the label.
label = labels.pop
# If this was the last label, remove the panel.
if labels.length == 0
panels.delete_at idx
end
outer_mapped = outer.map { |p| t * p }
# Append the generated data to the current sheet.
sheet << [loops, circles, outer_mapped, centroid, label]
c += 1
else
# We do not have a match, try the next panel.
idx += 1
end
end
# If no panels could be fitted, break so as to avoid an infinite loop.
if sheet.length == 0
break
end
# Add the sheet to the collection.
sheets << sheet
# If there are no more panels remaining, exit the loop.
if panels.length == 0
break
end
# Wipe the generated entities.
inner_faces.clear!
outer_faces.clear!
end
# Delete the generated sheet group.
root.erase_entities [inner_group, outer_group]
end
end
# ------------------------------------------------------------------------------
# Panel
# ------------------------------------------------------------------------------
class WikiHousePanel
attr_accessor :area, :centroid, :circles, :labels, :loops, :max, :min
attr_reader :bounds_area, :error, :no_padding, :shell_area, :singleton
def initialize(root, face, transform, labels, limits)
# Initalise some of the object attributes.
@error = nil
@labels = labels
@no_padding = false
@singleton = false
# Initialise a variable to hold temporarily generated entities.
to_delete = []
# Create a new face with the vertices transformed if the transformed areas
# do not match.
if (face.area - face.area(transform)).abs > 0.1
group_entity = root.add_group
to_delete << group_entity
group = group_entity.entities
tface = group.add_face(face.outer_loop.vertices.map {|v| transform * v.position })
face.loops.each do |loop|
if not loop.outer?
hole = group.add_face(loop.vertices.map {|v| transform * v.position })
hole.erase! if hole.valid?
end
end
face = tface
end
# Save the total surface area of the face.
total_area = face.area
# Find the normal to the face.
normal = face.normal
y_axis = normal.axes[1]
# See if the face is parallel to any of the base axes.
if normal.parallel? X_AXIS
x, y = 1, 2
elsif normal.parallel? Y_AXIS
x, y = 0, 2
elsif normal.parallel? Z_AXIS
x, y = 0, 1
else
x, y = nil, nil
end
# Initialise the ``loops`` variable.
loops = []
# Initialise a reference point for transforming slanted faces.
base = face.outer_loop.vertices[0].position
# Loop through the edges and convert the face into a 2D polygon -- ensuring
# that we are traversing the edges in the right order.
face.loops.each do |loop|
newloop = []
if loop.outer?
loops.insert 0, newloop
else
loops << newloop
end
edgeuse = first = loop.edgeuses[0]
virgin = true
prev = nil
while 1
edge = edgeuse.edge
if virgin
start = edge.start
stop = edge.end
next_edge = edgeuse.next.edge
next_start = next_edge.start
next_stop = next_edge.end
if (start == next_start) or (start == next_stop)
stop, start = start, stop
elsif not ((stop == next_start) or (stop == next_stop))
@error = "Unexpected edge connection"
return
end
virgin = nil
else
start = edge.start
stop = edge.end
if stop == prev
stop, start = start, stop
elsif not start == prev
@error = "Unexpected edge connection"
return
end
end
if x
# If the face is parallel to a base axis, use the cheap conversion
# route.
point = start.position.to_a
newloop << [point[x], point[y], 0]
else
# Otherwise, handle the case where the face is angled at a slope by
# realigning edges relative to the origin and rotating them according
# to their angle to the y-axis.
point = start.position
edge = Geom::Vector3d.new(point.x - base.x, point.y - base.y, point.z - base.z)
if not edge.valid?
newloop << [base.x, base.y, 0]
else
if edge.samedirection? y_axis
angle = 0
elsif edge.parallel? y_axis
angle = Math::PI
else
angle = edge.angle_between y_axis
if not edge.cross(y_axis).samedirection? normal
angle = -angle
end
end
rotate = Geom::Transformation.rotation ORIGIN, Z_AXIS, angle
newedge = rotate * Geom::Vector3d.new(edge.length, 0, 0)
newloop << [base.x + newedge.x, base.y + newedge.y, 0]
end
end
edgeuse = edgeuse.next
if edgeuse == first
break
end
prev = stop
end
end
# Initialise some more meta variables.
areas = []
circles = []
cxs, cys = [], []
intersections = []
outer_loop = true
# Go through the various loops calculating centroids and intersection points
# of potential curves.
loops.each do |loop|
idx = 0
intersect_points = []
area = 0
cx, cy = 0, 0
while 1
# Get the next three points on the loop.
p1, p2, p3 = loop[idx...idx+3]
if not p3
if not p1
break
end
if not p2
# Loop around to the first edge.
p2 = loop[0]
p3 = loop[1]
else
# Loop around to the first point.
p3 = loop[0]
end
end
# Construct the edge vectors.
edge1 = Geom::Vector3d.new(p2.x - p1.x, p2.y - p1.y, p2.z - p1.z)
edge2 = Geom::Vector3d.new(p3.x - p2.x, p3.y - p2.y, p3.z - p2.z)
intersect = nil
if not edge1.parallel? edge2
# Find the perpendicular vectors.
cross = edge1.cross edge2
vec1 = edge1.cross cross
vec2 = edge2.cross cross
# Find the midpoints.
mid1 = Geom.linear_combination 0.5, p1, 0.5, p2
mid2 = Geom.linear_combination 0.5, p2, 0.5, p3
# Try finding an intersection.
line1 = [mid1, vec1]
line2 = [mid2, vec2]
intersect = Geom.intersect_line_line line1, line2
# If no intersection, try finding one in the other direction.
if not intersect
vec1.reverse!
vec2.reverse!
intersect = Geom.intersect_line_line line1, line2
end
end
intersect_points << intersect
if p3
x1, y1 = p1.x, p1.y