UNPKG

2.24 kBJavaScriptView Raw
1const {EPS} = require('./constants')
2const Polygon = require('./math/Polygon3')
3const FuzzyFactory = require('./FuzzyFactory')
4
5// ////////////////////////////////////
6const FuzzyCSGFactory = function () {
7 this.vertexfactory = new FuzzyFactory(3, EPS)
8 this.planefactory = new FuzzyFactory(4, EPS)
9 this.polygonsharedfactory = {}
10}
11
12FuzzyCSGFactory.prototype = {
13 getPolygonShared: function (sourceshared) {
14 let hash = sourceshared.getHash()
15 if (hash in this.polygonsharedfactory) {
16 return this.polygonsharedfactory[hash]
17 } else {
18 this.polygonsharedfactory[hash] = sourceshared
19 return sourceshared
20 }
21 },
22
23 getVertex: function (sourcevertex) {
24 let elements = [sourcevertex.pos._x, sourcevertex.pos._y, sourcevertex.pos._z]
25 let result = this.vertexfactory.lookupOrCreate(elements, function (els) {
26 return sourcevertex
27 })
28 return result
29 },
30
31 getPlane: function (sourceplane) {
32 let elements = [sourceplane.normal._x, sourceplane.normal._y, sourceplane.normal._z, sourceplane.w]
33 let result = this.planefactory.lookupOrCreate(elements, function (els) {
34 return sourceplane
35 })
36 return result
37 },
38
39 getPolygon: function (sourcepolygon) {
40 let newplane = this.getPlane(sourcepolygon.plane)
41 let newshared = this.getPolygonShared(sourcepolygon.shared)
42 let _this = this
43 let newvertices = sourcepolygon.vertices.map(function (vertex) {
44 return _this.getVertex(vertex)
45 })
46 // two vertices that were originally very close may now have become
47 // truly identical (referring to the same Vertex object).
48 // Remove duplicate vertices:
49 let newverticesDedup = []
50 if (newvertices.length > 0) {
51 let prevvertextag = newvertices[newvertices.length - 1].getTag()
52 newvertices.forEach(function (vertex) {
53 let vertextag = vertex.getTag()
54 if (vertextag !== prevvertextag) {
55 newverticesDedup.push(vertex)
56 }
57 prevvertextag = vertextag
58 })
59 }
60 // If it's degenerate, remove all vertices:
61 if (newverticesDedup.length < 3) {
62 newverticesDedup = []
63 }
64 return new Polygon(newverticesDedup, newshared, newplane)
65 }
66}
67
68module.exports = FuzzyCSGFactory