Spaces:
Running
Running
File size: 60,901 Bytes
254b5bb |
1 |
var sceneScaffolder=pc.createScript("sceneScaffolder");sceneScaffolder.prototype.initialize=function(){var e=this.app,t=e.root.findByName("Camera");t&&t.destroy();var o=e.root.findByName("Light");o&&o.destroy();var a=new pc.Entity("SurgeonCamera");a.addComponent("camera",{clearColor:new pc.Color(.95,.98,1),nearClip:.1,farClip:100,fov:60}),a.setPosition(0,1.7,6.5),a.addComponent("script"),a.script.create("cameraController"),a.script.create("interactionController"),e.root.addChild(a),this.createCrosshairUI(e);var n=new pc.Entity("MainSurgicalLight");n.addComponent("light",{type:"spot",color:new pc.Color(1,.98,.92),intensity:3,range:15,innerConeAngle:15,outerConeAngle:35,castShadows:!0,shadowBias:.1,shadowDistance:20,shadowResolution:2048}),n.addComponent("render",{type:"box"}),n.setLocalScale(.5,.2,.5),n.addComponent("collision",{type:"box"}),n.addComponent("rigidbody",{type:"static"}),n.setPosition(0,4,0),n.setEulerAngles(90,0,0),e.root.addChild(n);var d=new pc.Entity("SecondarySurgicalLight");d.addComponent("light",{type:"spot",color:new pc.Color(1,.98,.92),intensity:2.5,range:12,innerConeAngle:20,outerConeAngle:40,castShadows:!0,shadowBias:.1}),d.setPosition(-1.5,3.8,-.5),d.setEulerAngles(75,15,0),e.root.addChild(d);var i=new pc.Entity("AmbientRoomLight");i.addComponent("light",{type:"directional",color:new pc.Color(.9,.95,1),intensity:.4,castShadows:!1}),i.setEulerAngles(30,45,0),e.root.addChild(i);var s=new pc.Entity("SterileFloor"),r=new pc.StandardMaterial;r.diffuse=new pc.Color(.92,.95,.98),r.metalness=.1,r.gloss=.8,r.useMetalness=!0,r.update(),s.addComponent("render",{type:"plane",material:r,receiveShadows:!0,castShadows:!1}),s.setLocalScale(20,1,15),e.root.addChild(s),this.createWall(e,"BackWall",0,2.5,-7.5,20,5,.2,new pc.Color(.95,.97,1)),this.createWall(e,"FrontWall",0,2.5,7.5,20,5,.2,new pc.Color(.95,.97,1)),this.createWall(e,"LeftWall",-10,2.5,0,.2,5,15,new pc.Color(.95,.97,1)),this.createWall(e,"RightWall",10,2.5,0,.2,5,15,new pc.Color(.95,.97,1));var l=new pc.Entity("OperatingTableBase"),c=new pc.StandardMaterial;c.diffuse=new pc.Color(.8,.8,.85),c.metalness=.7,c.gloss=.6,c.useMetalness=!0,c.update(),l.addComponent("render",{type:"cylinder",material:c,castShadows:!0,receiveShadows:!0}),l.setLocalScale(.8,.7,.8),l.setPosition(0,.35,0),e.root.addChild(l);var p=new pc.Entity("OperatingTableSurface"),w=new pc.StandardMaterial;w.diffuse=new pc.Color(.9,.92,.95),w.metalness=.2,w.gloss=.9,w.useMetalness=!0,w.update(),p.addComponent("render",{type:"box",material:w,castShadows:!0,receiveShadows:!0}),p.setLocalScale(2.2,.1,.8),p.setPosition(0,.75,0),p.addComponent("collision",{type:"box",halfExtents:new pc.Vec3(1.1,.05,.4)}),p.addComponent("rigidbody",{type:"static"}),e.root.addChild(p);var C=new pc.Entity("AnesthesiaMachine"),h=new pc.StandardMaterial;h.diffuse=new pc.Color(.7,.75,.8),h.metalness=.8,h.useMetalness=!0,h.update(),C.addComponent("render",{type:"box",material:h,castShadows:!0,receiveShadows:!0}),C.setLocalScale(1.2,1.8,.8),C.setPosition(-4,.9,2),e.root.addChild(C);var m=new pc.Entity("InstrumentTable"),y=new pc.StandardMaterial;y.diffuse=new pc.Color(.85,.87,.9),y.metalness=.6,y.gloss=.8,y.useMetalness=!0,y.update(),m.addComponent("render",{type:"box",material:y,castShadows:!0,receiveShadows:!0}),m.setLocalScale(1.5,1.2,.8),m.setPosition(3,.6,-1),e.root.addChild(m);var S=new pc.Entity("XRayViewer"),u=new pc.StandardMaterial;u.diffuse=new pc.Color(.1,.1,.12),u.metalness=.9,u.useMetalness=!0,u.update(),S.addComponent("render",{type:"box",material:u,castShadows:!0,receiveShadows:!0}),S.setLocalScale(1.8,1.2,.1),S.setPosition(-4,2.5,-6),e.root.addChild(S);var g=new pc.Entity("XRayScreen"),f=new pc.StandardMaterial;f.diffuse=new pc.Color(.9,.95,1),f.emissive=new pc.Color(.3,.35,.4),f.update(),g.addComponent("render",{type:"box",material:f,castShadows:!1,receiveShadows:!1}),g.addComponent("collision",{type:"box"}),g.addComponent("rigidbody",{type:"static"}),g.setLocalScale(1.6,1,.05),g.setPosition(-4,2.5,-5.9),e.root.addChild(g);var v=new pc.Entity("SurgicalLightArm1"),M=new pc.StandardMaterial;M.diffuse=new pc.Color(.9,.9,.92),M.metalness=.8,M.useMetalness=!0,M.update(),v.addComponent("render",{type:"cylinder",material:M,castShadows:!0,receiveShadows:!0}),v.setLocalScale(.15,2,.15),v.setPosition(0,3,0),e.root.addChild(v);var E=new pc.Entity("PatientBody"),b=new pc.StandardMaterial;b.diffuse=new pc.Color(.95,.85,.75),b.metalness=.1,b.gloss=.2,b.useMetalness=!0,b.update(),E.addComponent("render",{type:"box",material:b,castShadows:!0,receiveShadows:!0}),E.addComponent("collision",{type:"box"}),E.addComponent("rigidbody",{type:"static"}),E.setLocalScale(.6,.3,1.8),E.setPosition(0,.95,0),e.root.addChild(E);var L=new pc.Entity("SurgicalDrape"),x=new pc.StandardMaterial;x.diffuse=new pc.Color(.8,.9,.95),x.metalness=0,x.gloss=.1,x.update(),L.addComponent("render",{type:"box",material:x,castShadows:!0,receiveShadows:!0}),L.setLocalScale(.8,.05,2),L.setPosition(0,1.15,0),e.root.addChild(L);var P=new pc.Entity("CArmXRayMachine"),A=new pc.StandardMaterial;A.diffuse=new pc.Color(.75,.78,.82),A.metalness=.7,A.useMetalness=!0,A.update(),P.addComponent("render",{type:"box",material:A,castShadows:!0,receiveShadows:!0}),P.setLocalScale(1,2.2,1.5),P.setPosition(5,1.1,3),P.addComponent("collision",{type:"box",halfExtents:new pc.Vec3(.5,1.1,.75)}),P.addComponent("rigidbody",{type:"static"}),e.root.addChild(P);var B=new pc.Entity("PowerToolsStation"),V=new pc.StandardMaterial;V.diffuse=new pc.Color(.6,.65,.7),V.metalness=.8,V.useMetalness=!0,V.update(),B.addComponent("render",{type:"box",material:V,castShadows:!0,receiveShadows:!0}),B.setLocalScale(.8,1.5,.6),B.setPosition(-3.5,.75,-2.5),e.root.addChild(B);var T=new pc.Entity("BoneCementMixer"),O=new pc.StandardMaterial;O.diffuse=new pc.Color(.85,.85,.88),O.metalness=.6,O.useMetalness=!0,O.update(),T.addComponent("render",{type:"cylinder",material:O,castShadows:!0,receiveShadows:!0}),T.setLocalScale(.4,.8,.4),T.setPosition(2.5,.4,2.5),e.root.addChild(T),this.createVitalSignsMonitor(e,new pc.Vec3(-2,0,3)),console.log("Orthopaedic Operating Theatre scaffolded successfully!"),console.log("Orthopaedic Operating Theatre scaffolded successfully!"),console.log("Environment includes:"),console.log("- Sterile room with clinical lighting"),console.log("- Central operating table with patient"),console.log("- Anesthesia machine and monitoring equipment"),console.log("- X-ray viewer and C-arm machine"),console.log("- Surgical instrument tables"),console.log("- Orthopaedic-specific equipment (drills, cement mixer)"),console.log("- Proper surgical lighting setup")},sceneScaffolder.prototype.createWall=function(e,t,o,a,n,d,i,s,r){var l=new pc.Entity(t),c=new pc.StandardMaterial;c.diffuse=r,c.metalness=.1,c.gloss=.3,c.useMetalness=!0,c.update(),l.addComponent("render",{type:"box",material:c,castShadows:!1,receiveShadows:!0}),l.setPosition(o,a,n),l.setLocalScale(d,i,s),e.root.addChild(l)},sceneScaffolder.prototype.createVitalSignsMonitor=function(e,t){var o=new pc.Entity("VitalSignsMonitor");o.setPosition(t);var a=new pc.Entity("MonitorCartBody"),n=new pc.StandardMaterial;n.diffuse=new pc.Color(.8,.82,.85),n.useMetalness=!0,n.metalness=.4,n.gloss=.5,n.update(),a.addComponent("render",{type:"box",material:n}),a.setLocalScale(.6,1,.5),a.setLocalPosition(0,.5,0),a.addComponent("collision",{type:"box"}),a.addComponent("rigidbody",{type:"static"}),o.addChild(a);var d=new pc.Entity("MonitorScreen"),i=new pc.StandardMaterial;i.diffuse.set(.05,.05,.1),i.emissive.set(.02,.02,.05),i.update(),d.addComponent("render",{type:"box",material:i}),d.setLocalScale(.58,.45,.03),d.setLocalPosition(0,.7,.27),d.addComponent("collision",{type:"box"}),d.addComponent("rigidbody",{type:"static"}),o.addChild(d);var s=new pc.Entity("MonitorBase");return s.addComponent("render",{type:"box",material:n}),s.setLocalScale(.7,.05,.7),s.setLocalPosition(0,.025,0),o.addChild(s),e.root.addChild(o),o},sceneScaffolder.prototype.createCrosshairUI=function(e){var t=new pc.Entity("UIScreen");t.addComponent("screen",{referenceResolution:new pc.Vec2(1280,720),scaleBlend:.5,scaleMode:pc.SCALEMODE_BLEND,screenSpace:!0}),e.root.addChild(t);var o=new pc.Entity("CrosshairOutline");o.addComponent("image",{type:pc.ELEMENTTYPE_IMAGE,anchor:new pc.Vec4(.5,.5,.5,.5),pivot:new pc.Vec2(.5,.5),width:6,height:6,color:new pc.Color(0,0,0,.5)}),t.addChild(o);var a=new pc.Entity("CrosshairDot");a.addComponent("image",{type:pc.ELEMENTTYPE_IMAGE,anchor:new pc.Vec4(.5,.5,.5,.5),pivot:new pc.Vec2(.5,.5),width:2,height:2,color:new pc.Color(1,1,1,.8)}),t.addChild(a),console.log("Compound Crosshair UI created.")};var CameraController=pc.createScript("cameraController");CameraController.attributes.add("movementSpeed",{type:"number",default:5,title:"Movement Speed"}),CameraController.attributes.add("keyboardRotationSpeed",{type:"number",default:90,title:"Keyboard Rotation Speed"}),CameraController.attributes.add("pitchLimit",{type:"number",default:89,title:"Pitch Angle Limit"}),CameraController.attributes.add("useControlManager",{type:"boolean",default:!0,title:"Use Control Manager"}),CameraController.prototype.initialize=function(){console.log("CameraController: Initializing..."),this.eulers=new pc.Vec3;var e=this.entity.getEulerAngles();if(this.eulers.set(e.x,e.y,e.z),this.pitch=this.eulers.x,this.yaw=this.eulers.y,this.moveDirection=new pc.Vec3,this.controlManager=null,this.useControlManager){const e=this.app.root.findComponent("script",(e=>e.has("controlManager")));e?(this.controlManager=e.entity.script.controlManager,console.log("CameraController: Using Control Manager")):(console.warn("CameraController: Control Manager not found, using direct input"),this.useControlManager=!1)}console.log("CameraController initialized. Controls:"),console.log("- WASD: Move"),console.log("- Q/E: Rotate"),console.log("- Arrow Keys: Look up/down")},CameraController.prototype.update=function(e){this.shouldProcessInput()&&(this.processMovement(e),this.processRotation(e),this.entity.setLocalEulerAngles(this.pitch,this.yaw,0))},CameraController.prototype.shouldProcessInput=function(){return!this.useControlManager||!this.controlManager||!this.controlManager.blockedKeys.has("W")},CameraController.prototype.processMovement=function(e){var t=this.app,o=this.movementSpeed,r=this.entity.forward,i=this.entity.right,a=0,n=0;if(this.useControlManager&&this.controlManager?(this.controlManager.isKeyActive("W")&&(n-=1),this.controlManager.isKeyActive("S")&&(n+=1),this.controlManager.isKeyActive("A")&&(a-=1),this.controlManager.isKeyActive("D")&&(a+=1)):(t.keyboard.isPressed(pc.KEY_W)&&(n-=1),t.keyboard.isPressed(pc.KEY_S)&&(n+=1),t.keyboard.isPressed(pc.KEY_A)&&(a-=1),t.keyboard.isPressed(pc.KEY_D)&&(a+=1)),0!==a||0!==n){this.moveDirection.set(0,0,0);var s=r.clone().mulScalar(-n),l=i.clone().mulScalar(a);this.moveDirection.add(s).add(l),this.moveDirection.lengthSq()>0&&(this.moveDirection.normalize().mulScalar(o*e),this.entity.translateLocal(this.moveDirection))}},CameraController.prototype.processRotation=function(e){var t=this.app,o=0;this.useControlManager&&this.controlManager?(this.controlManager.isKeyActive("Q")&&(o=1),this.controlManager.isKeyActive("E")&&(o=-1)):(t.keyboard.isPressed(pc.KEY_Q)&&(o=1),t.keyboard.isPressed(pc.KEY_E)&&(o=-1)),this.yaw+=o*this.keyboardRotationSpeed*e;var r=0;this.useControlManager&&this.controlManager?(this.controlManager.isKeyActive("UP")&&(r=-1),this.controlManager.isKeyActive("DOWN")&&(r=1)):(t.keyboard.isPressed(pc.KEY_UP)&&(r=-1),t.keyboard.isPressed(pc.KEY_DOWN)&&(r=1)),this.pitch+=r*this.keyboardRotationSpeed*e,this.pitch=pc.math.clamp(this.pitch,-this.pitchLimit,this.pitchLimit)};var SceneScaffolder=pc.createScript("sceneScaffolder");SceneScaffolder.prototype.initialize=function(){var e=this.app,a=e.root.findByName("Camera");a&&a.destroy();var o=e.root.findByName("Light");o&&o.destroy();var t=new pc.Entity("MyControllableCamera");t.addComponent("camera",{clearColor:new pc.Color(.1,.1,.1),nearClip:.1,farClip:1e3,fov:45}),t.setPosition(0,1.6,5),t.addComponent("script"),t.script.create("cameraController"),e.root.addChild(t);var n=new pc.Entity("MyLight");n.addComponent("light",{type:"directional",color:new pc.Color(1,1,1),intensity:1,castShadows:!0,shadowBias:.2,shadowDistance:50,normalOffsetBias:.05,shadowResolution:2048}),n.setEulerAngles(45,30,0),e.root.addChild(n);var r=new pc.Entity("GroundPlane"),d=new pc.StandardMaterial;d.diffuse=new pc.Color(.5,.5,.5),d.update(),r.addComponent("render",{type:"plane",material:d,castShadows:!1,receiveShadows:!0}),r.setLocalScale(50,1,50),e.root.addChild(r);var i=new pc.Entity("MyCube"),s=new pc.StandardMaterial;s.diffuse=new pc.Color(1,0,0),s.shininess=50,s.update(),i.addComponent("render",{type:"box",material:s,castShadows:!0,receiveShadows:!0}),i.setPosition(0,1,0),e.root.addChild(i);var l=new pc.Entity("MySphere"),c=new pc.StandardMaterial;c.diffuse=new pc.Color(0,0,1),c.shininess=70,c.metalness=.3,c.useMetalness=!0,c.update(),l.addComponent("render",{type:"sphere",material:c,castShadows:!0,receiveShadows:!0}),l.setPosition(3,1.5,2),e.root.addChild(l),console.log("Controllable 3D environment scaffolded from code!")};var OrthopaedicTheatreScaffolder=pc.createScript("orthopaedicTheatreScaffolder");OrthopaedicTheatreScaffolder.prototype.initialize=function(){var e=this.app,a=e.root.findByName("Camera");a&&a.destroy();var t=e.root.findByName("Light");t&&t.destroy();var o=new pc.Entity("SurgeonCamera");o.addComponent("camera",{clearColor:new pc.Color(.95,.98,1),nearClip:.1,farClip:100,fov:60}),o.setPosition(0,1.7,8),o.addComponent("script"),o.script.create("cameraController"),e.root.addChild(o);var n=new pc.Entity("MainSurgicalLight");n.addComponent("light",{type:"spot",color:new pc.Color(1,.98,.92),intensity:3,range:15,innerConeAngle:15,outerConeAngle:35,castShadows:!0,shadowBias:.1,shadowDistance:20,shadowResolution:2048}),n.setPosition(0,4,0),n.setEulerAngles(90,0,0),e.root.addChild(n);var s=new pc.Entity("SecondarySurgicalLight");s.addComponent("light",{type:"spot",color:new pc.Color(1,.98,.92),intensity:2.5,range:12,innerConeAngle:20,outerConeAngle:40,castShadows:!0,shadowBias:.1}),s.setPosition(-1.5,3.8,-.5),s.setEulerAngles(75,15,0),e.root.addChild(s);var r=new pc.Entity("AmbientRoomLight");r.addComponent("light",{type:"directional",color:new pc.Color(.9,.95,1),intensity:.4,castShadows:!1}),r.setEulerAngles(30,45,0),e.root.addChild(r);var d=new pc.Entity("SterileFloor"),l=new pc.StandardMaterial;l.diffuse=new pc.Color(.92,.95,.98),l.metalness=.1,l.gloss=.8,l.useMetalness=!0,l.update(),d.addComponent("render",{type:"plane",material:l,receiveShadows:!0,castShadows:!1}),d.setLocalScale(20,1,15),e.root.addChild(d),this.createWall(e,"BackWall",0,2.5,-7.5,20,5,.2,new pc.Color(.95,.97,1)),this.createWall(e,"FrontWall",0,2.5,7.5,20,5,.2,new pc.Color(.95,.97,1)),this.createWall(e,"LeftWall",-10,2.5,0,.2,5,15,new pc.Color(.95,.97,1)),this.createWall(e,"RightWall",10,2.5,0,.2,5,15,new pc.Color(.95,.97,1));var i=new pc.Entity("OperatingTableBase"),c=new pc.StandardMaterial;c.diffuse=new pc.Color(.8,.8,.85),c.metalness=.7,c.gloss=.6,c.useMetalness=!0,c.update(),i.addComponent("render",{type:"cylinder",material:c,castShadows:!0,receiveShadows:!0}),i.setLocalScale(.8,.7,.8),i.setPosition(0,.35,0),e.root.addChild(i);var p=new pc.Entity("OperatingTableSurface"),w=new pc.StandardMaterial;w.diffuse=new pc.Color(.9,.92,.95),w.metalness=.2,w.gloss=.9,w.useMetalness=!0,w.update(),p.addComponent("render",{type:"box",material:w,castShadows:!0,receiveShadows:!0}),p.setLocalScale(2.2,.1,.8),p.setPosition(0,.75,0),e.root.addChild(p);var h=new pc.Entity("AnesthesiaMachine"),S=new pc.StandardMaterial;S.diffuse=new pc.Color(.7,.75,.8),S.metalness=.8,S.useMetalness=!0,S.update(),h.addComponent("render",{type:"box",material:S,castShadows:!0,receiveShadows:!0}),h.setLocalScale(1.2,1.8,.8),h.setPosition(-4,.9,2),e.root.addChild(h);var C=new pc.Entity("InstrumentTable"),m=new pc.StandardMaterial;m.diffuse=new pc.Color(.85,.87,.9),m.metalness=.6,m.gloss=.8,m.useMetalness=!0,m.update(),C.addComponent("render",{type:"box",material:m,castShadows:!0,receiveShadows:!0}),C.setLocalScale(1.5,1.2,.8),C.setPosition(3,.6,-1),e.root.addChild(C);var u=new pc.Entity("XRayViewer"),y=new pc.StandardMaterial;y.diffuse=new pc.Color(.1,.1,.12),y.metalness=.9,y.useMetalness=!0,y.update(),u.addComponent("render",{type:"box",material:y,castShadows:!0,receiveShadows:!0}),u.setLocalScale(1.8,1.2,.1),u.setPosition(-4,2.5,-6),e.root.addChild(u);var g=new pc.Entity("XRayScreen"),f=new pc.StandardMaterial;f.diffuse=new pc.Color(.9,.95,1),f.emissive=new pc.Color(.3,.35,.4),f.update(),g.addComponent("render",{type:"box",material:f,castShadows:!1,receiveShadows:!1}),g.setLocalScale(1.6,1,.05),g.setPosition(-4,2.5,-5.9),e.root.addChild(g);var v=new pc.Entity("SurgicalLightArm1"),M=new pc.StandardMaterial;M.diffuse=new pc.Color(.9,.9,.92),M.metalness=.8,M.useMetalness=!0,M.update(),v.addComponent("render",{type:"cylinder",material:M,castShadows:!0,receiveShadows:!0}),v.setLocalScale(.15,2,.15),v.setPosition(0,3,0),e.root.addChild(v);var E=new pc.Entity("PatientBody"),L=new pc.StandardMaterial;L.diffuse=new pc.Color(.95,.85,.75),L.metalness=.1,L.gloss=.2,L.useMetalness=!0,L.update(),E.addComponent("render",{type:"box",material:L,castShadows:!0,receiveShadows:!0}),E.setLocalScale(.6,.3,1.8),E.setPosition(0,.95,0),e.root.addChild(E);var P=new pc.Entity("SurgicalDrape"),b=new pc.StandardMaterial;b.diffuse=new pc.Color(.8,.9,.95),b.metalness=0,b.gloss=.1,b.update(),P.addComponent("render",{type:"box",material:b,castShadows:!0,receiveShadows:!0}),P.setLocalScale(.8,.05,2),P.setPosition(0,1.15,0),e.root.addChild(P);var x=new pc.Entity("CArmXRayMachine"),A=new pc.StandardMaterial;A.diffuse=new pc.Color(.75,.78,.82),A.metalness=.7,A.useMetalness=!0,A.update(),x.addComponent("render",{type:"box",material:A,castShadows:!0,receiveShadows:!0}),x.setLocalScale(1,2.2,1.5),x.setPosition(5,1.1,3),e.root.addChild(x);var T=new pc.Entity("PowerToolsStation"),W=new pc.StandardMaterial;W.diffuse=new pc.Color(.6,.65,.7),W.metalness=.8,W.useMetalness=!0,W.update(),T.addComponent("render",{type:"box",material:W,castShadows:!0,receiveShadows:!0}),T.setLocalScale(.8,1.5,.6),T.setPosition(-3.5,.75,-2.5),e.root.addChild(T);var B=new pc.Entity("BoneCementMixer"),O=new pc.StandardMaterial;O.diffuse=new pc.Color(.85,.85,.88),O.metalness=.6,O.useMetalness=!0,O.update(),B.addComponent("render",{type:"cylinder",material:O,castShadows:!0,receiveShadows:!0}),B.setLocalScale(.4,.8,.4),B.setPosition(2.5,.4,2.5),e.root.addChild(B),console.log("Orthopaedic Operating Theatre scaffolded successfully!"),console.log("Environment includes:"),console.log("- Sterile room with clinical lighting"),console.log("- Central operating table with patient"),console.log("- Anesthesia machine and monitoring equipment"),console.log("- X-ray viewer and C-arm machine"),console.log("- Surgical instrument tables"),console.log("- Orthopaedic-specific equipment (drills, cement mixer)"),console.log("- Proper surgical lighting setup")},OrthopaedicTheatreScaffolder.prototype.createWall=function(e,a,t,o,n,s,r,d,l){var i=new pc.Entity(a),c=new pc.StandardMaterial;c.diffuse=l,c.metalness=.1,c.gloss=.3,c.useMetalness=!0,c.update(),i.addComponent("render",{type:"box",material:c,castShadows:!1,receiveShadows:!0}),i.setPosition(t,o,n),i.setLocalScale(s,r,d),e.root.addChild(i)};var InteractionController=pc.createScript("interactionController");InteractionController.attributes.add("interactionDistance",{type:"number",default:5,title:"Interaction Distance"}),InteractionController.attributes.add("highlightColor",{type:"rgba",default:[.4,.4,0,1],title:"Highlight Color (Emissive)"}),InteractionController.prototype.initialize=function(){this.highlightedEntity=null,this.originalEmissive=new pc.Color;const t=this.app.scene.layers.getLayerById(pc.LAYERID_IMMEDIATE),i=this.entity.camera,e=i.layers;-1===e.indexOf(t.id)&&(i.layers=e.concat(t.id)),console.log("Interaction Controller is active. Look at an object to highlight it, press 'F' to interact.")},InteractionController.prototype.update=function(t){if("undefined"!=typeof Ammo){var i=this.entity.getPosition(),e=(new pc.Vec3).copy(this.entity.forward).mulScalar(this.interactionDistance).add(i),n=this.app.systems.rigidbody.raycastFirst(i,e),o=n?n.entity:null;o!==this.highlightedEntity&&(this.highlightedEntity&&this.setHighlight(this.highlightedEntity,!1),o&&this.setHighlight(o,!0),this.highlightedEntity=o),this.app.keyboard.wasPressed(pc.KEY_F)&&this.highlightedEntity&&this.interactWith(this.highlightedEntity)}},InteractionController.prototype.interactWith=function(t){console.log("Interacting with:",t.name);var i=t;if(t.parent&&"VitalSignsMonitor"===t.parent.name&&(i=t.parent),"VitalSignsMonitor"===i.name){var e=i.findByName("MonitorScreen");if(e){void 0===e.isOn&&(e.isOn=!1),e.isOn=!e.isOn;var n=e.render.material;n.emissive.set(e.isOn?.5:0,e.isOn?.8:0,e.isOn?1:0),n.update(),console.log("Monitor screen state set to:",e.isOn?"ON":"OFF")}}else if("PatientBody"===t.name){var o=this.app.root.findByName("SurgicalDrape");o&&(o.enabled=!o.enabled,console.log("Surgical drape visibility set to:",o.enabled))}else if("MainSurgicalLight"===t.name)void 0===t.isAdjusted&&(t.isAdjusted=!1),t.isAdjusted=!t.isAdjusted,t.isAdjusted?(t.setEulerAngles(75,20,0),console.log("Surgical light adjusted.")):(t.setEulerAngles(90,0,0),console.log("Surgical light reset."));else if("XRayScreen"===t.name){void 0===t.colorIndex&&(t.colorIndex=0);var r=[new pc.Color(.9,.95,1),new pc.Color(.9,1,.9),new pc.Color(1,.9,.9)];t.colorIndex=(t.colorIndex+1)%r.length;var s=t.render.material;s.diffuse.copy(r[t.colorIndex]),s.update(),console.log("X-Ray screen color changed to index:",t.colorIndex)}},InteractionController.prototype.setHighlight=function(t,i){if((!t||"MonitorScreen"!==t.name)&&t&&t.render&&t.render.material){var e=t.render.material;i?(this.originalEmissive.copy(e.emissive),e.emissive.set(this.highlightColor.r,this.highlightColor.g,this.highlightColor.b)):e.emissive.copy(this.originalEmissive),e.update()}};var GameManager=pc.createScript("gameManager");GameManager.attributes.add("gameData",{type:"asset",assetType:"text",title:"Game Data JSON"}),GameManager.prototype.initialize=function(){this.storyData=null,this.currentLocation="tavern",this.currentRoom="start",this.isUiReady=!1,this.app.on("ui:choiceMade",this.onChoiceMade,this),this.app.on("ui:ready",this.onUiReady,this),this.gameData&&this.gameData.resource?(this.storyData=JSON.parse(this.gameData.resource),console.log("GameManager: Data loaded and parsed."),this.isUiReady&&this.displayCurrentState()):console.error("GameManager: Game Data JSON asset is not linked or has not loaded yet.")},GameManager.prototype.onUiReady=function(){console.log("GameManager: Received 'ui:ready' event."),this.isUiReady=!0,this.storyData&&this.displayCurrentState()},GameManager.prototype.displayCurrentState=function(){if(this.storyData&&this.isUiReady){var t=this.storyData[this.currentLocation][this.currentRoom];t?(console.log("GameManager: Firing 'story:display' event for room:",this.currentRoom),this.app.fire("story:display",{description:t.description,choices:t.choices})):console.error("GameManager: Could not find room data for:",this.currentLocation,this.currentRoom)}},GameManager.prototype.onChoiceMade=function(t){if(this.storyData){var a=this.storyData[this.currentLocation][this.currentRoom].transitions[t];if(a){if(a.includes("_")){var e=a.split("_");this.currentLocation=e[0],this.currentRoom=e[1]}else this.currentRoom=a;this.displayCurrentState()}else console.error("GameManager: No transition found for choice:",t)}};var GameAutoLocationDatabase=pc.createScript("gameAutoLocationDatabase");GameAutoLocationDatabase.prototype.initialize=function(){},GameAutoLocationDatabase.prototype.update=function(a){};var SceneIntegrationManager=pc.createScript("sceneIntegrationManager");SceneIntegrationManager.attributes.add("integrationRules",{type:"json",schema:[{name:"tagMatch",type:"string",default:"interactive"},{name:"scriptToAdd",type:"string",default:"interactionController"},{name:"componentConfig",type:"json",default:{}}],array:!0,title:"Integration Rules"}),SceneIntegrationManager.prototype.initialize=function(){this.sceneTypes={MEDICAL:"medical",SCIFI:"scifi",FANTASY:"fantasy",CUSTOM:"custom"},this.currentSceneType=null,this.mappings=new Map,this.app.on("scene:loaded",this.onSceneLoaded,this),this.app.on("scene:analyze",this.analyzeScene,this),this.integrationRules&&0!==this.integrationRules.length||this.setupDefaultRules(),console.log("[Integration] Scene Integration Manager ready")},SceneIntegrationManager.prototype.setupDefaultRules=function(){this.integrationRules=[{tagMatch:"interactive",scriptToAdd:"dynamicInteraction",componentConfig:{interactionDistance:5}},{tagMatch:"character",scriptToAdd:"characterBehavior",componentConfig:{dialogueEnabled:!0}}]},SceneIntegrationManager.prototype.onSceneLoaded=function(e){switch(console.log("[Integration] Processing loaded scene..."),this.currentSceneType=this.detectSceneType(e),console.log(`[Integration] Detected scene type: ${this.currentSceneType}`),this.currentSceneType){case this.sceneTypes.MEDICAL:this.integrateMedicalScene(e);break;case this.sceneTypes.SCIFI:this.integrateSciFiScene(e);break;default:this.integrateGenericScene(e)}this.applyIntegrationRules(e),this.generateSceneReport(e)},SceneIntegrationManager.prototype.detectSceneType=function(e){const t=[],n=new Set,collectData=e=>{t.push(e.name.toLowerCase()),e.tags._list.forEach((e=>n.add(e.toLowerCase()))),e.children.forEach(collectData)};return e.children.forEach(collectData),t.some((e=>e.includes("patient")||e.includes("surgical")||e.includes("medical")))?this.sceneTypes.MEDICAL:n.has("alien")||n.has("robot")||n.has("spacecraft")?this.sceneTypes.SCIFI:this.sceneTypes.CUSTOM},SceneIntegrationManager.prototype.integrateSciFiScene=function(e){console.log("[Integration] Applying Sci-Fi scene integration...");e.findByTag("interactive").forEach((e=>{let t="default";e.tags._list.forEach((e=>{e.startsWith("ui_display_")&&(t=e.replace("ui_display_",""))})),this.mappings.set(e.name,{type:"interactive",interactionType:t,gameEvent:this.mapInteractionToGameEvent(t)}),this.addInteractionFeedback(e)}));e.findByTag("character").forEach((e=>{this.processSciFiCharacter(e)}))},SceneIntegrationManager.prototype.mapInteractionToGameEvent=function(e){return{toggle:"story:choice",button:"story:action",screen:"story:display",overlay:"ui:overlay",cursor:"ui:focus",window:"ui:window"}[e]||"interaction:generic"},SceneIntegrationManager.prototype.processSciFiCharacter=function(e){const t={name:e.name,role:null,background:null,skills:[],traits:[],equipment:[]};e.tags._list.forEach((e=>{e.startsWith("role_")?t.role=e.replace("role_",""):e.startsWith("background_")?t.background=e.replace("background_",""):e.startsWith("skill_")?t.skills.push(e.replace("skill_","")):e.startsWith("trait_")?t.traits.push(e.replace("trait_","")):e.startsWith("equipment_")&&t.equipment.push(e.replace("equipment_",""))})),this.mappings.set(e.name,{type:"character",data:t}),e.script||e.addComponent("script"),this.addCharacterController(e,t)},SceneIntegrationManager.prototype.addCharacterController=function(e,t){const n=pc.createScript("characterBehavior_"+e.name);n.prototype.initialize=function(){this.data=t,this.interactionDistance=3,this.player=this.app.root.findByName("SurgeonCamera")||this.app.root.findByName("player")},n.prototype.update=function(e){if(!this.player)return;this.entity.getPosition().distance(this.player.getPosition())<this.interactionDistance?this.nearPlayer||(this.nearPlayer=!0,this.app.fire("character:nearby",this.entity.name,this.data)):this.nearPlayer=!1},pc.registerScript(n,"characterBehavior_"+e.name),e.script.create("characterBehavior_"+e.name)},SceneIntegrationManager.prototype.addInteractionFeedback=function(e){if(!e.render)return;const t=e.render.material;t&&(e.originalEmissive=t.emissive.clone(),e.highlightColor=new pc.Color(.3,.3,.5))},SceneIntegrationManager.prototype.applyIntegrationRules=function(e){console.log("[Integration] Applying custom integration rules..."),this.integrationRules.forEach((t=>{e.findByTag(t.tagMatch).forEach((e=>{if(console.log(`[Integration] Applying rule to ${e.name}: ${t.scriptToAdd}`),e.script||e.addComponent("script"),pc.ScriptRegistry.get(t.scriptToAdd)){if(!e.script.has(t.scriptToAdd)){e.script.create(t.scriptToAdd,{attributes:t.componentConfig})}}else console.warn(`[Integration] Script '${t.scriptToAdd}' not found in registry`)}))}))},SceneIntegrationManager.prototype.generateSceneReport=function(e){const t={sceneType:this.currentSceneType,stats:{totalEntities:0,characters:[],interactives:[],unmappedEntities:[]},mappings:[]},processEntity=e=>{t.stats.totalEntities++;const n=this.mappings.get(e.name);n?(t.mappings.push({entity:e.name,mapping:n}),"character"===n.type?t.stats.characters.push(n.data):"interactive"===n.type&&t.stats.interactives.push({name:e.name,type:n.interactionType,event:n.gameEvent})):e.script&&e.script._scripts.length>0&&t.stats.unmappedEntities.push(e.name),e.children.forEach(processEntity)};return e.children.forEach(processEntity),console.log("[Integration] Scene Report:"),console.log("========================"),console.log(`Type: ${t.sceneType}`),console.log(`Total Entities: ${t.stats.totalEntities}`),console.log(`Characters: ${t.stats.characters.length}`),console.log(`Interactives: ${t.stats.interactives.length}`),console.log(`Unmapped: ${t.stats.unmappedEntities.length}`),console.log("========================"),this.lastReport=t,this.app.fire("scene:report",t),t},SceneIntegrationManager.prototype.getEntityMapping=function(e){return this.mappings.get(e)},SceneIntegrationManager.prototype.getMappingsByType=function(e){const t=[];return this.mappings.forEach(((n,a)=>{n.type===e&&t.push({entity:a,...n})})),t},SceneIntegrationManager.prototype.analyzeScene=function(){const e=this.app.root.findComponent("sceneLoader");return e&&e.currentSceneRoot?this.generateSceneReport(e.currentSceneRoot):null};var StorySceneBridge=pc.createScript("storySceneBridge");StorySceneBridge.attributes.add("sceneMapping",{type:"json",schema:[{name:"storyLocation",type:"string",default:"tavern"},{name:"sceneUrl",type:"string",default:""},{name:"sceneType",type:"string",default:"medical"}],array:!0,title:"Story Location to Scene Mapping"}),StorySceneBridge.prototype.initialize=function(){this.gameManager=null,this.sceneLoader=null,this.integrationManager=null,this.currentStoryLocation=null,this.interactionMappings=new Map,this.findRequiredComponents(),this.app.on("story:display",this.onStoryDisplay,this),this.app.on("ui:choiceMade",this.onChoiceMade,this),this.app.on("interaction:triggered",this.onSceneInteraction,this),this.app.on("character:nearby",this.onCharacterNearby,this),this.setupDebugCommands(),console.log("[Bridge] Story-Scene Bridge initialized")},StorySceneBridge.prototype.findRequiredComponents=function(){const e=this.app.root.findComponent("script",(e=>e.has("gameManager")));e&&(this.gameManager=e.entity.script.gameManager);const t=this.app.root.findComponent("script",(e=>e.has("sceneLoader")));t&&(this.sceneLoader=t.entity.script.sceneLoader);const n=this.app.root.findComponent("script",(e=>e.has("sceneIntegrationManager")));n&&(this.integrationManager=n.entity.script.sceneIntegrationManager)},StorySceneBridge.prototype.setupDebugCommands=function(){this.app.keyboard.on(pc.EVENT_KEYDOWN,(e=>{switch(e.key){case pc.KEY_I:this.showCurrentState();break;case pc.KEY_M:this.showMappings();break;case pc.KEY_T:this.testInteraction()}}))},StorySceneBridge.prototype.onStoryDisplay=function(e){if(this.gameManager){const e=this.gameManager.currentLocation;e!==this.currentStoryLocation&&(console.log(`[Bridge] Story location changed: ${this.currentStoryLocation} -> ${e}`),this.currentStoryLocation=e,this.checkSceneTransition(e))}this.mapChoicesToScene(e.choices)},StorySceneBridge.prototype.checkSceneTransition=function(e){const t=this.sceneMapping.find((t=>t.storyLocation===e));t?(console.log(`[Bridge] Loading scene for location: ${e}`),this.sceneLoader&&(this.currentSceneMapping=t,t.sceneUrl&&(this.sceneLoader.sceneSource="url",this.sceneLoader.sceneUrl=t.sceneUrl,this.sceneLoader.loadScene()))):console.log(`[Bridge] No scene mapping for location: ${e}`)},StorySceneBridge.prototype.mapChoicesToScene=function(e){if(!e||!this.integrationManager)return;this.interactionMappings.clear();const t=this.integrationManager.getMappingsByType("interactive");e.forEach(((e,n)=>{if(n<t.length){const o=t[n];this.interactionMappings.set(o.entity,{choice:e,index:n}),console.log(`[Bridge] Mapped "${e}" to ${o.entity}`),this.updateInteractiveVisual(o.entity,e)}}))},StorySceneBridge.prototype.updateInteractiveVisual=function(e,t){if(!this.sceneLoader)return;const n=this.sceneLoader.findInScene(e);if(n&&!n.findByName("ChoiceLabel")){const e=new pc.Entity("ChoiceLabel");e.addComponent("element",{type:"text",text:t,fontSize:16,color:new pc.Color(1,1,1),opacity:.8}),e.setLocalPosition(0,2,0),n.addChild(e),e.addComponent("script");const o=pc.createScript("billboard");o.prototype.update=function(){const e=this.app.root.findByName("SurgeonCamera");e&&this.entity.lookAt(e.getPosition())},pc.registerScript(o,"billboard"),e.script.create("billboard")}},StorySceneBridge.prototype.onSceneInteraction=function(e){console.log(`[Bridge] Scene interaction with: ${e}`);const t=this.interactionMappings.get(e);t?(console.log(`[Bridge] Triggering story choice: "${t.choice}"`),this.app.fire("ui:choiceMade",t.choice)):this.handleUnmappedInteraction(e)},StorySceneBridge.prototype.onCharacterNearby=function(e,t){console.log(`[Bridge] Character nearby: ${e}`,t);const n=this.generateCharacterDescription(t);this.app.fire("story:display",{description:n,choices:this.generateCharacterChoices(t)})},StorySceneBridge.prototype.generateCharacterDescription=function(e){const{role:t,background:n,traits:o}=e;let i=`You encounter a ${t}`;return n&&(i+=` with a ${n} background`),o&&o.length>0&&(i+=`. They appear to be ${o.join(" and ")}`),i+=".",i},StorySceneBridge.prototype.generateCharacterChoices=function(e){const t=[];return e.skills&&e.skills.includes("Diplomacy")&&t.push("Negotiate peacefully"),e.equipment&&e.equipment.includes("Scanner")&&t.push("Ask about their equipment"),t.push("Greet them"),t.push("Walk away"),t},StorySceneBridge.prototype.handleUnmappedInteraction=function(e){if(!this.integrationManager)return;const t=this.integrationManager.getEntityMapping(e);t&&t.gameEvent&&(console.log(`[Bridge] Firing game event: ${t.gameEvent}`),this.app.fire(t.gameEvent,e))},StorySceneBridge.prototype.onChoiceMade=function(e){console.log(`[Bridge] Story choice made: "${e}"`),this.interactionMappings.forEach(((t,n)=>{t.choice===e&&this.showChoiceFeedback(n)}))},StorySceneBridge.prototype.showChoiceFeedback=function(e){if(!this.sceneLoader)return;const t=this.sceneLoader.findInScene(e);if(!t)return;const n=t.getLocalScale().clone();t.setLocalScale(1.2*n.x,1.2*n.y,1.2*n.z),setTimeout((()=>{t.setLocalScale(n)}),200)},StorySceneBridge.prototype.showCurrentState=function(){if(console.log("[Bridge] Current State:"),console.log("==================="),console.log(`Story Location: ${this.currentStoryLocation}`),console.log(`Active Mappings: ${this.interactionMappings.size}`),this.sceneLoader){const e=this.sceneLoader.getSceneStats();console.log(`Scene Loaded: ${e.loaded}`),e.loaded&&(console.log(`- Entities: ${e.entityCount}`),console.log(`- Characters: ${e.characters.length}`),console.log(`- Interactives: ${e.interactives.length}`))}console.log("===================")},StorySceneBridge.prototype.showMappings=function(){console.log("[Bridge] Current Interaction Mappings:"),console.log("===================================="),this.interactionMappings.forEach(((e,t)=>{console.log(`${t} -> "${e.choice}"`)})),console.log("====================================")},StorySceneBridge.prototype.testInteraction=function(){console.log("[Bridge] Testing first mapped interaction...");const e=this.interactionMappings.entries().next().value;if(e){const[t,n]=e;console.log(`[Bridge] Simulating interaction with ${t}`),this.onSceneInteraction(t)}else console.log("[Bridge] No mappings available to test")};var SceneLoader=pc.createScript("sceneLoader");SceneLoader.attributes.add("sceneSource",{type:"string",enum:[{url:"URL"},{asset:"Asset"},{text:"Text Input"}],default:"url",title:"Scene Source Type"}),SceneLoader.attributes.add("sceneUrl",{type:"string",default:"",title:"Scene URL",description:"URL to fetch dynamic scene from"}),SceneLoader.attributes.add("sceneAsset",{type:"asset",assetType:"text",title:"Scene Asset",description:"Text asset containing scene code"}),SceneLoader.attributes.add("autoLoad",{type:"boolean",default:!1,title:"Auto Load on Start"}),SceneLoader.prototype.initialize=function(){this.currentSceneRoot=null,this.preservedEntities=new Set,this.app.on("scene:load",this.loadScene,this),this.app.on("scene:unload",this.unloadCurrentScene,this),this.app.on("scene:reload",this.reloadScene,this),this.setupDebugUI(),this.autoLoad&&this.loadScene(),console.log("SceneLoader initialized. Commands:"),console.log("- Press L to load dynamic scene"),console.log("- Press U to unload dynamic scene"),console.log("- Press R to reload scene")},SceneLoader.prototype.setupDebugUI=function(){this.app.keyboard.on(pc.EVENT_KEYDOWN,(function(e){switch(e.key){case pc.KEY_L:console.log("[SceneLoader] Loading dynamic scene..."),this.loadScene();break;case pc.KEY_U:console.log("[SceneLoader] Unloading dynamic scene..."),this.unloadCurrentScene();break;case pc.KEY_R:console.log("[SceneLoader] Reloading scene..."),this.reloadScene()}}),this)},SceneLoader.prototype.loadScene=function(e){this.unloadCurrentScene();let t="";if(e&&"string"==typeof e)t=e;else switch(this.sceneSource){case"url":return void this.loadFromUrl(this.sceneUrl);case"asset":if(!this.sceneAsset||!this.sceneAsset.resource)return void console.error("[SceneLoader] Scene asset not found");t=this.sceneAsset.resource;break;case"text":t=this._textSceneCode||""}t&&this.executeSceneCode(t)},SceneLoader.prototype.loadFromUrl=function(e){e?fetch(e).then((e=>e.text())).then((e=>{console.log("[SceneLoader] Scene loaded from URL"),this.executeSceneCode(e)})).catch((e=>{console.error("[SceneLoader] Failed to load scene from URL:",e)})):console.error("[SceneLoader] No URL specified")},SceneLoader.prototype.executeSceneCode=function(e){console.log("[SceneLoader] Executing scene code..."),this.currentSceneRoot=new pc.Entity("DynamicSceneRoot"),this.app.root.addChild(this.currentSceneRoot);const t={pc:pc,app:this.app,sceneRoot:this.currentSceneRoot,_originalAddChild:this.app.root.addChild.bind(this.app.root)},n=`\n (function() {\n // Store original app.root.addChild\n const originalAddChild = app.root.addChild.bind(app.root);\n \n // Override to add to scene root instead\n app.root.addChild = function(entity) {\n // Check if this is a preserved entity\n if (entity.tags.has('preserve') || \n entity.name === 'SurgeonCamera' || \n entity.name === 'UIScreen') {\n originalAddChild(entity);\n } else {\n sceneRoot.addChild(entity);\n }\n };\n \n // Execute the scene code\n ${e}\n \n // Restore original function\n app.root.addChild = originalAddChild;\n \n // Post-process the scene\n app.fire('scene:loaded', sceneRoot);\n })();\n `;try{new Function(...Object.keys(t),n)(...Object.values(t)),console.log("[SceneLoader] Scene loaded successfully"),this.integrateScene()}catch(e){console.error("[SceneLoader] Failed to execute scene code:",e),this.currentSceneRoot&&(this.currentSceneRoot.destroy(),this.currentSceneRoot=null)}},SceneLoader.prototype.integrateScene=function(){if(!this.currentSceneRoot)return;console.log("[SceneLoader] Integrating dynamic scene...");this.currentSceneRoot.findComponents("script").forEach((e=>{const t=e.entity;t.tags.has("interactive")&&(t.script.has("interactionController")||console.log(`[SceneLoader] Adding interactionController to ${t.name}`)),t.tags.has("character")&&console.log(`[SceneLoader] Found character: ${t.name}`)})),this.resolveConflicts(),this.app.fire("scene:integrated",this.currentSceneRoot)},SceneLoader.prototype.resolveConflicts=function(){this.currentSceneRoot.findComponents("camera").forEach((e=>{console.log(`[SceneLoader] Disabling dynamic camera: ${e.entity.name}`),e.enabled=!1}));const e=this.currentSceneRoot.findComponents("light");e.length>0&&console.log(`[SceneLoader] Found ${e.length} dynamic lights`)},SceneLoader.prototype.unloadCurrentScene=function(){this.currentSceneRoot&&(console.log("[SceneLoader] Unloading current scene..."),this.currentSceneRoot.destroy(),this.currentSceneRoot=null,this.app.fire("scene:unloaded"))},SceneLoader.prototype.reloadScene=function(){console.log("[SceneLoader] Reloading scene..."),this.loadScene()},SceneLoader.prototype.setTextScene=function(e){this._textSceneCode=e},SceneLoader.prototype.getSceneRoot=function(){return this.currentSceneRoot},SceneLoader.prototype.findInScene=function(e){return this.currentSceneRoot?this.currentSceneRoot.findByName(e):null},SceneLoader.prototype.getSceneStats=function(){if(!this.currentSceneRoot)return{loaded:!1};const e={loaded:!0,entityCount:0,characters:[],interactives:[],scripts:[]},processEntity=t=>{e.entityCount++,t.tags.has("character")&&e.characters.push({name:t.name,tags:Array.from(t.tags._list)}),t.tags.has("interactive")&&e.interactives.push({name:t.name,tags:Array.from(t.tags._list)}),t.script&&t.script._scripts.forEach((n=>{e.scripts.push({entity:t.name,script:n.__scriptType.__name})})),t.children.forEach(processEntity)};return this.currentSceneRoot.children.forEach(processEntity),e};var ControlManager=pc.createScript("controlManager");ControlManager.attributes.add("showControlsOnStart",{type:"boolean",default:!0,title:"Show Controls on Start"}),ControlManager.prototype.initialize=function(){this.modes={GAMEPLAY:"gameplay",UI_INTERACTION:"ui_interaction",DEBUG:"debug"},this.currentMode=this.modes.GAMEPLAY,this.controlMappings={[this.modes.GAMEPLAY]:{W:"move_forward",S:"move_backward",A:"move_left",D:"move_right",Q:"rotate_left",E:"rotate_right",UP:"look_up",DOWN:"look_down",F:"interact",TAB:"toggle_ui",SPACE:"jump"},[this.modes.UI_INTERACTION]:{TAB:"toggle_ui",ESCAPE:"close_ui","1-9":"select_choice"},[this.modes.DEBUG]:{L:"load_scene",U:"unload_scene",R:"reload_scene",C:"show_catalog",I:"show_info",M:"show_mappings",H:"show_help"}},this.activeKeys=new Set,this.blockedKeys=new Set,this.setupInputListeners(),this.app.on("ui:toggled",this.onUIToggled,this),this.showControlsOnStart&&this.showCurrentControls(),console.log("[ControlManager] Initialized - Press F1 for help")},ControlManager.prototype.setupInputListeners=function(){this.app.keyboard.on(pc.EVENT_KEYDOWN,this.onKeyDown,this),this.app.keyboard.on(pc.EVENT_KEYUP,this.onKeyUp,this)},ControlManager.prototype.onKeyDown=function(o){const e=this.getKeyName(o.key);if(o.key===pc.KEY_F1)return o.event.preventDefault(),void this.showFullHelp();if(this.blockedKeys.has(e))return;this.activeKeys.add(e);const t=this.getActionForKey(e);t&&(this.app.fire(`control:${this.currentMode}:${t}`,o),this.app.fire("control:action",{mode:this.currentMode,action:t,key:e}),["TAB","SPACE"].includes(e)&&o.event.preventDefault())},ControlManager.prototype.onKeyUp=function(o){const e=this.getKeyName(o.key);this.activeKeys.delete(e)},ControlManager.prototype.getKeyName=function(o){const e={[pc.KEY_W]:"W",[pc.KEY_A]:"A",[pc.KEY_S]:"S",[pc.KEY_D]:"D",[pc.KEY_Q]:"Q",[pc.KEY_E]:"E",[pc.KEY_F]:"F",[pc.KEY_R]:"R",[pc.KEY_L]:"L",[pc.KEY_U]:"U",[pc.KEY_C]:"C",[pc.KEY_I]:"I",[pc.KEY_M]:"M",[pc.KEY_H]:"H",[pc.KEY_TAB]:"TAB",[pc.KEY_SPACE]:"SPACE",[pc.KEY_ESCAPE]:"ESCAPE",[pc.KEY_UP]:"UP",[pc.KEY_DOWN]:"DOWN",[pc.KEY_LEFT]:"LEFT",[pc.KEY_RIGHT]:"RIGHT",[pc.KEY_F1]:"F1"};for(let o=1;o<=9;o++)e[pc.KEY_1+o-1]=o.toString();return e[o]||"UNKNOWN"},ControlManager.prototype.getActionForKey=function(o){const e=this.controlMappings[this.currentMode];return e[o]?e[o]:this.currentMode===this.modes.UI_INTERACTION&&/^[1-9]$/.test(o)?"select_choice_"+o:null},ControlManager.prototype.setMode=function(o){if(void 0===this.modes[o])return void console.error(`[ControlManager] Unknown mode: ${o}`);const e=this.currentMode;this.currentMode=this.modes[o],console.log(`[ControlManager] Mode changed: ${e} -> ${this.currentMode}`),this.activeKeys.clear(),this.app.fire("control:modeChanged",{previous:e,current:this.currentMode}),this.showCurrentControls()},ControlManager.prototype.onUIToggled=function(o){o?this.blockGameplayControls():this.unblockGameplayControls()},ControlManager.prototype.blockGameplayControls=function(){["W","A","S","D","Q","E","UP","DOWN","SPACE","F"].forEach((o=>this.blockedKeys.add(o))),console.log("[ControlManager] Gameplay controls blocked (UI active)")},ControlManager.prototype.unblockGameplayControls=function(){this.blockedKeys.clear(),console.log("[ControlManager] Gameplay controls unblocked")},ControlManager.prototype.showCurrentControls=function(){console.log(`\n=== CONTROLS (${this.currentMode.toUpperCase()}) ===`);const o=this.controlMappings[this.currentMode];Object.entries({movement:["W","S","A","D"],camera:["Q","E","UP","DOWN"],interaction:["F","TAB"],debug:["L","U","R","C","I","M","H"]}).forEach((([e,t])=>{const n=t.filter((e=>o[e]));n.length>0&&(console.log(`\n${e.toUpperCase()}:`),n.forEach((e=>{console.log(` ${e} - ${o[e].replace(/_/g," ")}`)})))})),this.blockedKeys.size>0&&console.log("\nBLOCKED: "+Array.from(this.blockedKeys).join(", ")),console.log("\nPress F1 for full help"),console.log("===================\n")},ControlManager.prototype.showFullHelp=function(){console.log("\n=== COMPLETE CONTROL REFERENCE ==="),console.log("\nGAMEPLAY MODE:"),console.log(" Movement: WASD"),console.log(" Camera: Q/E (rotate), Arrow Keys (pitch)"),console.log(" Interact: F (with objects)"),console.log(" UI: TAB (toggle story panel)"),console.log("\nUI INTERACTION MODE:"),console.log(" TAB - Close UI and return to game"),console.log(" 1-9 - Select story choices"),console.log(" ESC - Close UI"),console.log("\nDEBUG MODE (when implemented):"),console.log(" L - Load dynamic scene"),console.log(" U - Unload scene"),console.log(" R - Reload scene"),console.log(" C - Show scene catalog"),console.log(" I - Show current info"),console.log(" M - Show mappings"),console.log("\nCURRENT STATE:"),console.log(` Mode: ${this.currentMode}`),console.log(` Active Keys: ${Array.from(this.activeKeys).join(", ")||"none"}`),console.log(` Blocked Keys: ${Array.from(this.blockedKeys).join(", ")||"none"}`),console.log("================================\n")},ControlManager.prototype.isKeyActive=function(o){return this.activeKeys.has(o)},ControlManager.prototype.isActionActive=function(o){for(const e of this.activeKeys)if(this.getActionForKey(e)===o)return!0;return!1},ControlManager.prototype.blockKey=function(o){this.blockedKeys.add(o)},ControlManager.prototype.unblockKey=function(o){this.blockedKeys.delete(o)},ControlManager.prototype.getCurrentMode=function(){return this.currentMode};var UiController=pc.createScript("uiController");UiController.attributes.add("descriptionElement",{type:"entity",title:"Description Text Entity"}),UiController.attributes.add("choicesContainer",{type:"entity",title:"Choices Container Entity"}),UiController.attributes.add("choiceButtonTemplate",{type:"asset",assetType:"template",title:"Choice Button Template"}),UiController.attributes.add("uiPanel",{type:"entity",title:"UI Panel Entity",description:"The main panel that contains all UI elements"}),UiController.prototype.initialize=function(){this.app.on("story:display",this.onDisplay,this),console.log("UiController: Initialized and listening for 'story:display' events."),this.isVisible=!0,this.setupToggleControls(),this.setupTextWrapping(),this.validateSetup(),console.log("=== UI CONTROLS ==="),console.log("Press TAB to toggle story UI"),console.log("Press H to show/hide this help"),console.log("=================="),this.app.fire("ui:ready"),console.log("UiController: Fired 'ui:ready' event.")},UiController.prototype.setupToggleControls=function(){this.app.keyboard.on(pc.EVENT_KEYDOWN,(function(e){switch(e.key){case pc.KEY_TAB:e.event.preventDefault(),this.toggleUI();break;case pc.KEY_H:this.showHelp()}}),this)},UiController.prototype.setupTextWrapping=function(){this.descriptionElement&&this.descriptionElement.element&&(this.descriptionElement.element.autoWidth=!1,this.descriptionElement.element.wrapLines=!0,this.descriptionElement.element.width=600,this.descriptionElement.element.fontSize||(this.descriptionElement.element.fontSize=16),this.descriptionElement.element.alignment=pc.Vec2.ZERO,this.descriptionElement.element.margin=new pc.Vec4(20,20,20,20),console.log("UiController: Text wrapping configured"))},UiController.prototype.toggleUI=function(){this.isVisible=!this.isVisible,this.uiPanel?this.uiPanel.enabled=this.isVisible:(this.descriptionElement&&(this.descriptionElement.enabled=this.isVisible),this.choicesContainer&&(this.choicesContainer.enabled=this.isVisible)),console.log("[UI] Story UI "+(this.isVisible?"shown":"hidden")),this.app.fire("ui:toggled",this.isVisible)},UiController.prototype.showHelp=function(){console.log("\n=== UI HELP ==="),console.log("TAB - Toggle story UI visibility"),console.log("H - Show this help"),console.log("F - Interact with objects (when UI is hidden)"),console.log("WASD - Move"),console.log("Q/E - Rotate camera"),console.log("===============\n")},UiController.prototype.validateSetup=function(){console.log("UiController: Validating setup..."),this.descriptionElement||console.error("UiController VALIDATION ERROR: 'Description Text Entity' is not assigned in the editor!"),this.choicesContainer||console.error("UiController VALIDATION ERROR: 'Choices Container Entity' is not assigned in the editor!"),this.choiceButtonTemplate?"template"!==this.choiceButtonTemplate.type&&console.error("UiController VALIDATION ERROR: The asset assigned to 'Choice Button Template' must be a Template asset."):console.error("UiController VALIDATION ERROR: 'Choice Button Template' asset is not assigned in the editor!"),this.uiPanel||console.warn("UiController: 'UI Panel Entity' not assigned. Toggle will affect individual elements.")},UiController.prototype.onDisplay=function(e){console.log("UiController: Received 'story:display' event."),e?(this.isVisible||this.toggleUI(),this.updateDescription(e.description),this.updateChoices(e.choices)):console.error("UiController: Received event but data was null or undefined.")},UiController.prototype.updateDescription=function(e){this.descriptionElement&&this.descriptionElement.element&&(this.descriptionElement.element.text=e||"Description text is missing.",this.descriptionElement.element._text.width=this.descriptionElement.element.width,this.descriptionElement.element._text.autoFitWidth=!1,this.descriptionElement.element._text.wrapLines=!0)},UiController.prototype.updateChoices=function(e){if(this.choicesContainer){for(;this.choicesContainer.children.length>0;)this.choicesContainer.children[0].destroy();e&&e.length>0&&e.forEach(((e,t)=>{this.createChoiceButton(e,t)}))}},UiController.prototype.createChoiceButton=function(e,t){if(this.choiceButtonTemplate&&this.choiceButtonTemplate.resource){var i=this.choiceButtonTemplate.resource.instantiate();this.choicesContainer.addChild(i);var o=i.element,n=t%2,s=Math.floor(t/2);o.width=280,o.height=50;var l=0===n?10:-290,r=-(60*s+20);0===n?(o.anchor=new pc.Vec4(0,1,0,1),o.pivot=new pc.Vec2(0,1)):(o.anchor=new pc.Vec4(1,1,1,1),o.pivot=new pc.Vec2(1,1)),i.setLocalPosition(l,r,0);var c=i.findByName("ButtonText");c&&c.element&&(c.element.text=e,c.element.wrapLines=!0,c.element.width=260,c.element.fontSize=14,c.element.alignment=new pc.Vec2(.5,.5)),i.button&&(i.button.on("click",(function(){console.log(`[UI] Choice selected: "${e}"`),this.app.fire("ui:choiceMade",e)}),this),i.button.on("mouseenter",(function(){i.setLocalScale(1.05,1.05,1)})),i.button.on("mouseleave",(function(){i.setLocalScale(1,1,1)})))}},UiController.prototype.show=function(){this.isVisible||this.toggleUI()},UiController.prototype.hide=function(){this.isVisible&&this.toggleUI()},UiController.prototype.isUIVisible=function(){return this.isVisible};var UiDebugFix=pc.createScript("uiDebugFix");UiDebugFix.prototype.initialize=function(){console.log("=== UI DEBUG STARTING ==="),setTimeout((()=>{this.debugAndFix()}),100),this.app.on("story:display",(()=>{setTimeout((()=>{this.debugAndFix()}),100)}))},UiDebugFix.prototype.debugAndFix=function(){console.log("\n=== CHECKING UI ELEMENTS ===");const e=this.app.root.findByName("DescriptionText");e&&e.element?(console.log("DescriptionText found!"),console.log("- Current width:",e.element.width),console.log("- Auto width:",e.element.autoWidth),console.log("- Wrap lines:",e.element.wrapLines),console.log("- Font size:",e.element.fontSize),console.log("- Text content:",e.element.text?.substring(0,50)+"..."),console.log("\nFIXING TEXT SETTINGS..."),e.element.autoWidth=!1,e.element.width=1400,e.element.wrapLines=!0,e.element.fontSize=20,e.element.lineHeight=30,e.element.anchor=e.element.anchor,e.element._calculateSize(),console.log("Text settings fixed!")):console.error("DescriptionText NOT FOUND!");const o=this.app.root.findByName("ChoicesContainer");if(o){console.log("\nChoicesContainer found!"),console.log("- Number of buttons:",o.children.length),console.log("- Container width:",o.element?.width||"No element component");const e=o.children;if(e.length>0){console.log("\nFIXING BUTTON POSITIONS...");const o=350,n=60,t=20,l=e.length,i=-(o*l+t*(l-1))/2+o/2;e.forEach(((e,l)=>{e.element&&(e.element.width=o,e.element.height=n,e.enabled=!0,console.log(`- Button ${l+1}: "${e.name}"`));const s=i+l*(o+t);e.setLocalPosition(s,0,0);const c=e.findByName("ButtonText");c&&c.element&&(c.element.width=o-30,c.element.wrapLines=!0,console.log(` Text: "${c.element.text}"`))})),console.log("Button positions fixed!")}else console.log("No buttons found in container!")}else console.error("ChoicesContainer NOT FOUND!");const n=this.app.root.findByName("GameUIPanel");n&&(console.log("\nGameUIPanel found!"),n.element&&(console.log("- Width:",n.element.width),console.log("- Height:",n.element.height),console.log("- Type:",n.element.type))),console.log("\n=== DEBUG COMPLETE ===\n")},UiDebugFix.prototype.update=function(e){if(this.app.keyboard.wasPressed(pc.KEY_X)&&(console.log("Manual fix triggered!"),this.debugAndFix()),this.app.keyboard.wasPressed(pc.KEY_V)){const e=this.app.root.findByName("ChoicesContainer");e&&e.children.forEach(((e,o)=>{e.enabled=!0,console.log(`Button ${o} enabled:`,e.name)}))}};var SimpleSceneLoader=pc.createScript("simpleSceneLoader");SimpleSceneLoader.prototype.initialize=function(){console.log("=== SCENE LOADER READY ==="),console.log("Press 1 to load a test scene"),console.log("Press 2 to unload test scene"),console.log("========================"),this.testSceneRoot=null,this.app.keyboard.on(pc.EVENT_KEYDOWN,this.onKeyDown,this)},SimpleSceneLoader.prototype.onKeyDown=function(e){e.key===pc.KEY_1?this.loadTestScene():e.key===pc.KEY_2&&this.unloadTestScene()},SimpleSceneLoader.prototype.loadTestScene=function(){if(this.testSceneRoot)console.log("Test scene already loaded");else{console.log("Loading test scene..."),this.testSceneRoot=new pc.Entity("TestSceneRoot"),this.app.root.addChild(this.testSceneRoot);var e=new pc.Entity("TestCube");e.addComponent("render",{type:"box"}),e.setPosition(3,1,-3),e.setLocalScale(.5,2,.5);var t=new pc.StandardMaterial;t.diffuse.set(0,.5,1),t.emissive.set(0,.2,.5),t.update(),e.render.material=t,e.addComponent("script"),e.script.create("rotator",{attributes:{speed:30}}),this.testSceneRoot.addChild(e),console.log("Test scene loaded!")}},SimpleSceneLoader.prototype.unloadTestScene=function(){this.testSceneRoot&&(this.testSceneRoot.destroy(),this.testSceneRoot=null,console.log("Test scene unloaded"))};var Rotator=pc.createScript("rotator");Rotator.attributes.add("speed",{type:"number",default:30}),Rotator.prototype.update=function(e){this.entity.rotate(0,this.speed*e,0)};var HuggingFaceSceneLoader=pc.createScript("huggingFaceSceneLoader");HuggingFaceSceneLoader.prototype.initialize=function(){this.baseUrl="https://huggingface.co/datasets/KwabsHug/playcanvas-scenes-experiment/resolve/main/",this.currentSceneRoot=null,this.catalog=null,this.catalogLoaded=!1,console.log("=== HF SCENE LOADER READY ==="),console.log("Dataset: KwabsHug/playcanvas-scenes-experiment"),console.log("Press C to load scene catalog"),console.log("Press 1-9 to load scenes from catalog"),console.log("Press 0 to unload current scene"),console.log("============================="),this.app.keyboard.on(pc.EVENT_KEYDOWN,this.onKeyDown,this),this.loadCatalog()},HuggingFaceSceneLoader.prototype.onKeyDown=function(e){if(e.key>=pc.KEY_1&&e.key<=pc.KEY_9){const o=e.key-pc.KEY_1;this.loadSceneByIndex(o)}else switch(e.key){case pc.KEY_C:this.loadCatalog();break;case pc.KEY_0:this.unloadCurrentScene()}},HuggingFaceSceneLoader.prototype.loadCatalog=async function(){const e=this.baseUrl+"scene_catalog.json";console.log("Loading scene catalog...");try{const o=await fetch(e);if(!o.ok)throw new Error(`HTTP ${o.status}`);this.catalog=await o.json(),this.catalogLoaded=!0,console.log("\n=== AVAILABLE SCENES ==="),this.catalog.scenes.forEach(((e,o)=>{console.log(`[${o+1}] ${e.name}`),console.log(` ${e.description}`)})),console.log("Press 1-9 to load a scene"),console.log("Press 0 to unload"),console.log("======================\n")}catch(e){console.error("Failed to load catalog:",e),console.log("Using fallback scene list..."),this.catalog={scenes:[{name:"Test Crystal",file:"scenes/test_scene.js",description:"Simple floating crystal"},{name:"Sci-Fi Environment",file:"scenes/scifi_scene.js",description:"Futuristic scene with holograms"},{name:"Medical Lab",file:"scenes/medical_lab_scene.js",description:"Additional medical equipment"}]},this.catalogLoaded=!0}},HuggingFaceSceneLoader.prototype.loadSceneByIndex=function(e){if(!this.catalogLoaded||!this.catalog)return void console.log("Catalog not loaded yet. Press C to load catalog.");if(e>=this.catalog.scenes.length)return void console.log(`No scene at index ${e+1}`);const o=this.catalog.scenes[e];console.log(`Loading scene: ${o.name}`),this.loadScene(o.file)},HuggingFaceSceneLoader.prototype.loadScene=async function(e){this.unloadCurrentScene();const o=this.baseUrl+e;console.log(`Loading scene from: ${o}`);try{const e=await fetch(o);if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);const n=await e.text();console.log(`Loaded ${n.length} bytes of scene code`),this.currentSceneRoot=new pc.Entity("DynamicSceneRoot"),this.app.root.addChild(this.currentSceneRoot);const t=`\n (function() {\n // Store original addChild\n const originalAddChild = app.root.addChild.bind(app.root);\n \n // Redirect entities to scene root\n app.root.addChild = function(entity) {\n // Keep cameras and UI at root level\n if (entity.camera || entity.screen || entity.name === 'SurgeonCamera') {\n originalAddChild(entity);\n } else {\n sceneRoot.addChild(entity);\n }\n };\n \n try {\n ${n}\n } catch (error) {\n console.error('Scene execution error:', error);\n }\n \n // Restore original function\n app.root.addChild = originalAddChild;\n })();\n `;new Function("app","pc","sceneRoot",t)(this.app,pc,this.currentSceneRoot),console.log("Scene loaded successfully!"),this.postProcessScene()}catch(e){console.error("Failed to load scene:",e)}},HuggingFaceSceneLoader.prototype.postProcessScene=function(){if(!this.currentSceneRoot)return;this.currentSceneRoot.findComponents("camera").forEach((e=>{console.log(`Disabling camera: ${e.entity.name}`),e.enabled=!1}));const e=this.currentSceneRoot.findComponents("light");console.log(`Scene contains ${e.length} lights`)},HuggingFaceSceneLoader.prototype.unloadCurrentScene=function(){if(this.currentSceneRoot){const e=this.currentSceneRoot.name;this.currentSceneRoot.destroy(),this.currentSceneRoot=null,console.log(`Scene unloaded: ${e}`)}}; |