workbenchEditor.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. import * as React from "react";
  2. import { GlobalState } from './globalState';
  3. import { NodeListComponent } from './components/nodeList/nodeListComponent';
  4. import { PropertyTabComponent } from './components/propertyTab/propertyTabComponent';
  5. import { Portal } from './portal';
  6. import { LogComponent, LogEntry } from './components/log/logComponent';
  7. import { DataStorage } from 'babylonjs/Misc/dataStorage';
  8. import { Nullable } from 'babylonjs/types';
  9. import { MessageDialogComponent } from './sharedComponents/messageDialog';
  10. import { BlockTools } from './blockTools';
  11. import { IEditorData } from './nodeLocationInfo';
  12. import { WorkbenchComponent } from './diagram/workbench';
  13. import { GUINode } from './diagram/guiNode';
  14. import { IInspectorOptions } from "babylonjs/Debug/debugLayer";
  15. import { _TypeStore } from 'babylonjs/Misc/typeStore';
  16. require("./main.scss");
  17. interface IGraphEditorProps {
  18. globalState: GlobalState;
  19. }
  20. interface IGraphEditorState {
  21. showPreviewPopUp: boolean;
  22. };
  23. interface IInternalPreviewAreaOptions extends IInspectorOptions {
  24. popup: boolean;
  25. original: boolean;
  26. explorerWidth?: string;
  27. inspectorWidth?: string;
  28. embedHostWidth?: string;
  29. }
  30. export class WorkbenchEditor extends React.Component<IGraphEditorProps, IGraphEditorState> {
  31. private _workbenchCanvas: WorkbenchComponent;
  32. private _startX: number;
  33. private _moveInProgress: boolean;
  34. private _leftWidth = DataStorage.ReadNumber("LeftWidth", 200);
  35. private _rightWidth = DataStorage.ReadNumber("RightWidth", 300);
  36. private _blocks = new Array<BABYLON.GUI.Container | BABYLON.GUI.Control>();
  37. private _onWidgetKeyUpPointer: any;
  38. private _previewHost: Nullable<HTMLElement>;
  39. private _popUpWindow: Window;
  40. /**
  41. * Creates a node and recursivly creates its parent nodes from it's input
  42. * @param block
  43. */
  44. public createNodeFromObject(block: BABYLON.GUI.Control, recursion = true) {
  45. if (this._blocks.indexOf(block) !== -1) {
  46. return this._workbenchCanvas.nodes.filter(n => n.guiNode === block)[0];
  47. }
  48. this._blocks.push(block);
  49. // Graph
  50. const node = null;// this._workbenchCanvas.appendBlock(block);
  51. return node;
  52. }
  53. componentDidMount() {
  54. if (this.props.globalState.hostDocument) {
  55. this._workbenchCanvas = (this.refs["graphCanvas"] as WorkbenchComponent);
  56. // this._previewManager = new PreviewManager(this.props.globalState.hostDocument.getElementById("preview-canvas") as HTMLCanvasElement, this.props.globalState);
  57. }
  58. if (navigator.userAgent.indexOf("Mobile") !== -1) {
  59. ((this.props.globalState.hostDocument || document).querySelector(".blocker") as HTMLElement).style.visibility = "visible";
  60. }
  61. }
  62. componentWillUnmount() {
  63. if (this.props.globalState.hostDocument) {
  64. this.props.globalState.hostDocument!.removeEventListener("keyup", this._onWidgetKeyUpPointer, false);
  65. }
  66. }
  67. constructor(props: IGraphEditorProps) {
  68. super(props);
  69. this.state = {
  70. showPreviewPopUp: false
  71. };
  72. this.props.globalState.onRebuildRequiredObservable.add(() => {
  73. });
  74. this.props.globalState.onResetRequiredObservable.add(() => {
  75. });
  76. this.props.globalState.onImportFrameObservable.add((source: any) => {
  77. /*const frameData = source.editorData.frames[0];
  78. // create new graph nodes for only blocks from frame (last blocks added)
  79. this.props.globalState.nodeMaterial.attachedBlocks.slice(-(frameData.blocks.length)).forEach((block: NodeMaterialBlock) => {
  80. this.createNodeFromObject();
  81. });
  82. this.reOrganize(this.props.globalState.nodeMaterial.editorData, true);*/
  83. })
  84. this.props.globalState.onZoomToFitRequiredObservable.add(() => {
  85. this.zoomToFit();
  86. });
  87. this.props.globalState.onReOrganizedRequiredObservable.add(() => {
  88. this.reOrganize();
  89. });
  90. this.props.globalState.hostDocument!.addEventListener("keydown", evt => {
  91. if ((evt.keyCode === 46 || evt.keyCode === 8) && !this.props.globalState.blockKeyboardEvents) { // Delete
  92. let selectedItems = this._workbenchCanvas.selectedGuiNodes;
  93. for (var selectedItem of selectedItems) {
  94. selectedItem.dispose();
  95. //let targetBlock = selectedItem.block;
  96. //this.props.globalState.nodeMaterial!.removeBlock(targetBlock);
  97. //let blockIndex = this._blocks.indexOf(targetBlock);
  98. //if (blockIndex > -1) {
  99. // this._blocks.splice(blockIndex, 1);
  100. //}
  101. }
  102. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  103. this.props.globalState.onRebuildRequiredObservable.notifyObservers();
  104. return;
  105. }
  106. if (!evt.ctrlKey || this.props.globalState.blockKeyboardEvents) {
  107. return;
  108. }
  109. if (evt.key === "c") { // Copy
  110. let selectedItems = this._workbenchCanvas.selectedGuiNodes;
  111. if (!selectedItems.length) {
  112. return;
  113. }
  114. let selectedItem = selectedItems[0] as GUINode;
  115. if (!selectedItem.guiNode) {
  116. return;
  117. }
  118. } else if (evt.key === "v") { // Paste
  119. //const rootElement = this.props.globalState.hostDocument!.querySelector(".diagram-container") as HTMLDivElement;
  120. //const zoomLevel = this._workbenchCanvas.zoom;
  121. //let currentY = (this._mouseLocationY - rootElement.offsetTop - this._workbenchCanvas.y - 20) / zoomLevel;
  122. }
  123. }, false);
  124. }
  125. pasteSelection(copiedNodes: GUINode[], currentX: number, currentY: number, selectNew = false) {
  126. //let originalNode: Nullable<GUINode> = null;
  127. let newNodes:GUINode[] = [];
  128. // Copy to prevent recursive side effects while creating nodes.
  129. copiedNodes = copiedNodes.slice();
  130. // Cancel selection
  131. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  132. // Create new nodes
  133. for (var node of copiedNodes) {
  134. let block = node.guiNode;
  135. if (!block) {
  136. continue;
  137. }
  138. let clone = null;//block.clone(this.props.globalState.nodeMaterial.getScene());
  139. if (!clone) {
  140. return;
  141. }
  142. //let newNode = this.createNodeFromObject(clone, false);
  143. /*let x = 0;
  144. let y = 0;
  145. if (originalNode) {
  146. x = currentX + node.x - originalNode.x;
  147. y = currentY + node.y - originalNode.y;
  148. } else {
  149. originalNode = node;
  150. x = currentX;
  151. y = currentY;
  152. }*/
  153. /*newNode.x = x;
  154. newNode.y = y;
  155. newNode.cleanAccumulation();
  156. newNodes.push(newNode);
  157. if (selectNew) {
  158. this.props.globalState.onSelectionChangedObservable.notifyObservers(newNode);
  159. }*/
  160. }
  161. return newNodes;
  162. }
  163. zoomToFit() {
  164. this._workbenchCanvas.zoomToFit();
  165. }
  166. buildMaterial() {
  167. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry("Node material build successful", false));
  168. this.props.globalState.onBuiltObservable.notifyObservers();
  169. }
  170. showWaitScreen() {
  171. this.props.globalState.hostDocument.querySelector(".wait-screen")?.classList.remove("hidden");
  172. }
  173. hideWaitScreen() {
  174. this.props.globalState.hostDocument.querySelector(".wait-screen")?.classList.add("hidden");
  175. }
  176. reOrganize(editorData: Nullable<IEditorData> = null, isImportingAFrame = false) {
  177. this.showWaitScreen();
  178. this._workbenchCanvas._isLoading = true; // Will help loading large graphes
  179. setTimeout(() => {
  180. if (!editorData || !editorData.locations) {
  181. this._workbenchCanvas.distributeGraph();
  182. } else {
  183. // Locations
  184. for (var location of editorData.locations) {
  185. for (var node of this._workbenchCanvas.nodes) {
  186. if (node.guiNode && node.guiNode.uniqueId === location.blockId) {
  187. node.x = location.x;
  188. node.y = location.y;
  189. node.cleanAccumulation();
  190. break;
  191. }
  192. }
  193. }
  194. if (!isImportingAFrame){
  195. this._workbenchCanvas.processEditorData(editorData);
  196. }
  197. }
  198. this._workbenchCanvas._isLoading = false;
  199. for (var node of this._workbenchCanvas.nodes) {
  200. }
  201. this.hideWaitScreen();
  202. });
  203. }
  204. onPointerDown(evt: React.PointerEvent<HTMLDivElement>) {
  205. this._startX = evt.clientX;
  206. this._moveInProgress = true;
  207. evt.currentTarget.setPointerCapture(evt.pointerId);
  208. }
  209. onPointerUp(evt: React.PointerEvent<HTMLDivElement>) {
  210. this._moveInProgress = false;
  211. evt.currentTarget.releasePointerCapture(evt.pointerId);
  212. }
  213. resizeColumns(evt: React.PointerEvent<HTMLDivElement>, forLeft = true) {
  214. if (!this._moveInProgress) {
  215. return;
  216. }
  217. const deltaX = evt.clientX - this._startX;
  218. const rootElement = evt.currentTarget.ownerDocument!.getElementById("node-editor-graph-root") as HTMLDivElement;
  219. if (forLeft) {
  220. this._leftWidth += deltaX;
  221. this._leftWidth = Math.max(150, Math.min(400, this._leftWidth));
  222. DataStorage.WriteNumber("LeftWidth", this._leftWidth);
  223. } else {
  224. this._rightWidth -= deltaX;
  225. this._rightWidth = Math.max(250, Math.min(500, this._rightWidth));
  226. DataStorage.WriteNumber("RightWidth", this._rightWidth);
  227. rootElement.ownerDocument!.getElementById("preview")!.style.height = this._rightWidth + "px";
  228. }
  229. rootElement.style.gridTemplateColumns = this.buildColumnLayout();
  230. this._startX = evt.clientX;
  231. }
  232. buildColumnLayout() {
  233. return `${this._leftWidth}px 4px calc(100% - ${this._leftWidth + 8 + this._rightWidth}px) 4px ${this._rightWidth}px`;
  234. }
  235. emitNewBlock(event: React.DragEvent<HTMLDivElement>) {
  236. var data = event.dataTransfer.getData("babylonjs-material-node") as string;
  237. let guiElement = BlockTools.GetGuiFromString(data);
  238. //guiElement.background = "#138016FF";
  239. let newGuiNode = this._workbenchCanvas.appendBlock(guiElement);
  240. /*let x = event.clientX;// - event.currentTarget.offsetLeft - this._workbenchCanvas.x;
  241. let y = event.clientY;// - event.currentTarget.offsetTop - this._workbenchCanvas.y - 20;
  242. newGuiNode.x += (x - newGuiNode.x);
  243. newGuiNode.y += y - newGuiNode.y;
  244. //newGuiNode.cleanAccumulation();*/
  245. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  246. this.props.globalState.onSelectionChangedObservable.notifyObservers(newGuiNode);
  247. this.forceUpdate();
  248. }
  249. handlePopUp = () => {
  250. this.setState({
  251. showPreviewPopUp : true
  252. });
  253. this.createPopUp();
  254. this.props.globalState.hostWindow.addEventListener('beforeunload', this.handleClosingPopUp);
  255. }
  256. handleClosingPopUp = () => {
  257. this._popUpWindow.close();
  258. this.setState({
  259. showPreviewPopUp: false
  260. }, () => this.initiatePreviewArea()
  261. );
  262. }
  263. initiatePreviewArea = (canvas: HTMLCanvasElement = this.props.globalState.hostDocument.getElementById("preview-canvas") as HTMLCanvasElement) => {
  264. //this._previewManager = new PreviewManager(canvas, this.props.globalState);
  265. }
  266. createPopUp = () => {
  267. const userOptions = {
  268. original: true,
  269. popup: true,
  270. overlay: false,
  271. embedMode: false,
  272. enableClose: true,
  273. handleResize: true,
  274. enablePopup: true,
  275. };
  276. const options = {
  277. embedHostWidth: "100%",
  278. ...userOptions
  279. };
  280. const popUpWindow = this.createPopupWindow("PREVIEW AREA", "_PreviewHostWindow");
  281. if (popUpWindow) {
  282. popUpWindow.addEventListener('beforeunload', this.handleClosingPopUp);
  283. const parentControl = popUpWindow.document.getElementById('gui-editor-workbench-root');
  284. this.createPreviewMeshControlHost(options, parentControl);
  285. this.createPreviewHost(options, parentControl);
  286. if (parentControl) {
  287. this.fixPopUpStyles(parentControl.ownerDocument!);
  288. this.initiatePreviewArea(parentControl.ownerDocument!.getElementById("preview-canvas") as HTMLCanvasElement);
  289. }
  290. }
  291. }
  292. createPopupWindow = (title: string, windowVariableName: string, width = 500, height = 500): Window | null => {
  293. const windowCreationOptionsList = {
  294. width: width,
  295. height: height,
  296. top: (this.props.globalState.hostWindow.innerHeight - width) / 2 + window.screenY,
  297. left: (this.props.globalState.hostWindow.innerWidth - height) / 2 + window.screenX
  298. };
  299. var windowCreationOptions = Object.keys(windowCreationOptionsList)
  300. .map(
  301. (key) => key + '=' + (windowCreationOptionsList as any)[key]
  302. )
  303. .join(',');
  304. const popupWindow = this.props.globalState.hostWindow.open("", title, windowCreationOptions);
  305. if (!popupWindow) {
  306. return null;
  307. }
  308. const parentDocument = popupWindow.document;
  309. parentDocument.title = title;
  310. parentDocument.body.style.width = "100%";
  311. parentDocument.body.style.height = "100%";
  312. parentDocument.body.style.margin = "0";
  313. parentDocument.body.style.padding = "0";
  314. let parentControl = parentDocument.createElement("div");
  315. parentControl.style.width = "100%";
  316. parentControl.style.height = "100%";
  317. parentControl.style.margin = "0";
  318. parentControl.style.padding = "0";
  319. parentControl.style.display = "grid";
  320. parentControl.style.gridTemplateRows = "40px auto";
  321. parentControl.id = 'node-editor-graph-root';
  322. parentControl.className = 'right-panel';
  323. popupWindow.document.body.appendChild(parentControl);
  324. this.copyStyles(this.props.globalState.hostWindow.document, parentDocument);
  325. (this as any)[windowVariableName] = popupWindow;
  326. this._popUpWindow = popupWindow;
  327. return popupWindow;
  328. }
  329. copyStyles = (sourceDoc: HTMLDocument, targetDoc: HTMLDocument) => {
  330. const styleContainer = [];
  331. for (var index = 0; index < sourceDoc.styleSheets.length; index++) {
  332. var styleSheet: any = sourceDoc.styleSheets[index];
  333. try {
  334. if (styleSheet.href) { // for <link> elements loading CSS from a URL
  335. const newLinkEl = sourceDoc.createElement('link');
  336. newLinkEl.rel = 'stylesheet';
  337. newLinkEl.href = styleSheet.href;
  338. targetDoc.head!.appendChild(newLinkEl);
  339. styleContainer.push(newLinkEl);
  340. }
  341. else if (styleSheet.cssRules) { // for <style> elements
  342. const newStyleEl = sourceDoc.createElement('style');
  343. for (var cssRule of styleSheet.cssRules) {
  344. newStyleEl.appendChild(sourceDoc.createTextNode(cssRule.cssText));
  345. }
  346. targetDoc.head!.appendChild(newStyleEl);
  347. styleContainer.push(newStyleEl);
  348. }
  349. } catch (e) {
  350. console.log(e);
  351. }
  352. }
  353. }
  354. createPreviewMeshControlHost = (options: IInternalPreviewAreaOptions, parentControl: Nullable<HTMLElement>) => {
  355. // Prepare the preview control host
  356. if (parentControl) {
  357. const host = parentControl.ownerDocument!.createElement("div");
  358. host.id = "PreviewMeshControl-host";
  359. host.style.width = options.embedHostWidth || "auto";
  360. parentControl.appendChild(host);
  361. /*const PreviewMeshControlComponentHost = React.createElement(PreviewMeshControlComponent, {
  362. globalState: this.props.globalState,
  363. togglePreviewAreaComponent: this.handlePopUp
  364. });
  365. ReactDOM.render(PreviewMeshControlComponentHost, host);*/
  366. }
  367. }
  368. createPreviewHost = (options: IInternalPreviewAreaOptions, parentControl: Nullable<HTMLElement>) => {
  369. // Prepare the preview host
  370. if (parentControl) {
  371. const host = parentControl.ownerDocument!.createElement("div");
  372. host.id = "PreviewAreaComponent-host";
  373. host.style.width = options.embedHostWidth || "auto";
  374. host.style.display = "grid";
  375. host.style.gridRow = '2';
  376. host.style.gridTemplateRows = "auto 40px";
  377. parentControl.appendChild(host);
  378. this._previewHost = host;
  379. if (!options.overlay) {
  380. this._previewHost.style.position = "relative";
  381. }
  382. }
  383. }
  384. fixPopUpStyles = (document: Document) => {
  385. const previewContainer = document.getElementById("preview");
  386. if (previewContainer) {
  387. previewContainer.style.height = "auto";
  388. previewContainer.style.gridRow = "1";
  389. }
  390. const previewConfigBar = document.getElementById("preview-config-bar");
  391. if (previewConfigBar) {
  392. previewConfigBar.style.gridRow = "2";
  393. }
  394. const newWindowButton = document.getElementById('preview-new-window');
  395. if (newWindowButton) {
  396. newWindowButton.style.display = 'none';
  397. }
  398. const previewMeshBar = document.getElementById('preview-mesh-bar');
  399. if (previewMeshBar) {
  400. previewMeshBar.style.gridTemplateColumns = "auto 1fr 40px 40px";
  401. }
  402. }
  403. render() {
  404. return (
  405. <Portal globalState={this.props.globalState}>
  406. <div id="gui-editor-workbench-root" style={
  407. {
  408. gridTemplateColumns: this.buildColumnLayout()
  409. }}
  410. onMouseMove={evt => {
  411. // this._mouseLocationX = evt.pageX;
  412. // this._mouseLocationY = evt.pageY;
  413. }}
  414. onMouseDown={(evt) => {
  415. if ((evt.target as HTMLElement).nodeName === "INPUT") {
  416. return;
  417. }
  418. this.props.globalState.blockKeyboardEvents = false;
  419. }}
  420. >
  421. {/* Node creation menu */}
  422. <NodeListComponent globalState={this.props.globalState} />
  423. <div id="leftGrab"
  424. onPointerDown={evt => this.onPointerDown(evt)}
  425. onPointerUp={evt => this.onPointerUp(evt)}
  426. onPointerMove={evt => this.resizeColumns(evt)}
  427. ></div>
  428. {/* The gui workbench diagram */}
  429. <div className="diagram-container"
  430. onDrop={event => {
  431. this.emitNewBlock(event);
  432. }}
  433. onDragOver={event => {
  434. event.preventDefault();
  435. }}
  436. >
  437. <WorkbenchComponent ref={"graphCanvas"} globalState={this.props.globalState}/>
  438. </div>
  439. <div id="rightGrab"
  440. onPointerDown={evt => this.onPointerDown(evt)}
  441. onPointerUp={evt => this.onPointerUp(evt)}
  442. onPointerMove={evt => this.resizeColumns(evt, false)}
  443. ></div>
  444. {/* Property tab */}
  445. <div className="right-panel">
  446. <PropertyTabComponent globalState={this.props.globalState} />
  447. </div>
  448. <LogComponent globalState={this.props.globalState} />
  449. </div>
  450. <MessageDialogComponent globalState={this.props.globalState} />
  451. <div className="blocker">
  452. Node Material Editor runs only on desktop
  453. </div>
  454. <div className="wait-screen hidden">
  455. Processing...please wait
  456. </div>
  457. </Portal>
  458. );
  459. }
  460. }