graphEditor.tsx 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. import {
  2. DiagramEngine,
  3. DiagramModel,
  4. DiagramWidget,
  5. LinkModel
  6. } from "storm-react-diagrams";
  7. import * as React from "react";
  8. import { GlobalState } from './globalState';
  9. import { GenericNodeFactory } from './components/diagram/generic/genericNodeFactory';
  10. import { GenericNodeModel } from './components/diagram/generic/genericNodeModel';
  11. import { NodeMaterialBlock } from 'babylonjs/Materials/Node/nodeMaterialBlock';
  12. import { NodeMaterialConnectionPoint, NodeMaterialConnectionPointCompatibilityStates } from 'babylonjs/Materials/Node/nodeMaterialBlockConnectionPoint';
  13. import { NodeListComponent } from './components/nodeList/nodeListComponent';
  14. import { PropertyTabComponent } from './components/propertyTab/propertyTabComponent';
  15. import { Portal } from './portal';
  16. import { TextureNodeFactory } from './components/diagram/texture/textureNodeFactory';
  17. import { DefaultNodeModel } from './components/diagram/defaultNodeModel';
  18. import { TextureNodeModel } from './components/diagram/texture/textureNodeModel';
  19. import { DefaultPortModel } from './components/diagram/port/defaultPortModel';
  20. import { InputNodeFactory } from './components/diagram/input/inputNodeFactory';
  21. import { InputNodeModel } from './components/diagram/input/inputNodeModel';
  22. import { TextureBlock } from 'babylonjs/Materials/Node/Blocks/Dual/textureBlock';
  23. import { LogComponent, LogEntry } from './components/log/logComponent';
  24. import { LightBlock } from 'babylonjs/Materials/Node/Blocks/Dual/lightBlock';
  25. import { LightNodeModel } from './components/diagram/light/lightNodeModel';
  26. import { LightNodeFactory } from './components/diagram/light/lightNodeFactory';
  27. import { DataStorage } from './dataStorage';
  28. import { NodeMaterialBlockConnectionPointTypes } from 'babylonjs/Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes';
  29. import { InputBlock } from 'babylonjs/Materials/Node/Blocks/Input/inputBlock';
  30. import { Nullable } from 'babylonjs/types';
  31. import { MessageDialogComponent } from './sharedComponents/messageDialog';
  32. import { BlockTools } from './blockTools';
  33. import { AdvancedLinkFactory } from './components/diagram/link/advancedLinkFactory';
  34. import { RemapNodeFactory } from './components/diagram/remap/remapNodeFactory';
  35. import { RemapNodeModel } from './components/diagram/remap/remapNodeModel';
  36. import { RemapBlock } from 'babylonjs/Materials/Node/Blocks/remapBlock';
  37. import { SimplexPerlin3D } from 'babylonjs/Materials/Node/Blocks/simplexPerlin3D';
  38. import { GraphHelper } from './graphHelper';
  39. import { PreviewManager } from './components/preview/previewManager';
  40. import { INodeLocationInfo } from './nodeLocationInfo';
  41. import { PreviewMeshControlComponent } from './components/preview/previewMeshControlComponent';
  42. import { TrigonometryNodeFactory } from './components/diagram/trigonometry/trigonometryNodeFactory';
  43. import { TrigonometryBlock } from 'babylonjs/Materials/Node/Blocks/trigonometryBlock';
  44. import { TrigonometryNodeModel } from './components/diagram/trigonometry/trigonometryNodeModel';
  45. import { AdvancedLinkModel } from './components/diagram/link/advancedLinkModel';
  46. import { ClampNodeFactory } from './components/diagram/clamp/clampNodeFactory';
  47. import { ClampNodeModel } from './components/diagram/clamp/clampNodeModel';
  48. import { ClampBlock } from 'babylonjs/Materials/Node/Blocks/clampBlock';
  49. import { LightInformationNodeFactory } from './components/diagram/lightInformation/lightInformationNodeFactory';
  50. import { LightInformationNodeModel } from './components/diagram/lightInformation/lightInformationNodeModel';
  51. import { LightInformationBlock } from 'babylonjs/Materials/Node/Blocks/Vertex/lightInformationBlock';
  52. import { PreviewAreaComponent } from './components/preview/previewAreaComponent';
  53. import { GradientBlock } from 'babylonjs/Materials/Node/Blocks/gradientBlock';
  54. import { GradientNodeModel } from './components/diagram/gradient/gradientNodeModel';
  55. import { GradientNodeFactory } from './components/diagram/gradient/gradientNodeFactory';
  56. import { ReflectionTextureBlock } from 'babylonjs/Materials/Node/Blocks/Dual/reflectionTextureBlock';
  57. import { ReflectionTextureNodeFactory } from './components/diagram/reflectionTexture/reflectionTextureNodeFactory';
  58. import { ReflectionTextureNodeModel } from './components/diagram/reflectionTexture/reflectionTextureNodeModel';
  59. require("storm-react-diagrams/dist/style.min.css");
  60. require("./main.scss");
  61. require("./components/diagram/diagram.scss");
  62. interface IGraphEditorProps {
  63. globalState: GlobalState;
  64. }
  65. export class NodeCreationOptions {
  66. nodeMaterialBlock: NodeMaterialBlock;
  67. type?: string;
  68. connection?: NodeMaterialConnectionPoint;
  69. }
  70. export class GraphEditor extends React.Component<IGraphEditorProps> {
  71. private readonly NodeWidth = 100;
  72. private _engine: DiagramEngine;
  73. private _model: DiagramModel;
  74. private _startX: number;
  75. private _moveInProgress: boolean;
  76. private _leftWidth = DataStorage.ReadNumber("LeftWidth", 200);
  77. private _rightWidth = DataStorage.ReadNumber("RightWidth", 300);
  78. private _nodes = new Array<DefaultNodeModel>();
  79. private _blocks = new Array<NodeMaterialBlock>();
  80. private _previewManager: PreviewManager;
  81. private _copiedNodes: DefaultNodeModel[] = [];
  82. private _mouseLocationX = 0;
  83. private _mouseLocationY = 0;
  84. private _onWidgetKeyUpPointer: any;
  85. private _altKeyIsPressed = false;
  86. private _oldY = -1;
  87. /** @hidden */
  88. public _toAdd: LinkModel[] | null = [];
  89. /**
  90. * Creates a node and recursivly creates its parent nodes from it's input
  91. * @param nodeMaterialBlock
  92. */
  93. public createNodeFromObject(options: NodeCreationOptions) {
  94. if (this._blocks.indexOf(options.nodeMaterialBlock) !== -1) {
  95. return this._nodes.filter(n => n.block === options.nodeMaterialBlock)[0];
  96. }
  97. this._blocks.push(options.nodeMaterialBlock);
  98. if (this.props.globalState.nodeMaterial!.attachedBlocks.indexOf(options.nodeMaterialBlock) === -1) {
  99. this.props.globalState.nodeMaterial!.attachedBlocks.push(options.nodeMaterialBlock);
  100. }
  101. // Create new node in the graph
  102. var newNode: DefaultNodeModel;
  103. if (options.nodeMaterialBlock instanceof TextureBlock) {
  104. newNode = new TextureNodeModel();
  105. } else if (options.nodeMaterialBlock instanceof ReflectionTextureBlock) {
  106. newNode = new ReflectionTextureNodeModel();
  107. } else if (options.nodeMaterialBlock instanceof LightBlock) {
  108. newNode = new LightNodeModel();
  109. } else if (options.nodeMaterialBlock instanceof InputBlock) {
  110. newNode = new InputNodeModel();
  111. } else if (options.nodeMaterialBlock instanceof TrigonometryBlock) {
  112. newNode = new TrigonometryNodeModel();
  113. } else if (options.nodeMaterialBlock instanceof RemapBlock) {
  114. newNode = new RemapNodeModel();
  115. } else if (options.nodeMaterialBlock instanceof ClampBlock) {
  116. newNode = new ClampNodeModel();
  117. } else if (options.nodeMaterialBlock instanceof LightInformationBlock) {
  118. newNode = new LightInformationNodeModel();
  119. } else if (options.nodeMaterialBlock instanceof GradientBlock) {
  120. newNode = new GradientNodeModel();
  121. } else if (options.nodeMaterialBlock instanceof SimplexPerlin3D) {
  122. newNode = new GenericNodeModel();
  123. } else {
  124. newNode = new GenericNodeModel();
  125. }
  126. if (options.nodeMaterialBlock.isFinalMerger) {
  127. this.props.globalState.nodeMaterial!.addOutputNode(options.nodeMaterialBlock);
  128. }
  129. this._nodes.push(newNode);
  130. this._model.addAll(newNode);
  131. if (options.nodeMaterialBlock) {
  132. newNode.prepare(options, this._nodes, this._model, this);
  133. }
  134. return newNode;
  135. }
  136. addValueNode(type: string) {
  137. let nodeType: NodeMaterialBlockConnectionPointTypes = BlockTools.GetConnectionNodeTypeFromString(type);
  138. let newInputBlock = new InputBlock(type, undefined, nodeType);
  139. var localNode = this.createNodeFromObject({ type: type, nodeMaterialBlock: newInputBlock })
  140. return localNode;
  141. }
  142. onWidgetKeyUp(evt: any) {
  143. this._altKeyIsPressed = false;
  144. this._oldY = -1;
  145. var widget = (this.refs["test"] as DiagramWidget);
  146. if (!widget || this.props.globalState.blockKeyboardEvents) {
  147. return;
  148. }
  149. widget.onKeyUp(evt)
  150. }
  151. componentDidMount() {
  152. if (this.props.globalState.hostDocument) {
  153. var widget = (this.refs["test"] as DiagramWidget);
  154. widget.setState({ document: this.props.globalState.hostDocument })
  155. this._onWidgetKeyUpPointer = this.onWidgetKeyUp.bind(this)
  156. this.props.globalState.hostDocument!.addEventListener("keyup", this._onWidgetKeyUpPointer, false);
  157. let previousMouseMove = widget.onMouseMove;
  158. widget.onMouseMove = (evt: any) => {
  159. if (this._altKeyIsPressed && evt.buttons === 1) {
  160. if (this._oldY < 0) {
  161. this._oldY = evt.pageY;
  162. }
  163. let zoomDelta = (evt.pageY - this._oldY) / 10;
  164. if (Math.abs(zoomDelta) > 5) {
  165. this._engine.diagramModel.setZoomLevel(this._engine.diagramModel.getZoomLevel() + zoomDelta);
  166. this._engine.repaintCanvas();
  167. this._oldY = evt.pageY;
  168. }
  169. return;
  170. }
  171. previousMouseMove(evt);
  172. }
  173. let previousMouseUp = widget.onMouseUp;
  174. widget.onMouseUp = (evt: any) => {
  175. this._oldY = -1;
  176. previousMouseUp(evt);
  177. }
  178. this._previewManager = new PreviewManager(this.props.globalState.hostDocument.getElementById("preview-canvas") as HTMLCanvasElement, this.props.globalState);
  179. }
  180. if (navigator.userAgent.indexOf("Mobile") !== -1) {
  181. ((this.props.globalState.hostDocument || document).querySelector(".blocker") as HTMLElement).style.visibility = "visible";
  182. }
  183. }
  184. componentWillUnmount() {
  185. if (this.props.globalState.hostDocument) {
  186. this.props.globalState.hostDocument!.removeEventListener("keyup", this._onWidgetKeyUpPointer, false);
  187. }
  188. if (this._previewManager) {
  189. this._previewManager.dispose();
  190. }
  191. }
  192. constructor(props: IGraphEditorProps) {
  193. super(props);
  194. // setup the diagram engine
  195. this._engine = new DiagramEngine();
  196. this._engine.installDefaultFactories()
  197. this._engine.registerNodeFactory(new GenericNodeFactory(this.props.globalState));
  198. this._engine.registerNodeFactory(new TextureNodeFactory(this.props.globalState));
  199. this._engine.registerNodeFactory(new LightNodeFactory(this.props.globalState));
  200. this._engine.registerNodeFactory(new InputNodeFactory(this.props.globalState));
  201. this._engine.registerNodeFactory(new RemapNodeFactory(this.props.globalState));
  202. this._engine.registerNodeFactory(new TrigonometryNodeFactory(this.props.globalState));
  203. this._engine.registerNodeFactory(new ClampNodeFactory(this.props.globalState));
  204. this._engine.registerNodeFactory(new LightInformationNodeFactory(this.props.globalState));
  205. this._engine.registerNodeFactory(new GradientNodeFactory(this.props.globalState));
  206. this._engine.registerNodeFactory(new ReflectionTextureNodeFactory(this.props.globalState));
  207. this._engine.registerLinkFactory(new AdvancedLinkFactory());
  208. this.props.globalState.onRebuildRequiredObservable.add(() => {
  209. if (this.props.globalState.nodeMaterial) {
  210. this.buildMaterial();
  211. }
  212. });
  213. this.props.globalState.onResetRequiredObservable.add((locations) => {
  214. this.build(false, locations);
  215. if (this.props.globalState.nodeMaterial) {
  216. this.buildMaterial();
  217. }
  218. });
  219. this.props.globalState.onUpdateRequiredObservable.add(() => {
  220. this._engine.repaintCanvas();
  221. });
  222. this.props.globalState.onZoomToFitRequiredObservable.add(() => {
  223. this.zoomToFit();
  224. });
  225. this.props.globalState.onReOrganizedRequiredObservable.add(() => {
  226. this.reOrganize();
  227. });
  228. this.props.globalState.onGetNodeFromBlock = (block) => {
  229. return this._nodes.filter(n => n.block === block)[0];
  230. }
  231. this.props.globalState.hostDocument!.addEventListener("keydown", evt => {
  232. this._altKeyIsPressed = evt.altKey;
  233. if (!evt.ctrlKey) {
  234. return;
  235. }
  236. if (evt.key === "c") {
  237. let selectedItems = this._engine.diagramModel.getSelectedItems();
  238. if (!selectedItems.length) {
  239. return;
  240. }
  241. let selectedItem = selectedItems[0] as DefaultNodeModel;
  242. if (!selectedItem.block) {
  243. return;
  244. }
  245. this._copiedNodes = selectedItems.map(i => (i as DefaultNodeModel)!);
  246. } else if (evt.key === "v") {
  247. if (!this._copiedNodes.length) {
  248. return;
  249. }
  250. const rootElement = this.props.globalState.hostDocument!.querySelector(".diagram-container") as HTMLDivElement;
  251. const zoomLevel = this._engine.diagramModel.getZoomLevel() / 100.0;
  252. let currentX = (this._mouseLocationX - rootElement.offsetLeft - this._engine.diagramModel.getOffsetX() - this.NodeWidth) / zoomLevel;
  253. let currentY = (this._mouseLocationY - rootElement.offsetTop - this._engine.diagramModel.getOffsetY() - 20) / zoomLevel;
  254. let originalNode: Nullable<DefaultNodeModel> = null;
  255. for (var node of this._copiedNodes) {
  256. let block = node.block;
  257. if (!block) {
  258. continue;
  259. }
  260. let clone = block.clone(this.props.globalState.nodeMaterial.getScene());
  261. if (!clone) {
  262. return;
  263. }
  264. let newNode = this.createNodeFromObject({ nodeMaterialBlock: clone });
  265. let x = 0;
  266. let y = 0;
  267. if (originalNode) {
  268. x = currentX + node.x - originalNode.x;
  269. y = currentY + node.y - originalNode.y;
  270. } else {
  271. originalNode = node;
  272. x = currentX;
  273. y = currentY;
  274. }
  275. newNode.setPosition(x, y);
  276. }
  277. this._engine.repaintCanvas();
  278. }
  279. }, false);
  280. this.build(true);
  281. }
  282. zoomToFit(retry = 0) {
  283. const xFactor = this._engine.canvas.clientWidth / this._engine.canvas.scrollWidth;
  284. const yFactor = this._engine.canvas.clientHeight / this._engine.canvas.scrollHeight;
  285. const zoomFactor = xFactor < yFactor ? xFactor : yFactor;
  286. if (zoomFactor === 1) {
  287. return;
  288. }
  289. this._engine.diagramModel.setZoomLevel(this._engine.diagramModel.getZoomLevel() * zoomFactor);
  290. this._engine.diagramModel.setOffset(0, 0);
  291. this._engine.repaintCanvas();
  292. retry++;
  293. if (retry < 4) {
  294. setTimeout(() => this.zoomToFit(retry), 1);
  295. }
  296. }
  297. buildMaterial() {
  298. if (!this.props.globalState.nodeMaterial) {
  299. return;
  300. }
  301. try {
  302. this.props.globalState.nodeMaterial.build(true);
  303. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry("Node material build successful", false));
  304. }
  305. catch (err) {
  306. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry(err, true));
  307. }
  308. }
  309. applyFragmentOutputConstraints(rootInput: DefaultPortModel) {
  310. var model = rootInput.parent as GenericNodeModel;
  311. for (var inputKey in model.getPorts()) {
  312. let input = model.getPorts()[inputKey];
  313. if (rootInput.name === "rgba" && (inputKey === "a" || inputKey === "rgb")
  314. ||
  315. (rootInput.name === "a" || rootInput.name === "rgb") && inputKey === "rgba") {
  316. for (var key in input.links) {
  317. let other = input.links[key];
  318. other.remove();
  319. }
  320. continue;
  321. }
  322. }
  323. }
  324. build(needToWait = false, locations: Nullable<INodeLocationInfo[]> = null) {
  325. // setup the diagram model
  326. this._model = new DiagramModel();
  327. this._nodes = [];
  328. this._blocks = [];
  329. // Listen to events
  330. this._model.addListener({
  331. nodesUpdated: (e) => {
  332. if (!e.isCreated) {
  333. // Block is deleted
  334. let targetBlock = (e.node as GenericNodeModel).block;
  335. if (targetBlock) {
  336. let attachedBlockIndex = this.props.globalState.nodeMaterial!.attachedBlocks.indexOf(targetBlock);
  337. if (attachedBlockIndex > -1) {
  338. this.props.globalState.nodeMaterial!.attachedBlocks.splice(attachedBlockIndex, 1);
  339. }
  340. if (targetBlock.isFinalMerger) {
  341. this.props.globalState.nodeMaterial!.removeOutputNode(targetBlock);
  342. }
  343. let blockIndex = this._blocks.indexOf(targetBlock);
  344. if (blockIndex > -1) {
  345. this._blocks.splice(blockIndex, 1);
  346. }
  347. }
  348. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  349. } else {
  350. }
  351. },
  352. linksUpdated: (e) => {
  353. if (!e.isCreated) {
  354. // Link is deleted
  355. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  356. let sourcePort = e.link.sourcePort as DefaultPortModel;
  357. var link = DefaultPortModel.SortInputOutput(sourcePort, e.link.targetPort as DefaultPortModel);
  358. if (link) {
  359. if (link.input.connection && link.output.connection) {
  360. if (link.input.connection.connectedPoint) {
  361. // Disconnect standard nodes
  362. link.output.connection.disconnectFrom(link.input.connection);
  363. link.input.syncWithNodeMaterialConnectionPoint(link.input.connection);
  364. link.output.syncWithNodeMaterialConnectionPoint(link.output.connection);
  365. this.props.globalState.onRebuildRequiredObservable.notifyObservers();
  366. }
  367. }
  368. } else {
  369. if (!e.link.targetPort && e.link.sourcePort && (e.link.sourcePort as DefaultPortModel).position === "input" && !(e.link.sourcePort as DefaultPortModel).connection!.isConnected) {
  370. // Drag from input port, we are going to build an input for it
  371. let input = e.link.sourcePort as DefaultPortModel;
  372. if (input.connection!.type == NodeMaterialBlockConnectionPointTypes.AutoDetect) {
  373. return;
  374. }
  375. let nodeModel = this.addValueNode(BlockTools.GetStringFromConnectionNodeType(input.connection!.type));
  376. let link = nodeModel.ports.output.link(input);
  377. nodeModel.x = e.link.points[1].x - this.NodeWidth;
  378. nodeModel.y = e.link.points[1].y;
  379. setTimeout(() => {
  380. this._model.addLink(link);
  381. input.syncWithNodeMaterialConnectionPoint(input.connection!);
  382. nodeModel.ports.output.syncWithNodeMaterialConnectionPoint(nodeModel.ports.output.connection!);
  383. let isFragmentOutput = (input.parent as DefaultNodeModel).block!.getClassName() === "FragmentOutputBlock";
  384. if (isFragmentOutput) {
  385. this.applyFragmentOutputConstraints(input);
  386. }
  387. this.forceUpdate();
  388. }, 1);
  389. nodeModel.ports.output.connection!.connectTo(input.connection!);
  390. this.props.globalState.onRebuildRequiredObservable.notifyObservers();
  391. }
  392. }
  393. this.forceUpdate();
  394. return;
  395. } else {
  396. e.link.addListener({
  397. sourcePortChanged: () => {
  398. },
  399. targetPortChanged: (evt) => {
  400. // Link is created with a target port
  401. var link = DefaultPortModel.SortInputOutput(e.link.sourcePort as DefaultPortModel, e.link.targetPort as DefaultPortModel);
  402. if (link) {
  403. if (link.output.connection && link.input.connection) {
  404. let currentBlock = link.input.connection.ownerBlock;
  405. let isFragmentOutput = currentBlock.getClassName() === "FragmentOutputBlock";
  406. // Disconnect previous connection
  407. for (var key in link.input.links) {
  408. let other = link.input.links[key];
  409. let sourcePortConnection = (other.getSourcePort() as DefaultPortModel).connection;
  410. let targetPortConnection = (other.getTargetPort() as DefaultPortModel).connection;
  411. if (
  412. sourcePortConnection !== (link.output as DefaultPortModel).connection &&
  413. targetPortConnection !== (link.output as DefaultPortModel).connection
  414. ) {
  415. other.remove();
  416. }
  417. }
  418. let compatibilityState = link.output.connection.checkCompatibilityState(link.input.connection);
  419. if (compatibilityState === NodeMaterialConnectionPointCompatibilityStates.Compatible) {
  420. if (isFragmentOutput) {
  421. this.applyFragmentOutputConstraints(link.input);
  422. }
  423. link.output.connection.connectTo(link.input.connection);
  424. } else {
  425. (evt.entity as AdvancedLinkModel).remove();
  426. let message = "";
  427. switch (compatibilityState) {
  428. case NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible:
  429. message = "Cannot connect two different connection types";
  430. break;
  431. case NodeMaterialConnectionPointCompatibilityStates.TargetIncompatible:
  432. message = "Source block can only work in fragment shader whereas destination block is currently aimed for the vertex shader";
  433. break;
  434. }
  435. this.props.globalState.onErrorMessageDialogRequiredObservable.notifyObservers(message);
  436. }
  437. this.forceUpdate();
  438. }
  439. if (this.props.globalState.nodeMaterial) {
  440. this.buildMaterial();
  441. }
  442. }
  443. }
  444. });
  445. }
  446. }
  447. });
  448. // Load graph of nodes from the material
  449. if (this.props.globalState.nodeMaterial) {
  450. var material = this.props.globalState.nodeMaterial;
  451. material._vertexOutputNodes.forEach((n: any) => {
  452. this.createNodeFromObject({ nodeMaterialBlock: n });
  453. });
  454. material._fragmentOutputNodes.forEach((n: any) => {
  455. this.createNodeFromObject({ nodeMaterialBlock: n });
  456. });
  457. material.attachedBlocks.forEach((n: any) => {
  458. this.createNodeFromObject({ nodeMaterialBlock: n });
  459. });
  460. }
  461. // load model into engine
  462. setTimeout(() => {
  463. if (this._toAdd) {
  464. this._model.addAll(...this._toAdd);
  465. }
  466. this._toAdd = null;
  467. this._engine.setDiagramModel(this._model);
  468. this.forceUpdate();
  469. this.reOrganize(locations);
  470. }, needToWait ? 500 : 1);
  471. }
  472. reOrganize(locations: Nullable<INodeLocationInfo[]> = null) {
  473. if (!locations) {
  474. let nodes = GraphHelper.DistributeGraph(this._model);
  475. nodes.forEach(node => {
  476. for (var nodeName in this._model.nodes) {
  477. let modelNode = this._model.nodes[nodeName];
  478. if (modelNode.id === node.id) {
  479. modelNode.setPosition(node.x - node.width / 2, node.y - node.height / 2);
  480. return;
  481. }
  482. }
  483. });
  484. } else {
  485. for (var location of locations) {
  486. for (var node of this._nodes) {
  487. if (node.block && node.block.uniqueId === location.blockId) {
  488. node.setPosition(location.x, location.y);
  489. break;
  490. }
  491. }
  492. }
  493. }
  494. this._engine.repaintCanvas();
  495. }
  496. onPointerDown(evt: React.PointerEvent<HTMLDivElement>) {
  497. this._startX = evt.clientX;
  498. this._moveInProgress = true;
  499. evt.currentTarget.setPointerCapture(evt.pointerId);
  500. }
  501. onPointerUp(evt: React.PointerEvent<HTMLDivElement>) {
  502. this._moveInProgress = false;
  503. evt.currentTarget.releasePointerCapture(evt.pointerId);
  504. }
  505. resizeColumns(evt: React.PointerEvent<HTMLDivElement>, forLeft = true) {
  506. if (!this._moveInProgress) {
  507. return;
  508. }
  509. const deltaX = evt.clientX - this._startX;
  510. const rootElement = evt.currentTarget.ownerDocument!.getElementById("node-editor-graph-root") as HTMLDivElement;
  511. if (forLeft) {
  512. this._leftWidth += deltaX;
  513. this._leftWidth = Math.max(150, Math.min(400, this._leftWidth));
  514. DataStorage.StoreNumber("LeftWidth", this._leftWidth);
  515. } else {
  516. this._rightWidth -= deltaX;
  517. this._rightWidth = Math.max(250, Math.min(500, this._rightWidth));
  518. DataStorage.StoreNumber("RightWidth", this._rightWidth);
  519. rootElement.ownerDocument!.getElementById("preview")!.style.height = this._rightWidth + "px";
  520. }
  521. rootElement.style.gridTemplateColumns = this.buildColumnLayout();
  522. this._startX = evt.clientX;
  523. }
  524. buildColumnLayout() {
  525. return `${this._leftWidth}px 4px calc(100% - ${this._leftWidth + 8 + this._rightWidth}px) 4px ${this._rightWidth}px`;
  526. }
  527. emitNewBlock(event: React.DragEvent<HTMLDivElement>) {
  528. var data = event.dataTransfer.getData("babylonjs-material-node") as string;
  529. let nodeModel: Nullable<DefaultNodeModel> = null;
  530. if (data.indexOf("Block") === -1) {
  531. nodeModel = this.addValueNode(data);
  532. } else {
  533. let block = BlockTools.GetBlockFromString(data, this.props.globalState.nodeMaterial.getScene(), this.props.globalState.nodeMaterial);
  534. if (block) {
  535. if (block.isUnique) {
  536. const className = block.getClassName();
  537. for (var other of this._blocks) {
  538. if (other !== block && other.getClassName() === className) {
  539. this.props.globalState.onErrorMessageDialogRequiredObservable.notifyObservers(`You can only have one ${className} per graph`);
  540. return;
  541. }
  542. }
  543. }
  544. this._toAdd = [];
  545. block.autoConfigure(this.props.globalState.nodeMaterial);
  546. nodeModel = this.createNodeFromObject({ nodeMaterialBlock: block });
  547. }
  548. };
  549. if (nodeModel) {
  550. const zoomLevel = this._engine.diagramModel.getZoomLevel() / 100.0;
  551. let x = (event.clientX - event.currentTarget.offsetLeft - this._engine.diagramModel.getOffsetX() - this.NodeWidth) / zoomLevel;
  552. let y = (event.clientY - event.currentTarget.offsetTop - this._engine.diagramModel.getOffsetY() - 20) / zoomLevel;
  553. nodeModel.setPosition(x, y);
  554. let block = nodeModel!.block;
  555. x -= this.NodeWidth + 150;
  556. block!._inputs.forEach((connection) => {
  557. if (connection.connectedPoint) {
  558. var existingNodes = this._nodes.filter((n) => { return n.block === (connection as any)._connectedPoint._ownerBlock });
  559. let connectedNode = existingNodes[0];
  560. if (connectedNode.x === 0 && connectedNode.y === 0) {
  561. connectedNode.setPosition(x, y);
  562. y += 80;
  563. }
  564. }
  565. });
  566. this._engine.repaintCanvas();
  567. setTimeout(() => {
  568. this._model.addAll(...this._toAdd!);
  569. this._toAdd = null;
  570. this._model.clearSelection();
  571. nodeModel!.setSelected(true);
  572. this._engine.repaintCanvas();
  573. }, 150);
  574. }
  575. this.forceUpdate();
  576. }
  577. render() {
  578. return (
  579. <Portal globalState={this.props.globalState}>
  580. <div id="node-editor-graph-root" style={
  581. {
  582. gridTemplateColumns: this.buildColumnLayout()
  583. }}
  584. onMouseMove={evt => {
  585. this._mouseLocationX = evt.pageX;
  586. this._mouseLocationY = evt.pageY;
  587. }}
  588. onMouseDown={(evt) => {
  589. if ((evt.target as HTMLElement).nodeName === "INPUT") {
  590. return;
  591. }
  592. this.props.globalState.blockKeyboardEvents = false;
  593. }}
  594. >
  595. {/* Node creation menu */}
  596. <NodeListComponent globalState={this.props.globalState} />
  597. <div id="leftGrab"
  598. onPointerDown={evt => this.onPointerDown(evt)}
  599. onPointerUp={evt => this.onPointerUp(evt)}
  600. onPointerMove={evt => this.resizeColumns(evt)}
  601. ></div>
  602. {/* The node graph diagram */}
  603. <div className="diagram-container"
  604. onDrop={event => {
  605. this.emitNewBlock(event);
  606. }}
  607. onDragOver={event => {
  608. event.preventDefault();
  609. }}
  610. >
  611. <DiagramWidget className="diagram" deleteKeys={[46]} ref={"test"}
  612. allowLooseLinks={false}
  613. inverseZoom={true}
  614. diagramEngine={this._engine}
  615. maxNumberPointsPerLink={0} />
  616. </div>
  617. <div id="rightGrab"
  618. onPointerDown={evt => this.onPointerDown(evt)}
  619. onPointerUp={evt => this.onPointerUp(evt)}
  620. onPointerMove={evt => this.resizeColumns(evt, false)}
  621. ></div>
  622. {/* Property tab */}
  623. <div className="right-panel">
  624. <PropertyTabComponent globalState={this.props.globalState} />
  625. <PreviewMeshControlComponent globalState={this.props.globalState} />
  626. <PreviewAreaComponent globalState={this.props.globalState} width={this._rightWidth}/>
  627. </div>
  628. <LogComponent globalState={this.props.globalState} />
  629. </div>
  630. <MessageDialogComponent globalState={this.props.globalState} />
  631. <div className="blocker">
  632. Node Material Editor runs only on desktop
  633. </div>
  634. </Portal>
  635. );
  636. }
  637. }