MeshToSolidTool.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * MeshToSolidTool.js
  3. *
  4. * @author realor
  5. */
  6. import { Tool } from './Tool.js'
  7. import { Selection } from '../utils/Selection.js'
  8. import { ObjectUtils } from '../utils/ObjectUtils.js'
  9. import { Solid } from '../core/Solid.js'
  10. import * as THREE from '../lib/three.module.js'
  11. class MeshToSolidTool extends Tool {
  12. constructor(application, options) {
  13. super(application)
  14. this.name = 'mesh_to_solid'
  15. this.label = 'tool.mesh_to_solid.label'
  16. this.help = 'tool.mesh_to_solid.help'
  17. this.className = 'mesh_to_solid'
  18. this.setOptions(options)
  19. this.immediate = true
  20. }
  21. execute() {
  22. const application = this.application
  23. const roots = application.selection.roots
  24. const newRoots = this.convert(roots)
  25. application.selection.set(...newRoots)
  26. }
  27. convert(roots) {
  28. const replacements = new Map()
  29. const application = this.application
  30. const parents = new Selection()
  31. for (let root of roots) {
  32. parents.add(root.parent)
  33. this.traverse(root, replacements)
  34. }
  35. application.baseObject.traverse(object => {
  36. if (object.builder) {
  37. let updated = object.builder.updateReferences(object, ref => replacements.get(ref) || null)
  38. if (updated) {
  39. object.needsRebuild = true
  40. }
  41. }
  42. })
  43. const changed = parents.roots
  44. application.notifyObjectsChanged(changed, this, 'structureChanged')
  45. return roots.map(object => replacements.get(object) || object)
  46. }
  47. traverse(object, replacements) {
  48. if (object instanceof THREE.Mesh) {
  49. let mesh = object
  50. let solid = this.meshToSolid(mesh)
  51. replacements.set(mesh, solid)
  52. } else {
  53. let children = object.children
  54. for (let child of children) {
  55. this.traverse(child, replacements)
  56. }
  57. }
  58. }
  59. meshToSolid(mesh) {
  60. const parent = mesh.parent
  61. const parentIndex = parent.children.indexOf(mesh)
  62. let solid = new Solid()
  63. solid.updateGeometry(mesh.geometry, true)
  64. parent.children[parentIndex] = solid
  65. solid.name = mesh.name
  66. solid.userData = mesh.userData
  67. solid.visible = mesh.visible
  68. solid.parent = parent
  69. if (mesh.material) solid.material = mesh.material
  70. mesh.matrix.decompose(solid.position, solid.rotation, solid.scale)
  71. solid.updateMatrix()
  72. mesh.parent = null
  73. ObjectUtils.dispose(mesh)
  74. return solid
  75. }
  76. }
  77. export { MeshToSolidTool }