Raymarching Shader - Converting camera position to object space

Hello - I’m playing around with setting up a raymarching shader in Three.js based on a tutorial from The Art of Code (Martijn) on Youtube: Writing a ray marcher in Unity - YouTube

The tutorial is for Unity, but the same concept can be applied to Three.js, and I’ve set up a working example in this pen: https://codepen.io/sampstrong/pen/mdGjxKR

The main issue I’m having is the camera’s position (ray origin) is in world coordinates, and the raymarched sphere is in the object’s coordinates. This means that everything looks correct when the object is at the world origin, but starts to warp and look strange if it is moved away from the origin. You can test this by shifting the cube around in the example.

I found another post that solves this issue by converting the camera’s coordinates outside the shader and passing them in as a uniform, which I’ve been able to recreate successfully, however, I’m curious if it’s possible to achieve the same result through matrix multiplication within the vertex shader. Post: Three.js Custom Shader Object Coordinate

Based on Martijn’s video, he is able to achieve this (starts to talk about this around 20:32), and it seems like a more elegant solution, but I have been unable to make this work in three.js.

I’ve tried multiplying almost every possible combination of matrices with the camera’s position using the built in uniform’s and attributes, but I haven’t had any luck. If anyone could shed some light on the proper way to do this, or if you know the reason why it must be done outside the shader and passed in as a uniform, I would greatly appreciate it!

Here are some examples of the things I’ve tried:

vCamPos = (modelMatrix * vec4(cameraPosition, 1.0)).xyz;

vCamPos = (vec4(cameraPosition, 1.0) * modelMatrix)).xyz;

vCamPos = (viewMatrix * vec4(cameraPosition, 1.0)).xyz;

vCamPos = (vec4(cameraPosition, 1.0) * viewMatrix).xyz;

You have a u_camPos uniform in your code! Use it instead of vCamPos without any transformations!

Right - I understand that’s one way to do it, as stated in the original post. My question is if it’s possible to achieve this within the shader to avoid having to create and pass in this value as a uniform every time.

Based on some additional research I’ve done, I think that maybe the matrix I need to accomplish this is just not available as a built in attribute as it is in Unity with ‘unity_WorldToObject’. It sounds like I maybe need the inverse of the modelMatrix, but I’m still looking for confirmation from someone with a bit more depth of knowledge in this area.