graphEditor.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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 } 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/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 { GraphHelper } from './graphHelper';
  38. import { PreviewManager } from './components/preview/previewManager';
  39. import { INodeLocationInfo } from './nodeLocationInfo';
  40. import { PreviewMeshControlComponent } from './components/preview/previewMeshControlComponent';
  41. require("storm-react-diagrams/dist/style.min.css");
  42. require("./main.scss");
  43. require("./components/diagram/diagram.scss");
  44. interface IGraphEditorProps {
  45. globalState: GlobalState;
  46. }
  47. export class NodeCreationOptions {
  48. nodeMaterialBlock: NodeMaterialBlock;
  49. type?: string;
  50. connection?: NodeMaterialConnectionPoint;
  51. }
  52. export class GraphEditor extends React.Component<IGraphEditorProps> {
  53. private readonly NodeWidth = 100;
  54. private _engine: DiagramEngine;
  55. private _model: DiagramModel;
  56. private _startX: number;
  57. private _moveInProgress: boolean;
  58. private _leftWidth = DataStorage.ReadNumber("LeftWidth", 200);
  59. private _rightWidth = DataStorage.ReadNumber("RightWidth", 300);
  60. private _nodes = new Array<DefaultNodeModel>();
  61. private _blocks = new Array<NodeMaterialBlock>();
  62. private _previewManager: PreviewManager;
  63. /** @hidden */
  64. public _toAdd: LinkModel[] | null = [];
  65. /**
  66. * Creates a node and recursivly creates its parent nodes from it's input
  67. * @param nodeMaterialBlock
  68. */
  69. public createNodeFromObject(options: NodeCreationOptions) {
  70. if (this._blocks.indexOf(options.nodeMaterialBlock) !== -1) {
  71. return this._nodes.filter(n => n.block === options.nodeMaterialBlock)[0];
  72. }
  73. this._blocks.push(options.nodeMaterialBlock);
  74. if (this.props.globalState.nodeMaterial!.attachedBlocks.indexOf(options.nodeMaterialBlock) === -1) {
  75. this.props.globalState.nodeMaterial!.attachedBlocks.push(options.nodeMaterialBlock);
  76. }
  77. // Create new node in the graph
  78. var newNode: DefaultNodeModel;
  79. if (options.nodeMaterialBlock instanceof TextureBlock) {
  80. newNode = new TextureNodeModel();
  81. } else if (options.nodeMaterialBlock instanceof LightBlock) {
  82. newNode = new LightNodeModel();
  83. } else if (options.nodeMaterialBlock instanceof InputBlock) {
  84. newNode = new InputNodeModel();
  85. } else if (options.nodeMaterialBlock instanceof RemapBlock) {
  86. newNode = new RemapNodeModel();
  87. } else {
  88. newNode = new GenericNodeModel();
  89. }
  90. if (options.nodeMaterialBlock.isFinalMerger) {
  91. this.props.globalState.nodeMaterial!.addOutputNode(options.nodeMaterialBlock);
  92. }
  93. this._nodes.push(newNode)
  94. this._model.addAll(newNode);
  95. if (options.nodeMaterialBlock) {
  96. newNode.prepare(options, this._nodes, this._model, this);
  97. }
  98. return newNode;
  99. }
  100. addValueNode(type: string) {
  101. let nodeType: NodeMaterialBlockConnectionPointTypes = BlockTools.GetConnectionNodeTypeFromString(type);
  102. let newInputBlock = new InputBlock(type, undefined, nodeType);
  103. var localNode = this.createNodeFromObject({ type: type, nodeMaterialBlock: newInputBlock })
  104. return localNode;
  105. }
  106. componentDidMount() {
  107. if (this.props.globalState.hostDocument) {
  108. var widget = (this.refs["test"] as DiagramWidget);
  109. widget.setState({ document: this.props.globalState.hostDocument })
  110. this.props.globalState.hostDocument!.addEventListener("keyup", widget.onKeyUpPointer as any, false);
  111. this._previewManager = new PreviewManager(this.props.globalState.hostDocument.getElementById("preview-canvas") as HTMLCanvasElement, this.props.globalState);
  112. }
  113. }
  114. componentWillUnmount() {
  115. if (this.props.globalState.hostDocument) {
  116. var widget = (this.refs["test"] as DiagramWidget);
  117. this.props.globalState.hostDocument!.removeEventListener("keyup", widget.onKeyUpPointer as any, false);
  118. }
  119. this._previewManager.dispose();
  120. }
  121. constructor(props: IGraphEditorProps) {
  122. super(props);
  123. // setup the diagram engine
  124. this._engine = new DiagramEngine();
  125. this._engine.installDefaultFactories()
  126. this._engine.registerNodeFactory(new GenericNodeFactory(this.props.globalState));
  127. this._engine.registerNodeFactory(new TextureNodeFactory(this.props.globalState));
  128. this._engine.registerNodeFactory(new LightNodeFactory(this.props.globalState));
  129. this._engine.registerNodeFactory(new InputNodeFactory(this.props.globalState));
  130. this._engine.registerNodeFactory(new RemapNodeFactory(this.props.globalState));
  131. this._engine.registerLinkFactory(new AdvancedLinkFactory());
  132. this.props.globalState.onRebuildRequiredObservable.add(() => {
  133. if (this.props.globalState.nodeMaterial) {
  134. this.buildMaterial();
  135. }
  136. this.forceUpdate();
  137. });
  138. this.props.globalState.onResetRequiredObservable.add((locations) => {
  139. this.build(false, locations);
  140. if (this.props.globalState.nodeMaterial) {
  141. this.buildMaterial();
  142. }
  143. });
  144. this.props.globalState.onUpdateRequiredObservable.add(() => {
  145. this.forceUpdate();
  146. });
  147. this.props.globalState.onZoomToFitRequiredObservable.add(() => {
  148. this.zoomToFit();
  149. });
  150. this.props.globalState.onReOrganizedRequiredObservable.add(() => {
  151. this.reOrganize();
  152. });
  153. this.props.globalState.onGetNodeFromBlock = (block) => {
  154. return this._nodes.filter(n => n.block === block)[0];
  155. }
  156. this.build(true);
  157. }
  158. zoomToFit(retry = 0) {
  159. const xFactor = this._engine.canvas.clientWidth / this._engine.canvas.scrollWidth;
  160. const yFactor = this._engine.canvas.clientHeight / this._engine.canvas.scrollHeight;
  161. const zoomFactor = xFactor < yFactor ? xFactor : yFactor;
  162. if (zoomFactor === 1) {
  163. return;
  164. }
  165. this._engine.diagramModel.setZoomLevel(this._engine.diagramModel.getZoomLevel() * zoomFactor);
  166. this._engine.diagramModel.setOffset(0, 0);
  167. this._engine.repaintCanvas();
  168. retry++;
  169. if (retry < 4) {
  170. setTimeout(() => this.zoomToFit(retry), 1);
  171. }
  172. }
  173. buildMaterial() {
  174. if (!this.props.globalState.nodeMaterial) {
  175. return;
  176. }
  177. try {
  178. this.props.globalState.nodeMaterial.build();
  179. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry("Node material build successful", false));
  180. }
  181. catch (err) {
  182. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry(err, true));
  183. }
  184. }
  185. build(needToWait = false, locations: Nullable<INodeLocationInfo[]> = null) {
  186. // setup the diagram model
  187. this._model = new DiagramModel();
  188. this._nodes = [];
  189. this._blocks = [];
  190. // Listen to events
  191. this._model.addListener({
  192. nodesUpdated: (e) => {
  193. if (!e.isCreated) {
  194. // Block is deleted
  195. let targetBlock = (e.node as GenericNodeModel).block;
  196. if (targetBlock) {
  197. let attachedBlockIndex = this.props.globalState.nodeMaterial!.attachedBlocks.indexOf(targetBlock);
  198. if (attachedBlockIndex > -1) {
  199. this.props.globalState.nodeMaterial!.attachedBlocks.splice(attachedBlockIndex, 1);
  200. }
  201. if (targetBlock.isFinalMerger) {
  202. this.props.globalState.nodeMaterial!.removeOutputNode(targetBlock);
  203. }
  204. let blockIndex = this._blocks.indexOf(targetBlock);
  205. if (blockIndex > -1) {
  206. this._blocks.splice(blockIndex, 1);
  207. }
  208. }
  209. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  210. }
  211. },
  212. linksUpdated: (e) => {
  213. if (!e.isCreated) {
  214. // Link is deleted
  215. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  216. let sourcePort = e.link.sourcePort as DefaultPortModel;
  217. var link = DefaultPortModel.SortInputOutput(sourcePort, e.link.targetPort as DefaultPortModel);
  218. if (link) {
  219. if (link.input.connection && link.output.connection) {
  220. if (link.input.connection.connectedPoint) {
  221. // Disconnect standard nodes
  222. link.output.connection.disconnectFrom(link.input.connection);
  223. link.input.syncWithNodeMaterialConnectionPoint(link.input.connection);
  224. link.output.syncWithNodeMaterialConnectionPoint(link.output.connection);
  225. }
  226. }
  227. } else {
  228. if (!e.link.targetPort && e.link.sourcePort && (e.link.sourcePort as DefaultPortModel).position === "input") {
  229. // Drag from input port, we are going to build an input for it
  230. let input = e.link.sourcePort as DefaultPortModel;
  231. let nodeModel = this.addValueNode(BlockTools.GetStringFromConnectionNodeType(input.connection!.type));
  232. let link = nodeModel.ports.output.link(input);
  233. nodeModel.x = e.link.points[1].x - this.NodeWidth;
  234. nodeModel.y = e.link.points[1].y;
  235. setTimeout(() => {
  236. this._model.addLink(link);
  237. input.syncWithNodeMaterialConnectionPoint(input.connection!);
  238. nodeModel.ports.output.syncWithNodeMaterialConnectionPoint(nodeModel.ports.output.connection!);
  239. this.forceUpdate();
  240. }, 1);
  241. nodeModel.ports.output.connection!.connectTo(input.connection!);
  242. this.props.globalState.onRebuildRequiredObservable.notifyObservers();
  243. }
  244. }
  245. this.forceUpdate();
  246. return;
  247. }
  248. e.link.addListener({
  249. sourcePortChanged: () => {
  250. },
  251. targetPortChanged: () => {
  252. // Link is created with a target port
  253. var link = DefaultPortModel.SortInputOutput(e.link.sourcePort as DefaultPortModel, e.link.targetPort as DefaultPortModel);
  254. if (link) {
  255. if (link.output.connection && link.input.connection) {
  256. // Disconnect previous connection
  257. for (var key in link.input.links) {
  258. let other = link.input.links[key];
  259. if ((other.getSourcePort() as DefaultPortModel).connection !== (link.output as DefaultPortModel).connection &&
  260. (other.getTargetPort() as DefaultPortModel).connection !== (link.output as DefaultPortModel).connection
  261. ) {
  262. other.remove();
  263. }
  264. }
  265. try {
  266. link.output.connection.connectTo(link.input.connection);
  267. }
  268. catch (err) {
  269. link.output.remove();
  270. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry(err, true));
  271. this.props.globalState.onErrorMessageDialogRequiredObservable.notifyObservers(err);
  272. }
  273. this.forceUpdate();
  274. }
  275. if (this.props.globalState.nodeMaterial) {
  276. this.buildMaterial();
  277. }
  278. }
  279. }
  280. })
  281. }
  282. });
  283. // Load graph of nodes from the material
  284. if (this.props.globalState.nodeMaterial) {
  285. var material = this.props.globalState.nodeMaterial;
  286. material._vertexOutputNodes.forEach((n: any) => {
  287. this.createNodeFromObject({ nodeMaterialBlock: n });
  288. });
  289. material._fragmentOutputNodes.forEach((n: any) => {
  290. this.createNodeFromObject({ nodeMaterialBlock: n });
  291. });
  292. material.attachedBlocks.forEach((n: any) => {
  293. this.createNodeFromObject({ nodeMaterialBlock: n });
  294. });
  295. }
  296. // load model into engine
  297. setTimeout(() => {
  298. if (this._toAdd) {
  299. this._model.addAll(...this._toAdd);
  300. }
  301. this._toAdd = null;
  302. this._engine.setDiagramModel(this._model);
  303. this.forceUpdate();
  304. this.reOrganize(locations);
  305. }, needToWait ? 500 : 1);
  306. }
  307. reOrganize(locations: Nullable<INodeLocationInfo[]> = null) {
  308. if (!locations) {
  309. let nodes = GraphHelper.DistributeGraph(this._model);
  310. nodes.forEach(node => {
  311. for (var nodeName in this._model.nodes) {
  312. let modelNode = this._model.nodes[nodeName];
  313. if (modelNode.id === node.id) {
  314. modelNode.setPosition(node.x - node.width / 2, node.y - node.height / 2);
  315. return;
  316. }
  317. }
  318. });
  319. } else {
  320. for (var location of locations) {
  321. for (var node of this._nodes) {
  322. if (node.block && node.block.uniqueId === location.blockId) {
  323. node.setPosition(location.x, location.y);
  324. break;
  325. }
  326. }
  327. }
  328. }
  329. this._engine.repaintCanvas();
  330. }
  331. onPointerDown(evt: React.PointerEvent<HTMLDivElement>) {
  332. this._startX = evt.clientX;
  333. this._moveInProgress = true;
  334. evt.currentTarget.setPointerCapture(evt.pointerId);
  335. }
  336. onPointerUp(evt: React.PointerEvent<HTMLDivElement>) {
  337. this._moveInProgress = false;
  338. evt.currentTarget.releasePointerCapture(evt.pointerId);
  339. }
  340. resizeColumns(evt: React.PointerEvent<HTMLDivElement>, forLeft = true) {
  341. if (!this._moveInProgress) {
  342. return;
  343. }
  344. const deltaX = evt.clientX - this._startX;
  345. const rootElement = evt.currentTarget.ownerDocument!.getElementById("node-editor-graph-root") as HTMLDivElement;
  346. if (forLeft) {
  347. this._leftWidth += deltaX;
  348. this._leftWidth = Math.max(150, Math.min(400, this._leftWidth));
  349. DataStorage.StoreNumber("LeftWidth", this._leftWidth);
  350. } else {
  351. this._rightWidth -= deltaX;
  352. this._rightWidth = Math.max(250, Math.min(500, this._rightWidth));
  353. DataStorage.StoreNumber("RightWidth", this._rightWidth);
  354. rootElement.ownerDocument!.getElementById("preview")!.style.height = this._rightWidth + "px";
  355. }
  356. rootElement.style.gridTemplateColumns = this.buildColumnLayout();
  357. this._startX = evt.clientX;
  358. }
  359. buildColumnLayout() {
  360. return `${this._leftWidth}px 4px calc(100% - ${this._leftWidth + 8 + this._rightWidth}px) 4px ${this._rightWidth}px`;
  361. }
  362. emitNewBlock(event: React.DragEvent<HTMLDivElement>) {
  363. var data = event.dataTransfer.getData("babylonjs-material-node") as string;
  364. let nodeModel: Nullable<DefaultNodeModel> = null;
  365. if (data.indexOf("Block") === -1) {
  366. nodeModel = this.addValueNode(data);
  367. } else {
  368. let block = BlockTools.GetBlockFromString(data);
  369. if (block) {
  370. nodeModel = this.createNodeFromObject({ nodeMaterialBlock: block });
  371. }
  372. };
  373. if (nodeModel) {
  374. const zoomLevel = this._engine.diagramModel.getZoomLevel() / 100.0;
  375. let x = (event.clientX - event.currentTarget.offsetLeft - this._engine.diagramModel.getOffsetX() - this.NodeWidth) / zoomLevel;
  376. let y = (event.clientY - event.currentTarget.offsetTop - this._engine.diagramModel.getOffsetY() - 20) / zoomLevel;
  377. nodeModel.setPosition(x, y);
  378. }
  379. this.forceUpdate();
  380. }
  381. render() {
  382. return (
  383. <Portal globalState={this.props.globalState}>
  384. <div id="node-editor-graph-root" style={
  385. {
  386. gridTemplateColumns: this.buildColumnLayout()
  387. }
  388. }>
  389. {/* Node creation menu */}
  390. <NodeListComponent globalState={this.props.globalState} />
  391. <div id="leftGrab"
  392. onPointerDown={evt => this.onPointerDown(evt)}
  393. onPointerUp={evt => this.onPointerUp(evt)}
  394. onPointerMove={evt => this.resizeColumns(evt)}
  395. ></div>
  396. {/* The node graph diagram */}
  397. <div className="diagram-container"
  398. onDrop={event => {
  399. this.emitNewBlock(event);
  400. }}
  401. onDragOver={event => {
  402. event.preventDefault();
  403. }}
  404. >
  405. <DiagramWidget className="diagram" deleteKeys={[46]} ref={"test"}
  406. allowLooseLinks={false}
  407. inverseZoom={true}
  408. diagramEngine={this._engine}
  409. maxNumberPointsPerLink={0} />
  410. </div>
  411. <div id="rightGrab"
  412. onPointerDown={evt => this.onPointerDown(evt)}
  413. onPointerUp={evt => this.onPointerUp(evt)}
  414. onPointerMove={evt => this.resizeColumns(evt, false)}
  415. ></div>
  416. {/* Property tab */}
  417. <div className="right-panel">
  418. <PropertyTabComponent globalState={this.props.globalState} />
  419. <PreviewMeshControlComponent globalState={this.props.globalState} />
  420. <div id="preview" style={{height: this._rightWidth + "px"}}>
  421. <canvas id="preview-canvas"/>
  422. </div>
  423. </div>
  424. <LogComponent globalState={this.props.globalState} />
  425. </div>
  426. <MessageDialogComponent globalState={this.props.globalState} />
  427. </Portal>
  428. );
  429. }
  430. }