Skip to content

Commit

Permalink
Slight copy refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
3b1b committed Apr 23, 2022
1 parent 587bc4d commit 902c2c0
Showing 1 changed file with 21 additions and 18 deletions.
39 changes: 21 additions & 18 deletions manimlib/mobject/mobject.py
Expand Up @@ -500,46 +500,49 @@ def deserialize(self, data: bytes):
self.become(pickle.loads(data))
return self

def deepcopy(self):
try:
# Often faster than deepcopy
return pickle.loads(pickle.dumps(self))
except AttributeError:
return copy.deepcopy(self)

@stash_mobject_pointers
def copy(self, deep: bool = False):
if deep:
try:
# Often faster than deepcopy
return pickle.loads(pickle.dumps(self))
except AttributeError:
return copy.deepcopy(self)
return self.deepcopy()

result = copy.copy(self)

# The line above is only a shallow copy, so the internal
# data which are numpyu arrays or other mobjects still
# need to be further copied.
result.data = dict(self.data)
for key in result.data:
result.data[key] = result.data[key].copy()

result.uniforms = dict(self.uniforms)
for key in result.uniforms:
if isinstance(result.uniforms[key], np.ndarray):
result.uniforms[key] = result.uniforms[key].copy()
result.data = {
key: np.array(value)
for key, value in self.data.items()
}
result.uniforms = {
key: np.array(value)
for key, value in self.uniforms.items()
}

result.submobjects = []
result.add(*(sm.copy() for sm in self.submobjects))
result.match_updaters(self)

family = self.get_family()
for attr, value in list(self.__dict__.items()):
if isinstance(value, Mobject) and value in family and value is not self:
setattr(result, attr, result.family[self.family.index(value)])
if isinstance(value, Mobject) and value is not self:
if value in family:
setattr(result, attr, result.family[self.family.index(value)])
else:
setattr(result, attr, value.copy())
if isinstance(value, np.ndarray):
setattr(result, attr, value.copy())
if isinstance(value, ShaderWrapper):
setattr(result, attr, value.copy())
return result

def deepcopy(self):
return self.copy(deep=True)

def generate_target(self, use_deepcopy: bool = False):
self.target = self.copy(deep=use_deepcopy)
self.target.saved_state = self.saved_state
Expand Down

0 comments on commit 902c2c0

Please sign in to comment.